Sonar cleanup in controllers etc
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / AutoPushController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Bell Canada
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controller;
23
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.api.pap.PDPPolicy;
26 import com.fasterxml.jackson.databind.DeserializationFeature;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29
30 import java.io.BufferedWriter;
31 import java.io.File;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Set;
44 import java.util.stream.Collectors;
45 import java.util.stream.IntStream;
46 import java.util.stream.Stream;
47
48 import javax.script.SimpleBindings;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.json.JSONObject;
53 import org.onap.policy.common.logging.flexlogger.FlexLogger;
54 import org.onap.policy.common.logging.flexlogger.Logger;
55 import org.onap.policy.model.PDPGroupContainer;
56 import org.onap.policy.model.Roles;
57 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
58 import org.onap.policy.rest.dao.CommonClassDao;
59 import org.onap.policy.rest.jpa.PolicyEntity;
60 import org.onap.policy.rest.jpa.PolicyVersion;
61 import org.onap.policy.rest.util.PDPPolicyContainer;
62 import org.onap.policy.utils.PolicyUtils;
63 import org.onap.policy.xacml.api.XACMLErrorConstants;
64 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
65 import org.onap.policy.xacml.std.pap.StdPDPGroup;
66 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
67 import org.onap.portalsdk.core.controller.RestrictedBaseController;
68 import org.onap.portalsdk.core.web.support.JsonMessage;
69 import org.onap.portalsdk.core.web.support.UserUtils;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.http.MediaType;
72 import org.springframework.stereotype.Controller;
73 import org.springframework.web.bind.annotation.RequestMapping;
74 import org.springframework.web.bind.annotation.RequestMethod;
75 import org.springframework.web.servlet.ModelAndView;
76
77 @Controller
78 @RequestMapping({"/"})
79 public class AutoPushController extends RestrictedBaseController {
80
81     private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
82     private static final String UTF8 = "UTF-8";
83
84     @Autowired
85     CommonClassDao commonClassDao;
86
87     private PDPGroupContainer container;
88     private PDPPolicyContainer policyContainer;
89     private PolicyController policyController;
90     protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
91
92     public PolicyController getPolicyController() {
93         return policyController;
94     }
95
96     public void setPolicyController(PolicyController policyController) {
97         this.policyController = policyController;
98     }
99
100     /**
101      * refreshGroups.
102      */
103     public synchronized void refreshGroups() {
104         synchronized (this.groups) {
105             this.groups.clear();
106             try {
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);
112             }
113
114         }
115     }
116
117     private PolicyController getPolicyControllerInstance() {
118         return policyController != null ? getPolicyController() : new PolicyController();
119     }
120
121     private Set<String> addAllScopes(Roles userRole, Set<String> scopes) {
122         if (userRole.getScope() != null) {
123             scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
124         }
125         return scopes;
126     }
127
128     /**
129      * getPolicyGroupContainerData.
130      *
131      * @param request HttpServletRequest
132      * @param response HttpServletResponse
133      */
134     @RequestMapping(
135             value = {"/get_AutoPushPoliciesContainerData"},
136             method = {RequestMethod.GET},
137             produces = MediaType.APPLICATION_JSON_VALUE)
138     public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
139         try {
140             Set<String> scopes = new HashSet<>();
141             List<String> roles = new ArrayList<>();
142             List<Object> data = new ArrayList<>();
143             Map<String, Object> model = new HashMap<>();
144
145             String userId = UserUtils.getUserSession(request).getOrgUserId();
146
147             PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
148             List<Object> userRoles = controller.getRoles(userId);
149             for (Object role : userRoles) {
150                 Roles userRole = (Roles) role;
151                 roles.add(userRole.getRole());
152                 addAllScopes(userRole, scopes);
153             }
154
155             if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
156                 data = commonClassDao.getData(PolicyVersion.class);
157             } else {
158                 if (!scopes.isEmpty()) {
159                     for (String scope : scopes) {
160                         scope += "%";
161                         String query = "From PolicyVersion where policy_name like :scope and id > 0";
162                         SimpleBindings params = new SimpleBindings();
163                         params.put("scope", scope);
164                         List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
165                         if (filterdatas != null) {
166                             data.addAll(filterdatas);
167                         }
168                     }
169                 } else {
170                     PolicyVersion emptyPolicyName = new PolicyVersion();
171                     emptyPolicyName
172                             .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
173                     data.add(emptyPolicyName);
174                 }
175             }
176             ObjectMapper mapper = new ObjectMapper();
177             model.put("policydatas", mapper.writeValueAsString(data));
178             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
179             response.getWriter().write(new JSONObject(msg).toString());
180         } catch (Exception e) {
181             logger.error("Exception Occurred" + e);
182         }
183     }
184
185     /**
186      * pushPolicyToPDPGroup.
187      *
188      * @param request HttpServletRequest
189      * @param response HttpServletResponse
190      * @return ModelAndView
191      * @throws IOException IOException
192      */
193     @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
194     public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
195             throws IOException {
196         try {
197             ArrayList<Object> selectedPdps = new ArrayList<>();
198             ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
199             PolicyController controller = getPolicyControllerInstance();
200             this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
201             ObjectMapper mapper = new ObjectMapper();
202             this.container = new PDPGroupContainer(controller.getPapEngine());
203             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
204             JsonNode root = mapper.readTree(request.getReader());
205
206             String userId = UserUtils.getUserSession(request).getOrgUserId();
207             logger.info(
208                     "**********************Logging UserID while Pushing  Policy to PDP Group***********************");
209             logger.info("UserId:  " + userId + "Push Policy Data:  " + root.get("pushTabData").toString());
210             logger.info(
211                     "**********************************************************************************************");
212
213             AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
214             for (Object pdpGroupId : adapter.getPdpDatas()) {
215                 LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
216                 for (OnapPDPGroup pdpGroup : this.groups) {
217                     if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
218                         selectedPdps.add(pdpGroup);
219                     }
220                 }
221             }
222
223             for (Object policyId : adapter.getPolicyDatas()) {
224                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
225                 String policyName =
226                         selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
227                 selectedPoliciesInUI.add(policyName);
228             }
229
230             for (Object pdpDestinationGroupId : selectedPdps) {
231                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
232                 Set<PDPPolicy> selectedPolicies = new HashSet<>();
233                 for (String policyId : selectedPoliciesInUI) {
234                     logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
235
236                     //
237                     // Get the current selection
238                     //
239                     assert policyId != null;
240                     // create the id of the target file
241                     // Our standard for file naming is:
242                     // <domain>.<filename>.<version>.xml
243                     // since the file name usually has a ".xml", we need to strip
244                     // that
245                     // before adding the other parts
246                     String name = policyId.replace(File.separator, ".");
247                     String id = name;
248                     if (id.endsWith(".xml")) {
249                         id = id.replace(".xml", "");
250                         id = id.substring(0, id.lastIndexOf('.'));
251                     }
252
253                     // Default policy to be Root policy; user can change to deferred
254                     // later
255
256                     StdPDPPolicy selectedPolicy = null;
257                     String dbCheckName = name;
258                     if (dbCheckName.contains("Config_")) {
259                         dbCheckName = dbCheckName.replace(".Config_", ":Config_");
260                     } else if (dbCheckName.contains("Action_")) {
261                         dbCheckName = dbCheckName.replace(".Action_", ":Action_");
262                     } else if (dbCheckName.contains("Decision_")) {
263                         dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
264                     }
265                     String[] split = dbCheckName.split(":");
266                     String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
267                     SimpleBindings policyParams = new SimpleBindings();
268                     policyParams.put("split_1", split[1]);
269                     policyParams.put("split_0", split[0]);
270                     List<Object> queryData = controller.getDataByQuery(query, policyParams);
271                     PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
272                     File temp = new File(name);
273                     BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
274                     bw.write(policyEntity.getPolicyData());
275                     bw.close();
276                     try {
277                         // Create the policy
278                         selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
279                     } catch (IOException e) {
280                         logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
281                     }
282                     StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
283                     if (selectedPolicy != null) {
284                         // Add Current policies from container
285                         for (OnapPDPGroup group : container.getGroups()) {
286                             if (group.getId().equals(selectedGroup.getId())) {
287                                 currentPoliciesInGroup.addAll(group.getPolicies());
288                             }
289                         }
290                         // copy policy to PAP
291                         try {
292                             controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
293                         } catch (PAPException e) {
294                             logger.error("Exception Occured" + e);
295                             return null;
296                         }
297                         selectedPolicies.add(selectedPolicy);
298                     }
299                     temp.delete();
300                 }
301                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
302                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
303                         pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
304                 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
305                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
306                 updatedGroupObject.setStatus(pdpGroup.getStatus());
307                 updatedGroupObject.setOperation("push");
308
309                 // replace the original set of Policies with the set from the
310                 // container (possibly modified by the user)
311                 // do not allow multiple copies of same policy
312                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
313                 logger.debug("policyIterator....." + selectedPolicies);
314                 while (policyIterator.hasNext()) {
315                     PDPPolicy existingPolicy = policyIterator.next();
316                     for (PDPPolicy selPolicy : selectedPolicies) {
317                         if (selPolicy.getName().equals(existingPolicy.getName())) {
318                             if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
319                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
320                                     policyIterator.remove();
321                                     logger.debug("Removing policy: " + selPolicy);
322                                     break;
323                                 }
324                             } else {
325                                 policyIterator.remove();
326                                 logger.debug("Removing Old Policy version: " + selPolicy);
327                                 break;
328                             }
329                         }
330                     }
331                 }
332
333                 currentPoliciesInGroup.addAll(selectedPolicies);
334                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
335                 this.container.updateGroup(updatedGroupObject, userId);
336
337                 response.setCharacterEncoding(UTF8);
338                 response.setContentType("application / json");
339                 request.setCharacterEncoding(UTF8);
340
341                 refreshGroups();
342                 response.getWriter().write(new JSONObject(
343                         new JsonMessage(mapper.writeValueAsString(groups))).toString());
344             }
345         } catch (Exception e) {
346             response.setCharacterEncoding(UTF8);
347             request.setCharacterEncoding(UTF8);
348             logger.error(e);
349             response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
350         }
351         return null;
352     }
353
354     /**
355      * removePDPGroup.
356      */
357     @SuppressWarnings("unchecked")
358     @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
359     public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
360         try {
361             PolicyController controller = getPolicyControllerInstance();
362             this.container = new PDPGroupContainer(controller.getPapEngine());
363             ObjectMapper mapper = new ObjectMapper();
364             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
365             JsonNode root = mapper.readTree(request.getReader());
366             final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
367             final JsonNode removePolicyData = root.get("data");
368
369             String userId = UserUtils.getUserSession(request).getOrgUserId();
370             logger.info(
371                     "**********************Logging UserID while Removing Policy from PDP Group*********************");
372             logger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("activePdpGroup").toString()
373                     + "Remove Policy Data: " + root.get("data"));
374             logger.info(
375                     "**********************************************************************************************");
376
377             policyContainer = new PDPPolicyContainer(group);
378             if (removePolicyData.size() > 0) {
379                 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
380                         .forEach(polData -> this.policyContainer.removeItem(polData));
381                 Set<PDPPolicy> changedPolicies =
382                         new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
383                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
384                         group.getDescription(), null);
385                 updatedGroupObject.setPolicies(changedPolicies);
386                 updatedGroupObject.setOnapPdps(group.getOnapPdps());
387                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
388                 updatedGroupObject.setStatus(group.getStatus());
389                 updatedGroupObject.setOperation("delete");
390                 this.container.updateGroup(updatedGroupObject);
391             }
392
393             response.setCharacterEncoding(UTF8);
394             response.setContentType("application / json");
395             request.setCharacterEncoding(UTF8);
396
397             refreshGroups();
398             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
399         } catch (Exception e) {
400             response.setCharacterEncoding(UTF8);
401             request.setCharacterEncoding(UTF8);
402             logger.error(e);
403             response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
404         }
405         return null;
406     }
407 }