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