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