2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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=========================================================
21 package org.onap.policy.controller;
24 import java.io.BufferedWriter;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.PrintWriter;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
41 import javax.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
45 import org.json.JSONObject;
46 import org.onap.policy.common.logging.flexlogger.FlexLogger;
47 import org.onap.policy.common.logging.flexlogger.Logger;
48 import org.onap.policy.model.PDPGroupContainer;
49 import org.onap.policy.model.Roles;
50 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.PolicyEntity;
53 import org.onap.policy.rest.jpa.PolicyVersion;
54 import org.onap.policy.rest.util.PDPPolicyContainer;
55 import org.onap.policy.utils.PolicyUtils;
56 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
58 import org.onap.policy.xacml.std.pap.StdPDPGroup;
59 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
60 import org.onap.portalsdk.core.controller.RestrictedBaseController;
61 import org.onap.portalsdk.core.web.support.JsonMessage;
62 import org.onap.portalsdk.core.web.support.UserUtils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.http.MediaType;
65 import org.springframework.stereotype.Controller;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.servlet.ModelAndView;
69 import com.att.research.xacml.api.pap.PAPException;
70 import com.att.research.xacml.api.pap.PDPPolicy;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
77 @RequestMapping({"/"})
78 public class AutoPushController extends RestrictedBaseController{
80 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
81 private static final String UTF8 = "UTF-8";
85 CommonClassDao commonClassDao;
87 private PDPGroupContainer container;
88 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
90 private PDPPolicyContainer policyContainer;
92 private PolicyController policyController;
93 public PolicyController getPolicyController() {
94 return policyController;
97 public void setPolicyController(PolicyController policyController) {
98 this.policyController = policyController;
101 private List<Object> data;
103 public synchronized void refreshGroups() {
104 synchronized(this.groups) {
107 PolicyController controller = getPolicyControllerInstance();
108 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
109 } catch (PAPException e) {
110 String message = "Unable to retrieve Groups from server: " + e;
111 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
117 private PolicyController getPolicyControllerInstance(){
118 return policyController != null ? getPolicyController() : new PolicyController();
121 @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
122 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
126 data = new ArrayList<>();
127 String userId = UserUtils.getUserSession(request).getOrgUserId();
128 Map<String, Object> model = new HashMap<>();
129 ObjectMapper mapper = new ObjectMapper();
130 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
131 List<Object> userRoles = controller.getRoles(userId);
132 roles = new ArrayList<>();
133 scopes = new HashSet<>();
134 for(Object role: userRoles){
135 Roles userRole = (Roles) role;
136 roles.add(userRole.getRole());
137 if(userRole.getScope() != null){
138 if(userRole.getScope().contains(",")){
139 String[] multipleScopes = userRole.getScope().split(",");
140 for(int i =0; i < multipleScopes.length; i++){
141 scopes.add(multipleScopes[i]);
144 if(!"".equals(userRole.getScope())){
145 scopes.add(userRole.getScope());
150 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
151 data = commonClassDao.getData(PolicyVersion.class);
153 if(!scopes.isEmpty()){
154 for(String scope : scopes){
156 String query = "From PolicyVersion where policy_name like :scope and id > 0";
157 SimpleBindings params = new SimpleBindings();
158 params.put("scope", scope);
159 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
160 if(filterdatas != null){
161 for(int i =0; i < filterdatas.size(); i++){
162 data.add(filterdatas.get(i));
167 PolicyVersion emptyPolicyName = new PolicyVersion();
168 emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
169 data.add(emptyPolicyName);
172 model.put("policydatas", mapper.writeValueAsString(data));
173 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
174 JSONObject j = new JSONObject(msg);
175 response.getWriter().write(j.toString());
178 logger.error("Exception Occured"+e);
182 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
183 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
185 ArrayList<Object> selectedPDPS = new ArrayList<>();
186 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
187 PolicyController controller = getPolicyControllerInstance();
188 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
189 ObjectMapper mapper = new ObjectMapper();
190 this.container = new PDPGroupContainer(controller.getPapEngine());
191 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
192 JsonNode root = mapper.readTree(request.getReader());
194 String userId = UserUtils.getUserSession(request).getOrgUserId();
195 logger.info("****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
196 logger.info("UserId: " + userId + "Push Policy Data: "+ root.get("pushTabData").toString());
197 logger.info("***********************************************************************************************************************************");
199 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
200 for (Object pdpGroupId : adapter.getPdpDatas()) {
201 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
202 for(OnapPDPGroup pdpGroup : this.groups){
203 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
204 selectedPDPS.add(pdpGroup);
209 for (Object policyId : adapter.getPolicyDatas()) {
210 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
211 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
212 selectedPoliciesInUI.add(policyName);
215 for (Object pdpDestinationGroupId : selectedPDPS) {
216 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
217 Set<PDPPolicy> selectedPolicies = new HashSet<>();
218 for (String policyId : selectedPoliciesInUI) {
219 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
222 // Get the current selection
223 String selectedItem = policyId;
225 assert selectedItem != null;
226 // create the id of the target file
227 // Our standard for file naming is:
228 // <domain>.<filename>.<version>.xml
229 // since the file name usually has a ".xml", we need to strip
231 // before adding the other parts
232 String name = selectedItem.replace(File.separator, ".");
234 if (id.endsWith(".xml")) {
235 id = id.replace(".xml", "");
236 id = id.substring(0, id.lastIndexOf('.'));
239 // Default policy to be Root policy; user can change to deferred
242 StdPDPPolicy selectedPolicy = null;
243 String dbCheckName = name;
244 if(dbCheckName.contains("Config_")){
245 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
246 }else if(dbCheckName.contains("Action_")){
247 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
248 }else if(dbCheckName.contains("Decision_")){
249 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
251 String[] split = dbCheckName.split(":");
252 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
253 SimpleBindings policyParams = new SimpleBindings();
254 policyParams.put("split_1", split[1]);
255 policyParams.put("split_0", split[0]);
256 List<Object> queryData = controller.getDataByQuery(query, policyParams);
257 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
258 File temp = new File(name);
259 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
260 bw.write(policyEntity.getPolicyData());
262 URI selectedURI = temp.toURI();
266 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
267 } catch (IOException e) {
268 logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e);
270 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
271 if (selectedPolicy != null) {
272 // Add Current policies from container
273 for (OnapPDPGroup group : container.getGroups()) {
274 if (group.getId().equals(selectedGroup.getId())) {
275 currentPoliciesInGroup.addAll(group.getPolicies());
278 // copy policy to PAP
280 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
281 } catch (PAPException e) {
282 logger.error("Exception Occured"+e);
285 selectedPolicies.add(selectedPolicy);
289 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
290 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
291 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
292 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
293 updatedGroupObject.setStatus(pdpGroup.getStatus());
294 updatedGroupObject.setOperation("push");
296 // replace the original set of Policies with the set from the
297 // container (possibly modified by the user)
298 // do not allow multiple copies of same policy
299 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
300 logger.debug("policyIterator....." + selectedPolicies);
301 while (policyIterator.hasNext()) {
302 PDPPolicy existingPolicy = policyIterator.next();
303 for (PDPPolicy selPolicy : selectedPolicies) {
304 if (selPolicy.getName().equals(existingPolicy.getName())) {
305 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
306 if (selPolicy.getId().equals(existingPolicy.getId())) {
307 policyIterator.remove();
308 logger.debug("Removing policy: " + selPolicy);
312 policyIterator.remove();
313 logger.debug("Removing Old Policy version: "+ selPolicy);
320 currentPoliciesInGroup.addAll(selectedPolicies);
321 updatedGroupObject.setPolicies(currentPoliciesInGroup);
322 this.container.updateGroup(updatedGroupObject);
324 response.setCharacterEncoding(UTF8);
325 response.setContentType("application / json");
326 request.setCharacterEncoding(UTF8);
328 PrintWriter out = response.getWriter();
330 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
331 JSONObject j = new JSONObject(msg);
332 out.write(j.toString());
334 // Why is this here? This defeats the purpose of the loop??
335 // Sonar says to remove it or make it conditional
341 response.setCharacterEncoding(UTF8);
342 request.setCharacterEncoding(UTF8);
343 PrintWriter out = response.getWriter();
345 out.write(PolicyUtils.CATCH_EXCEPTION);
350 @SuppressWarnings("unchecked")
351 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
352 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
354 PolicyController controller = getPolicyControllerInstance();
355 this.container = new PDPGroupContainer(controller.getPapEngine());
356 ObjectMapper mapper = new ObjectMapper();
357 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
358 JsonNode root = mapper.readTree(request.getReader());
359 StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
360 JsonNode removePolicyData = root.get("data");
362 String userId = UserUtils.getUserSession(request).getOrgUserId();
363 logger.info("****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
364 logger.info("UserId: " + userId + "PDP Group Data: "+ root.get("activePdpGroup").toString() + "Remove Policy Data: "+root.get("data"));
365 logger.info("***********************************************************************************************************************************");
367 policyContainer = new PDPPolicyContainer(group);
368 if(removePolicyData.size() > 0){
369 for(int i = 0 ; i < removePolicyData.size(); i++){
370 String polData = removePolicyData.get(i).toString();
371 this.policyContainer.removeItem(polData);
373 Set<PDPPolicy> changedPolicies = new HashSet<>();
374 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
375 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
376 updatedGroupObject.setPolicies(changedPolicies);
377 updatedGroupObject.setOnapPdps(group.getOnapPdps());
378 updatedGroupObject.setPipConfigs(group.getPipConfigs());
379 updatedGroupObject.setStatus(group.getStatus());
380 updatedGroupObject.setOperation("delete");
381 this.container.updateGroup(updatedGroupObject);
384 response.setCharacterEncoding(UTF8);
385 response.setContentType("application / json");
386 request.setCharacterEncoding(UTF8);
388 PrintWriter out = response.getWriter();
390 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
391 JSONObject j = new JSONObject(msg);
393 out.write(j.toString());
398 response.setCharacterEncoding(UTF8);
399 request.setCharacterEncoding(UTF8);
400 PrintWriter out = response.getWriter();
402 out.write(PolicyUtils.CATCH_EXCEPTION);