summaryrefslogtreecommitdiffstats
path: root/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
blob: f7c175c0ca2ed45a74244d9f6f2b1adaa50afa83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
{
   "name": "${it.env.name}",
   "description": "OpenSource-${it.env.name}",
   "json_class": "Chef::Environment",
   "chef_type": "environment",

   "default_attributes": {
      "disableHttp": false,
      "CS_VIP": "sdc-cs",
      "BE_VIP": "sdc-BE",
      "ONBOARDING_BE_VIP": "sdc-onboard-BE",
      "FE_VIP": "sdc-FE",
      "interfaces": {
         "application": "eth0",
         "private": "eth1"
      },
      "ECompP": {
         "ecomp_rest_url": "http://portal.api.simpledemo.onap.org:8989/ONAPPORTAL/auxapi",
         "ecomp_redirect_url": "http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/login.htm",
         "cipher_key": "AGLDdG4D04BKm2IxIWEr8o==",
         "portal_user": "Ipwxi2oLvDxctMA1royaRw1W0jhucLx+grHzci3ePIA=",
         "portal_pass": "j85yNhyIs7zKYbR1VlwEfNhS6b7Om4l0Gx5O8931sCI=",
         "portal_app_name": "Ipwxi2oLvDxctMA1royaRw1W0jhucLx+grHzci3ePIA="
      },
      "UEB": {
         "PublicKey": "iPIxkpAMI8qTcQj8",
         "SecretKey": "Ehq3WyT4bkif4zwgEbvshGal",
         "fqdn": ["10.0.11.1", "10.0.11.1"]
      },
      "Nodes": {
         "CS": [
            "sdc-cs"
         ],
         "BE":            "sdc-BE",
         "ONBOARDING_BE": "sdc-onboard-BE",
         "FE":            "sdc-FE"
      },
      "VnfRepo": {
         "vnfRepoPort": "8702",
         "vnfRepoHost": "10.0.14.1"
      }
   },
   "override_attributes": {
      "FE": {
         "http_port": "8181",
         "https_port": "9443",
         "domain_name": "sdc"
      },
      "BE": {
         "http_port": "8080",
         "https_port": "8443",
         "domain_name": "sdc"
      },
      "ONBOARDING_BE": {
         "http_port": "8081",
         "https_port": "8445",
         "domain_name": "sdc",
         "catalog_notification_url": "%s://%s:%s/sdc2/rest/v1/catalog/notif/vsp/"
      },
      "cassandra": {
         "cassandra_port": 9042,
         "concurrent_reads": "32",
         "num_tokens": "256",
         "data_dir": "/var/lib/cassandra/data",
         "hinted_handoff_enabled": "true",
         "cassandra_user": "${it.sdc.user}",
         "cassandra_password": "${it.sdc.password}",
         "concurrent_writes": "32",
         "cluster_name": "${it.sdc.cluster.name}",
         "datacenter_name": "${it.sdc.cluster.name}",
         "multithreaded_compaction": "false",
         "cache_dir": "/var/lib/cassandra/saved_caches",
         "log_file": "/var/lib/cassandra/log/system.log",
         "phi_convict_threshold": "8",
         "commitlog_dir": "/var/lib/cassandra/commitlog",
         "socket_read_timeout": "40000",
         "socket_connect_timeout": "40000",
         "janusgraph_connection_timeout": "20000",
         "replication_factor": "1"
      },
      "DMAAP": {
         "consumer": {
            "host": "dcae-mrtr.com:3905",
            "topic": "operationalEnvironmentEvent",
            "serviceName": "dcae-mrtr.com:3905/events",
            "environment": "${it.env.name}",
/*-
 * ============LICENSE_START=======================================================
 * ONAP-PDP-REST
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.policy.pdp.rest.api.services;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.onap.policy.api.PolicyException;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pdp.rest.config.PDPApiAuth;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;

import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;

public class PAPServices {
    private static final String SUCCESS = "success";
    private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class
            .getName());
    
    private int responseCode = 0;
    private static String environment = "DEVL";
    private static Boolean junit = false;
    private static List<String> paps = null;
    private static final Object papResourceLock = new Object();
    private String operation = null;
    private String requestMethod = null;
    private String encoding = null; 

    public PAPServices() {
        environment = PDPApiAuth.getEnvironment();
        if(paps == null){
            synchronized (papResourceLock) {
                String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
                if(urlList == null){
                    urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
                }
                paps = Arrays.asList(urlList.split(","));
            }
        }
    }
    
    private String getPAPEncoding(){
        if(encoding  == null){
            String userID =  XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
            String pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
            Base64.Encoder encoder = Base64.getEncoder();
            encoding =  encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8));
        }
        return encoding;
    }
    
    private void rotatePAPList(){
        synchronized (papResourceLock) {
            Collections.rotate(paps, -1);
        }
    }
    
    private String getPAP(){
        String result;
        synchronized (papResourceLock) {
            result = paps.get(0);
        }
        return result;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public Object callPAP(Object content, String[] parameters, UUID requestID,
            String clientScope) throws PolicyException {
        String response = null;
        HttpURLConnection connection = null;
        responseCode = 0;
        // Checking for the available PAPs is done during the first Request and
        // the List is going to have the connected PAP as first element.
        // This makes it Real-Time to change the list depending on their
        // availability.
        if (paps == null || paps.isEmpty()) {
            String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.";
            LOGGER.error(message);
            throw new PolicyException(message);
        }
        int papsCount = 0;
        boolean connected = false;
        while (papsCount < paps.size()) {
            try {
                String fullURL = getPAP();
                fullURL = checkParameter(parameters, fullURL);
                URL url = new URL(fullURL);
                LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---");
                // Open the connection
                connection = (HttpURLConnection) url.openConnection();
                // Setting Content-Type
                connection.setRequestProperty("Content-Type","application/json");
                // Adding Authorization
                connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding());
                connection.setRequestProperty("Environment", environment);
                connection.setRequestProperty("ClientScope", clientScope);
                // set the method and headers
                connection.setRequestMethod(requestMethod);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(false);
                connection.setDoOutput(true);
                connection.setDoInput(true);
                // Adding RequestID
                if (requestID == null) {
                    requestID = UUID.randomUUID();
                    LOGGER.info("No request ID provided, sending generated ID: "
                            + requestID.toString());
                } else {
                    LOGGER.info("Using provided request ID: "
                            + requestID.toString());
                }
                connection.setRequestProperty("X-ECOMP-RequestID",
                        requestID.toString());
                if (content != null && (content instanceof InputStream)) {
                    // send current configuration
                    try (OutputStream os = connection.getOutputStream()) {
                        int count = IOUtils.copy((InputStream) content, os);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("copied to output, bytes=" + count);
                        }
                    }
                } else if(content != null){
                    // the content is an object to be encoded in JSON
                    ObjectMapper mapper = new ObjectMapper();
                    if (!junit) {
                        mapper.writeValue(connection.getOutputStream(),
                                content);
                    }
                }
                // DO the connect
                connection.connect();
                responseCode = connection.getResponseCode();
                // If Connected to PAP then break from the loop and continue
                // with the Request
                if (connection.getResponseCode() > 0 || junit) {
                    connected = true;
                    break;
                } else {
                    LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : "  + connection.getResponseCode());
                    rotatePAPList();
                }
            } catch (Exception e) {
                // This means that the PAP is not working
                if (junit) {
                    connected = true;
                    break;
                }
                LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
                        + "PAP connection Error : " + e);
                rotatePAPList();
            }
            papsCount++;
        }
        if (connected) {
            // Read the Response
            LOGGER.debug("connected to the PAP : " + getPAP());
            LOGGER.debug("--- Response: ---");
            if(connection != null){
            	Map<String, List<String>> headers = connection.getHeaderFields();
            	for (String key : headers.keySet()) {
            		LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
            	}

            	try {
            		response = checkResponse(connection, requestID);
            	} catch (IOException e) {
            		LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
            		response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e;
            		throw new PolicyException(
            				XACMLErrorConstants.ERROR_SYSTEM_ERROR
            				+ "Decoding the result ", e);
            	}
            	if (junit) {
            		response = SUCCESS;
            	}
            }else{
            	response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null";
            }
            return response;
        } else {
            response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
                    + "Unable to get valid response from PAP(s) " + paps;
            return response;
        }
    }
    
    public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) {
        String version = null;
        HttpURLConnection connection = null;
        String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName};
        if (paps == null || paps.isEmpty()) {
            LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
        }else {
            int papsCount = 0;
            boolean connected = false;
            while (papsCount < paps.size()) {
                try {
                    String fullURL = getPAP();
                    if (parameters != null && parameters.length > 0) {
                        String queryString = "";
                        for (String p : parameters) {
                            queryString += "&" + p;
                        }
                        fullURL += "?" + queryString.substring(1);
                    }

                    URL url = new URL (fullURL);

                    //Open the connection
                    connection = (HttpURLConnection)url.openConnection();

                    // Setting Content-Type
                    connection.setRequestProperty("Content-Type",
                            "application/json");

                    // Adding Authorization
                    connection.setRequestProperty("Authorization", "Basic "
                            + getPAPEncoding());

                    connection.setRequestProperty("Environment", environment);
                    connection.setRequestProperty("ClientScope", clientScope);


                    //set the method and headers
                    connection.setRequestMethod("GET");
                    connection.setUseCaches(false);
                    connection.setInstanceFollowRedirects(false);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());

                    //DO the connect
                    connection.connect();

                    // If Connected to PAP then break from the loop and continue with the Request 
                    if (connection.getResponseCode() > 0) {
                        connected = true;
                        break;

                    } else {
                        LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
                    }
                } catch (Exception e) {
                    // This means that the PAP is not working 
                    LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
                    rotatePAPList();
                }
                papsCount++;
            }

            if (connected) {
                //Read the Response
                LOGGER.debug("connected to the PAP : " + getPAP());
                LOGGER.debug("--- Response: ---");
                Map<String, List<String>> headers = connection.getHeaderFields();
                for (String key : headers.keySet()) {
                    LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
                }
                try {
                    if (connection.getResponseCode() == 200) {
                        // Check for successful creation of policy
                        version = connection.getHeaderField("version");
                        LOGGER.debug("ActiveVersion from the Header: " + version);
                    } else if (connection.getResponseCode() == 403) {
                        LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " 
                                + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
                        version = "pe100";
                    } else if (connection.getResponseCode() == 404) {
                        LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " 
                                + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP");
                        version = "pe300";
                    } else {
                        LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST:  Error occured while getting the version from the PAP. The request may be incorrect.");
                    }
                } catch (IOException e) {
                    LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
                } 
            } else {
                LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
            }   
        }
        return version;
    }
    
    private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException {
        String response = null;
        if (responseCode == 200 || junit) {         
            // Check for successful creation of policy
            String isSuccess = null;
            if (!junit) { // is this a junit test?
                isSuccess = connection.getHeaderField("successMapKey");
                operation = connection.getHeaderField("operation");
            } else {
                isSuccess = SUCCESS;
            }
            if (SUCCESS.equals(isSuccess)) {
                if ("update".equals(operation)) {
                    response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName")
                            + " was successfully updated. ";
                    if (connection.getHeaderField("safetyChecker")!=null) {
                    	response = response 
            					+ "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
            					+ "is potentially in conflict with " + connection.getHeaderField("conflictCLName") 
            					+  " that already exists." + " See detailed information on ClosedLoop Pairs below: "
            					+"\n\n"+connection.getHeaderField("safetyChecker");
                    }
                } else if ("create".equals(operation)) {
                	response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName")
                            + " was successfully created.";
                    if (connection.getHeaderField("safetyChecker")!=null) {
                    	response = response 
            					+ "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
            					+ "is potentially in conflict with " + connection.getHeaderField("conflictCLName") 
            					+  " that already exists. " + "See detailed information on ClosedLoop Pairs below: "
            					+"\n\n"+connection.getHeaderField("safetyChecker");
                    }
                } else if ("delete".equals(operation)) {
                    response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";
                } else if ("import".equals(operation)) {
                    response = "Transaction ID: " + requestID + " --The policy engine import for "+ connection.getHeaderField("service")
                            + " was successfull.";
                } else if ("createDictionary".equals(operation)) {
                    response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!";
                } else if ("updateDictionary".equals(operation)) {
                    response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!";
                } else if ("getDictionary".equals(operation)) {
                    String json =  null;
                    try {
                        
                        //get the json string from the response 
                        InputStream is = connection.getInputStream();
                            
                        // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
                        java.util.Scanner scanner = new java.util.Scanner(is);
                        scanner.useDelimiter("\\A");
                        json =  scanner.hasNext() ? scanner.next() : "";
                        scanner.close();
                        
                    } catch (IOException e1) {
                        LOGGER.error(e1.getMessage() + e1);
                    }
                    response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json;
                } else if ("getMetrics".equals(operation)) {
                	response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics");
                }
                LOGGER.info(response);
            } else {
                String message = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Operation unsuccessful, unable to complete the request!";
                LOGGER.error(message);
                response = message;
            }
        } else if (connection.getResponseCode() == 202) {
            if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) &&
                    "true".equals(connection.getHeaderField("lockdown"))) {
                response = "Transaction ID: "
                        + requestID
                        + " --Policies are locked down, please try again later.";
                LOGGER.warn(response);
            }
        } else if (connection.getResponseCode() == 204) {
            if ("push".equals(connection.getHeaderField("operation"))) {
                response = "Transaction ID: "
                        + requestID
                        + " --Policy '"
                        + connection.getHeaderField("policyId")
                        + "' was successfully pushed to the PDP group '"
                        + connection.getHeaderField("groupId") + "'.";
                LOGGER.info(response);
            }
        } else if (connection.getResponseCode() == 400  && connection.getHeaderField("error") != null) {
        	response = connection.getHeaderField("error");
            LOGGER.error(response);
        } else if (connection.getResponseCode() == 403) {
            response = XACMLErrorConstants.ERROR_PERMISSIONS
                    + "response code of the URL is "
                    + connection.getResponseCode()
                    + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
            LOGGER.error(response);
        } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) {
            if ("unknownGroupId".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + connection.getHeaderField("message")
                        + " Please check the pdpGroup you are requesting to move the policy to.";
                LOGGER.error(response);
            }
        } else if (connection.getResponseCode() == 409  && connection.getHeaderField("error") != null) {
            if ("modelExistsDB".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Import Value Exist Error:  The import value "
                        + connection.getHeaderField("service")
                        + " already exist on the PAP. "
                        + "Please create a new import value.";
            } else if ("policyExists".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Policy Exist Error:  The Policy "
                        + connection.getHeaderField("policyName")
                        + " already exist on the PAP. "
                        + "Please create a new policy or use the update API to modify the existing one.";
            } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Dictionary Item Exist Error:  The Dictionary Item already exist in the database. "
                        + "Please create a new Dictionary Item or use the update API to modify the existing one.";
            } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Group Policy Scope List Exist Error:  The Group Policy Scope List for this Dictionary Item already exist in the database. "
                        + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. "
                        + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
            } else if("PolicyInPDP".equals(connection.getHeaderField("error"))){
            	response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Policy Exist Error:  The Policy trying to be deleted is active in PDP. "
                        + "Active PDP Polcies are not allowed to be deleted from PAP. "
                        + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP.";
            }
            LOGGER.error(response);
        } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) {
            if ("jpautils".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
                        + "Could not create JPAUtils instance on the PAP";
            } else if ("deleteDB".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
                        + "Failed to delete Policy from database.";
            } else if ("deleteFile".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Cannot delete the policy file";
            } else if ("groupUpdate".equals(connection.getHeaderField("error"))) {
                response = connection.getHeaderField("message");
            } else if ("unknown".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_UNKNOWN
                        + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.";
            } else if ("deleteConfig".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Cannot delete the configuration or action body file in specified location.";
            } else if ("missing".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Failed to create value in database because service does match a value in file";
            } else if ("importDB".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Database errors during policy engine import";
            } else if ("policyCopyError".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_PROCESS_FLOW
                        + connection.getHeaderField("message");
            } else if ("addGroupError".equals(connection.getHeaderField("error"))) {
                response = connection.getHeaderField("message");
            } else if ("validation".equals(connection.getHeaderField("error"))){
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Validation errors during policy engine " + connection.getHeaderField("operation") +
                        " for " + connection.getHeaderField("service");
            } else if ("error".equals(connection.getHeaderField("error"))) {
                response = XACMLErrorConstants.ERROR_UNKNOWN
                        + "Could not create or update the policy for and unknown reason";
            }else{
                response = XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "BAD REQUEST:  Error occured while attempting perform this operation.. the request may be incorrect. " + connection.getHeaderField("error");
            }
            LOGGER.error(response);
        } else {
            response = XACMLErrorConstants.ERROR_DATA_ISSUE
                    + "BAD REQUEST:  Error occured while attempting perform this operation.. the request may be incorrect.";
            LOGGER.error(response);
        }
        return response;
    }

    private String checkParameter(String[] parameters, String fullURL) {
        if (parameters != null && parameters.length > 0) {
            String queryString = "";
            for (String p : parameters) {
                queryString += "&" + p;
                if (p.equalsIgnoreCase("operation=post")) {
                    requestMethod = "POST";
                } else if (p.equalsIgnoreCase("operation=delete")) {
                    requestMethod = "DELETE";
                    operation = "delete";
                } else if (p.equalsIgnoreCase("operation=get")) {
                    requestMethod = "GET";
                    operation = "get";
                } else if (p.equalsIgnoreCase("operation=put")||p.equalsIgnoreCase("operation=create")
            		||p.equalsIgnoreCase("operation=update")||p.equalsIgnoreCase("operation=createDictionary")){
                	requestMethod = "PUT";
                    if (p.equalsIgnoreCase("operation=create")) {
                        operation = "create";
                    } else if (p.equalsIgnoreCase("operation=update")) {
                        operation = "update";
                    } else if (p.equalsIgnoreCase("operation=createDictionary")){
						operation = "createDictionary";
					}
                }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){
                	requestMethod = "PUT";
                }
            }
            fullURL += "?" + queryString.substring(1);
        }
        return fullURL;
    }

	public StdPDPPolicy pushPolicy(String policyScope, String filePrefix,
			String policyName, String clientScope, String pdpGroup,
			UUID requestID) throws PolicyException {
		String json = "{ "
				+ "\"apiflag\": \"api\","
				+ "\"policyScope\": \""+policyScope+"\","
				+ "\"filePrefix\": \""+filePrefix+"\","
				+ "\"policyName\": \""+policyName+"\","
				+ "\"clientScope\": \""+clientScope+"\","
				+ "\"pdpGroup\": \""+pdpGroup+"\"}";
        //String response = null;
        HttpURLConnection connection = null;
        responseCode = 0;
        if (paps == null || paps.isEmpty()) {
            String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.";
            LOGGER.error(message);
            throw new PolicyException(message);
        }
        int papsCount = 0;
        boolean connected = false;
        while (papsCount < paps.size()) {
            try {
            	String fullURL = getPAP();
                fullURL = (fullURL.endsWith("/"))? fullURL+"onap/pushPolicy" : fullURL+"/onap/pushPolicy";
                URL url = new URL(fullURL);
                LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---");
                // Open the connection
                connection = (HttpURLConnection) url.openConnection();
                // Setting Content-Type
                connection.setRequestProperty("Content-Type","application/json");
                // Adding Authorization
                connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding());
                connection.setRequestProperty("Environment", environment);
                connection.setRequestProperty("ClientScope", clientScope);
                // set the method and headers
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(false);
                connection.setDoOutput(true);
                // Adding RequestID
                if (requestID == null) {
                    requestID = UUID.randomUUID();
                    LOGGER.info("No request ID provided, sending generated ID: "
                            + requestID.toString());
                } else {
                    LOGGER.info("Using provided request ID: "
                            + requestID.toString());
                }
                connection.setRequestProperty("X-ECOMP-RequestID",
                        requestID.toString());
                // DO the connect
                try (OutputStream os = connection.getOutputStream()) {
                    int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("copied to output, bytes=" + count);
                    }
                }
                connection.connect();
                responseCode = connection.getResponseCode();
                // If Connected to PAP then break from the loop and continue
                // with the Request
                if (connection.getResponseCode() > 0 || junit) {
                    connected = true;
                    break;
                } else {
                    LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : "  + connection.getResponseCode());
                    rotatePAPList();
                }
            } catch (Exception e) {
                // This means that the PAP is not working
                if (junit) {
                    connected = true;
                    break;
                }
                LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
                        + "PAP connection Error : " + e);
                rotatePAPList();
            }
            papsCount++;
        }
        if (connected) {
            // Read the Response
            LOGGER.debug("connected to the PAP : " + getPAP());
            LOGGER.debug("--- Response: ---");
            if(connection != null){
            	Map<String, List<String>> headers = connection.getHeaderFields();
                for (String key : headers.keySet()) {
                    LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
                }
                try {
                    if(responseCode==202){
                    	StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject();
                    	return policy;
                    }
                } catch (IOException | ClassNotFoundException e) {
                    LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
                    throw new PolicyException(
                            XACMLErrorConstants.ERROR_SYSTEM_ERROR
                                    + "Decoding the result ", e);
                }	
            }
            return null;
        } else {
            return null;
        }
    }
}