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