Unit/SONAR/Checkstyle in ONAP-REST
[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
83     @Autowired
84     CommonClassDao commonClassDao;
85
86     private PDPGroupContainer container;
87     private PdpPolicyContainer policyContainer;
88     private PolicyController policyController;
89     protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
90
91     public PolicyController getPolicyController() {
92         return policyController;
93     }
94
95     public void setPolicyController(PolicyController policyController) {
96         this.policyController = policyController;
97     }
98
99     /**
100      * refreshGroups.
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     /**
128      * getPolicyGroupContainerData.
129      *
130      * @param request HttpServletRequest
131      * @param response HttpServletResponse
132      */
133     @RequestMapping(
134             value = {"/get_AutoPushPoliciesContainerData"},
135             method = {RequestMethod.GET},
136             produces = MediaType.APPLICATION_JSON_VALUE)
137     public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
138         try {
139             Set<String> scopes = new HashSet<>();
140             List<String> roles = new ArrayList<>();
141             List<Object> data = new ArrayList<>();
142             Map<String, Object> model = new HashMap<>();
143
144             String userId = UserUtils.getUserSession(request).getOrgUserId();
145
146             PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
147             List<Object> userRoles = controller.getRoles(userId);
148             for (Object role : userRoles) {
149                 Roles userRole = (Roles) role;
150                 roles.add(userRole.getRole());
151                 addAllScopes(userRole, scopes);
152             }
153
154             if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
155                 data = commonClassDao.getData(PolicyVersion.class);
156             } else {
157                 if (!scopes.isEmpty()) {
158                     for (String scope : scopes) {
159                         scope += "%";
160                         String query = "From PolicyVersion where policy_name like :scope and id > 0";
161                         SimpleBindings params = new SimpleBindings();
162                         params.put("scope", scope);
163                         List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
164                         if (filterdatas != null) {
165                             data.addAll(filterdatas);
166                         }
167                     }
168                 } else {
169                     PolicyVersion emptyPolicyName = new PolicyVersion();
170                     emptyPolicyName
171                             .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
172                     data.add(emptyPolicyName);
173                 }
174             }
175             ObjectMapper mapper = new ObjectMapper();
176             model.put("policydatas", mapper.writeValueAsString(data));
177             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
178             response.getWriter().write(new JSONObject(msg).toString());
179         } catch (Exception e) {
180             logger.error("Exception Occurred" + e);
181         }
182     }
183
184     /**
185      * pushPolicyToPDPGroup.
186      *
187      * @param request HttpServletRequest
188      * @param response HttpServletResponse
189      * @return ModelAndView
190      * @throws IOException IOException
191      */
192     @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
193     public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
194             throws IOException {
195         try {
196             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
197             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
198             //
199             //
200             //
201             ArrayList<Object> selectedPdps = new ArrayList<>();
202             ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
203             PolicyController controller = getPolicyControllerInstance();
204             this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
205             ObjectMapper mapper = new ObjectMapper();
206             this.container = new PDPGroupContainer(controller.getPapEngine());
207             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
208             JsonNode root = mapper.readTree(request.getReader());
209
210             String userId = UserUtils.getUserSession(request).getOrgUserId();
211             logger.info(
212                     "**********************Logging UserID while Pushing  Policy to PDP Group***********************");
213             logger.info("UserId:  " + userId + "Push Policy Data:  " + root.get("pushTabData").toString());
214             logger.info(
215                     "**********************************************************************************************");
216
217             AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
218             for (Object pdpGroupId : adapter.getPdpDatas()) {
219                 LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
220                 for (OnapPDPGroup pdpGroup : this.groups) {
221                     if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
222                         selectedPdps.add(pdpGroup);
223                     }
224                 }
225             }
226
227             for (Object policyId : adapter.getPolicyDatas()) {
228                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
229                 String policyName =
230                         selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
231                 selectedPoliciesInUI.add(policyName);
232             }
233
234             for (Object pdpDestinationGroupId : selectedPdps) {
235                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
236                 Set<PDPPolicy> selectedPolicies = new HashSet<>();
237                 for (String policyId : selectedPoliciesInUI) {
238                     logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
239
240                     //
241                     // Get the current selection
242                     //
243                     assert policyId != null;
244                     // create the id of the target file
245                     // Our standard for file naming is:
246                     // <domain>.<filename>.<version>.xml
247                     // since the file name usually has a ".xml", we need to strip
248                     // that
249                     // before adding the other parts
250                     String name = policyId.replace(File.separator, ".");
251                     String id = name;
252                     if (id.endsWith(".xml")) {
253                         id = id.replace(".xml", "");
254                         id = id.substring(0, id.lastIndexOf('.'));
255                     }
256
257                     // Default policy to be Root policy; user can change to deferred
258                     // later
259
260                     StdPDPPolicy selectedPolicy = null;
261                     String dbCheckName = name;
262                     if (dbCheckName.contains("Config_")) {
263                         dbCheckName = dbCheckName.replace(".Config_", ":Config_");
264                     } else if (dbCheckName.contains("Action_")) {
265                         dbCheckName = dbCheckName.replace(".Action_", ":Action_");
266                     } else if (dbCheckName.contains("Decision_")) {
267                         dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
268                     }
269                     String[] split = dbCheckName.split(":");
270                     String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
271                     SimpleBindings policyParams = new SimpleBindings();
272                     policyParams.put("split_1", split[1]);
273                     policyParams.put("split_0", split[0]);
274                     List<Object> queryData = controller.getDataByQuery(query, policyParams);
275                     PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
276                     File temp = new File(name);
277                     BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
278                     bw.write(policyEntity.getPolicyData());
279                     bw.close();
280                     try {
281                         // Create the policy
282                         selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
283                     } catch (IOException e) {
284                         logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
285                     }
286                     StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
287                     if (selectedPolicy != null) {
288                         // Add Current policies from container
289                         for (OnapPDPGroup group : container.getGroups()) {
290                             if (group.getId().equals(selectedGroup.getId())) {
291                                 currentPoliciesInGroup.addAll(group.getPolicies());
292                             }
293                         }
294                         // copy policy to PAP
295                         try {
296                             controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
297                         } catch (PAPException e) {
298                             logger.error("Exception Occured" + e);
299                             return null;
300                         }
301                         selectedPolicies.add(selectedPolicy);
302                     }
303                     temp.delete();
304                 }
305                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
306                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
307                         pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
308                 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
309                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
310                 updatedGroupObject.setStatus(pdpGroup.getStatus());
311                 updatedGroupObject.setOperation("push");
312
313                 // replace the original set of Policies with the set from the
314                 // container (possibly modified by the user)
315                 // do not allow multiple copies of same policy
316                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
317                 logger.debug("policyIterator....." + selectedPolicies);
318                 while (policyIterator.hasNext()) {
319                     PDPPolicy existingPolicy = policyIterator.next();
320                     for (PDPPolicy selPolicy : selectedPolicies) {
321                         if (selPolicy.getName().equals(existingPolicy.getName())) {
322                             if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
323                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
324                                     policyIterator.remove();
325                                     logger.debug("Removing policy: " + selPolicy);
326                                     break;
327                                 }
328                             } else {
329                                 policyIterator.remove();
330                                 logger.debug("Removing Old Policy version: " + selPolicy);
331                                 break;
332                             }
333                         }
334                     }
335                 }
336
337                 currentPoliciesInGroup.addAll(selectedPolicies);
338                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
339                 this.container.updateGroup(updatedGroupObject, userId);
340                 response.setContentType(PolicyUtils.APPLICATION_JSON);
341                 refreshGroups();
342                 response.getWriter().write(new JSONObject(
343                         new JsonMessage(mapper.writeValueAsString(groups))).toString());
344             }
345         } catch (Exception e) {
346             logger.error(e);
347             response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
348         }
349         return null;
350     }
351
352     /**
353      * removePDPGroup.
354      */
355     @SuppressWarnings("unchecked")
356     @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
357     public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
358         try {
359             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
360             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
361             //
362             //
363             //
364             PolicyController controller = getPolicyControllerInstance();
365             this.container = new PDPGroupContainer(controller.getPapEngine());
366             ObjectMapper mapper = new ObjectMapper();
367             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
368             JsonNode root = mapper.readTree(request.getReader());
369             final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
370             final JsonNode removePolicyData = root.get("data");
371
372             String userId = UserUtils.getUserSession(request).getOrgUserId();
373             logger.info(
374                     "**********************Logging UserID while Removing Policy from PDP Group*********************");
375             logger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("activePdpGroup").toString()
376                     + "Remove Policy Data: " + root.get("data"));
377             logger.info(
378                     "**********************************************************************************************");
379
380             policyContainer = new PdpPolicyContainer(group);
381             if (removePolicyData.size() > 0) {
382                 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
383                         .forEach(polData -> this.policyContainer.removeItem(polData));
384                 Set<PDPPolicy> changedPolicies =
385                         new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
386                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
387                         group.getDescription(), null);
388                 updatedGroupObject.setPolicies(changedPolicies);
389                 updatedGroupObject.setOnapPdps(group.getOnapPdps());
390                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
391                 updatedGroupObject.setStatus(group.getStatus());
392                 updatedGroupObject.setOperation("delete");
393                 this.container.updateGroup(updatedGroupObject);
394             }
395
396             response.setContentType(PolicyUtils.APPLICATION_JSON);
397
398             refreshGroups();
399             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
400         } catch (Exception e) {
401             logger.error(e);
402             response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
403         }
404         return null;
405     }
406 }