2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
24 import java.io.BufferedWriter;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.PrintWriter;
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;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
44 import org.json.JSONObject;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.model.PDPGroupContainer;
48 import org.onap.policy.model.PDPPolicyContainer;
49 import org.onap.policy.model.Roles;
50 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.PolicyEntity;
53 import org.onap.policy.rest.jpa.PolicyVersion;
54 import org.onap.policy.xacml.api.XACMLErrorConstants;
55 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
56 import org.onap.policy.xacml.std.pap.StdPDPGroup;
57 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.JsonMessage;
60 import org.openecomp.portalsdk.core.web.support.UserUtils;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.http.MediaType;
63 import org.springframework.stereotype.Controller;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.servlet.ModelAndView;
67 import com.att.research.xacml.api.pap.PAPException;
68 import com.att.research.xacml.api.pap.PDPPolicy;
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
75 @RequestMapping({"/"})
76 public class AutoPushController extends RestrictedBaseController{
78 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
81 CommonClassDao commonClassDao;
83 private PDPGroupContainer container;
84 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
86 private PDPPolicyContainer policyContainer;
88 private PolicyController policyController;
89 public PolicyController getPolicyController() {
90 return policyController;
93 public void setPolicyController(PolicyController policyController) {
94 this.policyController = policyController;
97 private List<Object> data;
99 public synchronized void refreshGroups() {
100 synchronized(this.groups) {
103 PolicyController controller = getPolicyControllerInstance();
104 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
105 } catch (PAPException e) {
106 String message = "Unable to retrieve Groups from server: " + e;
107 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
113 private PolicyController getPolicyControllerInstance(){
114 return policyController != null ? getPolicyController() : new PolicyController();
117 @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
118 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
120 Set<String> scopes = null;
121 List<String> roles = null;
122 data = new ArrayList<Object>();
123 String userId = UserUtils.getUserSession(request).getOrgUserId();
124 Map<String, Object> model = new HashMap<>();
125 ObjectMapper mapper = new ObjectMapper();
126 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
127 List<Object> userRoles = controller.getRoles(userId);
128 roles = new ArrayList<>();
129 scopes = new HashSet<>();
130 for(Object role: userRoles){
131 Roles userRole = (Roles) role;
132 roles.add(userRole.getRole());
133 if(userRole.getScope() != null){
134 if(userRole.getScope().contains(",")){
135 String[] multipleScopes = userRole.getScope().split(",");
136 for(int i =0; i < multipleScopes.length; i++){
137 scopes.add(multipleScopes[i]);
140 if(!userRole.getScope().equals("")){
141 scopes.add(userRole.getScope());
146 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
147 data = commonClassDao.getData(PolicyVersion.class);
149 if(!scopes.isEmpty()){
150 for(String scope : scopes){
151 String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0";
152 List<Object> filterdatas = commonClassDao.getDataByQuery(query);
153 if(filterdatas != null){
154 for(int i =0; i < filterdatas.size(); i++){
155 data.add(filterdatas.get(i));
160 PolicyVersion emptyPolicyName = new PolicyVersion();
161 emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
162 data.add(emptyPolicyName);
165 model.put("policydatas", mapper.writeValueAsString(data));
166 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
167 JSONObject j = new JSONObject(msg);
168 response.getWriter().write(j.toString());
171 logger.error("Exception Occured"+e);
175 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
176 public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
178 ArrayList<Object> selectedPDPS = new ArrayList<>();
179 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
180 PolicyController controller = getPolicyControllerInstance();
181 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
182 ObjectMapper mapper = new ObjectMapper();
183 this.container = new PDPGroupContainer(controller.getPapEngine());
184 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
185 JsonNode root = mapper.readTree(request.getReader());
186 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
187 for (Object pdpGroupId : adapter.getPdpDatas()) {
188 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
189 for(OnapPDPGroup pdpGroup : this.groups){
190 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
191 selectedPDPS.add(pdpGroup);
196 for (Object policyId : adapter.getPolicyDatas()) {
197 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
198 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
199 selectedPoliciesInUI.add(policyName);
202 for (Object pdpDestinationGroupId : selectedPDPS) {
203 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
204 Set<PDPPolicy> selectedPolicies = new HashSet<>();
205 for (String policyId : selectedPoliciesInUI) {
206 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
209 // Get the current selection
210 String selectedItem = policyId;
212 assert (selectedItem != null);
213 // create the id of the target file
214 // Our standard for file naming is:
215 // <domain>.<filename>.<version>.xml
216 // since the file name usually has a ".xml", we need to strip
218 // before adding the other parts
219 String name = selectedItem.replace(File.separator, ".");
221 if (id.endsWith(".xml")) {
222 id = id.replace(".xml", "");
223 id = id.substring(0, id.lastIndexOf("."));
226 // Default policy to be Root policy; user can change to deferred
229 StdPDPPolicy selectedPolicy = null;
230 String dbCheckName = name;
231 if(dbCheckName.contains("Config_")){
232 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
233 }else if(dbCheckName.contains("Action_")){
234 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
235 }else if(dbCheckName.contains("Decision_")){
236 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
238 String[] split = dbCheckName.split(":");
239 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
240 List<Object> queryData = controller.getDataByQuery(query);
241 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
242 File temp = new File(name);
243 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
244 bw.write(policyEntity.getPolicyData());
246 URI selectedURI = temp.toURI();
250 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
251 } catch (IOException e) {
252 logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
254 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
255 if (selectedPolicy != null) {
256 // Add Current policies from container
257 for (OnapPDPGroup group : container.getGroups()) {
258 if (group.getId().equals(selectedGroup.getId())) {
259 currentPoliciesInGroup.addAll(group.getPolicies());
262 // copy policy to PAP
264 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
265 } catch (PAPException e) {
266 logger.error("Exception Occured"+e);
269 selectedPolicies.add(selectedPolicy);
273 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
274 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
275 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
276 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
277 updatedGroupObject.setStatus(pdpGroup.getStatus());
279 // replace the original set of Policies with the set from the
280 // container (possibly modified by the user)
281 // do not allow multiple copies of same policy
282 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
283 logger.debug("policyIterator....." + selectedPolicies);
284 while (policyIterator.hasNext()) {
285 PDPPolicy existingPolicy = policyIterator.next();
286 for (PDPPolicy selPolicy : selectedPolicies) {
287 if (selPolicy.getName().equals(existingPolicy.getName())) {
288 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
289 if (selPolicy.getId().equals(existingPolicy.getId())) {
290 policyIterator.remove();
291 logger.debug("Removing policy: " + selPolicy);
295 policyIterator.remove();
296 logger.debug("Removing Old Policy version: "+ selPolicy);
303 currentPoliciesInGroup.addAll(selectedPolicies);
304 updatedGroupObject.setPolicies(currentPoliciesInGroup);
305 this.container.updateGroup(updatedGroupObject);
307 response.setCharacterEncoding("UTF-8");
308 response.setContentType("application / json");
309 request.setCharacterEncoding("UTF-8");
311 PrintWriter out = response.getWriter();
313 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
314 JSONObject j = new JSONObject(msg);
315 out.write(j.toString());
320 response.setCharacterEncoding("UTF-8");
321 request.setCharacterEncoding("UTF-8");
322 PrintWriter out = response.getWriter();
323 out.write(e.getMessage());
328 @SuppressWarnings("unchecked")
329 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
330 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
332 PolicyController controller = getPolicyControllerInstance();
333 this.container = new PDPGroupContainer(controller.getPapEngine());
334 ObjectMapper mapper = new ObjectMapper();
335 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
336 JsonNode root = mapper.readTree(request.getReader());
337 StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
338 JsonNode removePolicyData = root.get("data");
339 policyContainer = new PDPPolicyContainer(group);
340 if(removePolicyData.size() > 0){
341 for(int i = 0 ; i < removePolicyData.size(); i++){
342 String data = removePolicyData.get(i).toString();
343 this.policyContainer.removeItem(data);
345 Set<PDPPolicy> changedPolicies = new HashSet<>();
346 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
347 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
348 updatedGroupObject.setPolicies(changedPolicies);
349 updatedGroupObject.setOnapPdps(group.getOnapPdps());
350 updatedGroupObject.setPipConfigs(group.getPipConfigs());
351 updatedGroupObject.setStatus(group.getStatus());
352 this.container.updateGroup(updatedGroupObject);
355 response.setCharacterEncoding("UTF-8");
356 response.setContentType("application / json");
357 request.setCharacterEncoding("UTF-8");
359 PrintWriter out = response.getWriter();
361 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
362 JSONObject j = new JSONObject(msg);
364 out.write(j.toString());
369 response.setCharacterEncoding("UTF-8");
370 request.setCharacterEncoding("UTF-8");
371 PrintWriter out = response.getWriter();
372 out.write(e.getMessage());