aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java
blob: d88aee0cbefa27efe22f789a045ed0901d12e5c1 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*-
 * ============LICENSE_START=======================================================
 * ONAP-PAP-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.pap.xacml.rest.handler;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.std.pap.StdPAPPolicy;
import org.xml.sax.SAXException;

import com.att.research.xacml.util.XACMLProperties;

public class SavePolicyHandler {
	private HashMap<String, String> ErrorHeaders = null;
	
	public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String operation = request.getParameter("operation");
		String policyType = request.getParameter("policyType");
		String apiflag = request.getParameter("apiflag");
		PolicyCreation creation = new PolicyCreation();
        if ( policyType != null ) {
			PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
			if("update".equalsIgnoreCase(operation)){
				policyAdapter.setEditPolicy(true);
			}else{
				policyAdapter.setEditPolicy(false);
			}
			
			// get the request content into a String
			String json = null;
			// 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(request.getInputStream());
			scanner.useDelimiter("\\A");
			json =  scanner.hasNext() ? scanner.next() : "";
			scanner.close();
			PolicyLogger.info("JSON request from API: " + json);
			// convert Object sent as JSON into local object
			StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
			//Set policyAdapter values including parentPath (Common to all policy types)
			try {
                policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
                
                if(!extendedPolicyOptions(policyAdapter, response)){
                	creation.savePolicy(policyAdapter, response);
                }
                if ("update".equalsIgnoreCase(operation)) {
					response.addHeader("operation",  "update");
				} else {
					response.addHeader("operation", "create");
				}
			} catch (Exception e1) {
				PolicyLogger.error(XACMLErrorConstants.ERROR_UNKNOWN + 
						"Could not set data to policy adapter "+ e1.getMessage());
			}
        }
	}

	private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{
		PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
		policyAdapter.setApiflag(apiflag);
		/*
		 * set policy adapter values for Building JSON object containing policy data
		 */
		//Common among policy types
		policyAdapter.setPolicyName(policy.getPolicyName());
		policyAdapter.setPolicyDescription(policy.getPolicyDescription());
		policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies
		policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
	
		policyAdapter.setPolicyType(policyType);
		policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes());
		policyAdapter.setEditPolicy(policy.isEditPolicy());
		policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf());
		//Config Specific
		policyAdapter.setConfigName(policy.getConfigName());  //Base and Firewall
		policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base
		policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null);  //Base
		policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop
		policyAdapter.setConfigPolicyType(policy.getConfigPolicyType());
		policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault
		policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM
		policyAdapter.setUuid(policy.getUuid()); //Micro Service
		policyAdapter.setLocation(policy.getMsLocation()); //Micro Service
		policyAdapter.setPriority(policy.getPriority()); //Micro Service
		policyAdapter.setPolicyScope(policy.getDomainDir());
		policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes
		policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes
		policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes
		policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes
		policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
        policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies.
        policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies.
		//Action Policy Specific
		policyAdapter.setActionAttribute(policy.getActionAttribute());  //comboDictValue
		policyAdapter.setActionPerformer(policy.getActionPerformer());
		policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels());
		policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo());
		policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1());
		policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2());
		//Decision Policy Specific
		policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
		policyAdapter.setRuleProvider(policy.getProviderComboBox());
		policyAdapter.setDomainDir(policyAdapter.getPolicyScope());
		policyAdapter.setDomain(policyAdapter.getPolicyScope());
		return policyAdapter;
	}
	
	public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){
		return false;
	}
	
	public void addErrorHeader(String key, String value){
		if(ErrorHeaders==null){
			ErrorHeaders= new HashMap<>();
		}
		ErrorHeaders.put(key, value);
	}

	public static SavePolicyHandler getInstance() {
		try {
			Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName()));
			SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); 
			return instance;
		} catch (Exception e) {
			PolicyLogger.error(e.getMessage());
		}
		return null;
	}
}