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.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
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.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.policy.model.Roles;
59 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
60 import org.openecomp.portalsdk.core.web.support.JsonMessage;
61 import org.openecomp.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;
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;
76 @RequestMapping({"/"})
77 public class AutoPushController extends RestrictedBaseController{
79 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
82 CommonClassDao commonClassDao;
84 private PDPGroupContainer container;
85 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
87 private PDPPolicyContainer policyContainer;
89 private PolicyController policyController;
90 public PolicyController getPolicyController() {
91 return policyController;
94 public void setPolicyController(PolicyController policyController) {
95 this.policyController = policyController;
98 private List<Object> data;
100 public synchronized void refreshGroups() {
101 synchronized(this.groups) {
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);
114 private PolicyController getPolicyControllerInstance(){
115 return policyController != null ? getPolicyController() : new PolicyController();
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){
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]);
141 if(!userRole.getScope().equals("")){
142 scopes.add(userRole.getScope());
147 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
148 data = commonClassDao.getData(PolicyVersion.class);
150 if(!scopes.isEmpty()){
151 for(String scope : scopes){
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));
164 PolicyVersion emptyPolicyName = new PolicyVersion();
165 emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
166 data.add(emptyPolicyName);
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());
175 logger.error("Exception Occured"+e);
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 {
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 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
191 for (Object pdpGroupId : adapter.getPdpDatas()) {
192 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
193 for(OnapPDPGroup pdpGroup : this.groups){
194 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
195 selectedPDPS.add(pdpGroup);
200 for (Object policyId : adapter.getPolicyDatas()) {
201 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
202 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
203 selectedPoliciesInUI.add(policyName);
206 for (Object pdpDestinationGroupId : selectedPDPS) {
207 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
208 Set<PDPPolicy> selectedPolicies = new HashSet<>();
209 for (String policyId : selectedPoliciesInUI) {
210 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
213 // Get the current selection
214 String selectedItem = policyId;
216 assert (selectedItem != null);
217 // create the id of the target file
218 // Our standard for file naming is:
219 // <domain>.<filename>.<version>.xml
220 // since the file name usually has a ".xml", we need to strip
222 // before adding the other parts
223 String name = selectedItem.replace(File.separator, ".");
225 if (id.endsWith(".xml")) {
226 id = id.replace(".xml", "");
227 id = id.substring(0, id.lastIndexOf("."));
230 // Default policy to be Root policy; user can change to deferred
233 StdPDPPolicy selectedPolicy = null;
234 String dbCheckName = name;
235 if(dbCheckName.contains("Config_")){
236 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
237 }else if(dbCheckName.contains("Action_")){
238 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
239 }else if(dbCheckName.contains("Decision_")){
240 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
242 String[] split = dbCheckName.split(":");
243 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
244 SimpleBindings policyParams = new SimpleBindings();
245 policyParams.put("split_1", split[1]);
246 policyParams.put("split_0", split[0]);
247 List<Object> queryData = controller.getDataByQuery(query, policyParams);
248 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
249 File temp = new File(name);
250 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
251 bw.write(policyEntity.getPolicyData());
253 URI selectedURI = temp.toURI();
257 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
258 } catch (IOException e) {
259 logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e);
261 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
262 if (selectedPolicy != null) {
263 // Add Current policies from container
264 for (OnapPDPGroup group : container.getGroups()) {
265 if (group.getId().equals(selectedGroup.getId())) {
266 currentPoliciesInGroup.addAll(group.getPolicies());
269 // copy policy to PAP
271 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
272 } catch (PAPException e) {
273 logger.error("Exception Occured"+e);
276 selectedPolicies.add(selectedPolicy);
280 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
281 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
282 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
283 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
284 updatedGroupObject.setStatus(pdpGroup.getStatus());
286 // replace the original set of Policies with the set from the
287 // container (possibly modified by the user)
288 // do not allow multiple copies of same policy
289 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
290 logger.debug("policyIterator....." + selectedPolicies);
291 while (policyIterator.hasNext()) {
292 PDPPolicy existingPolicy = policyIterator.next();
293 for (PDPPolicy selPolicy : selectedPolicies) {
294 if (selPolicy.getName().equals(existingPolicy.getName())) {
295 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
296 if (selPolicy.getId().equals(existingPolicy.getId())) {
297 policyIterator.remove();
298 logger.debug("Removing policy: " + selPolicy);
302 policyIterator.remove();
303 logger.debug("Removing Old Policy version: "+ selPolicy);
310 currentPoliciesInGroup.addAll(selectedPolicies);
311 updatedGroupObject.setPolicies(currentPoliciesInGroup);
312 this.container.updateGroup(updatedGroupObject);
314 response.setCharacterEncoding("UTF-8");
315 response.setContentType("application / json");
316 request.setCharacterEncoding("UTF-8");
318 PrintWriter out = response.getWriter();
320 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
321 JSONObject j = new JSONObject(msg);
322 out.write(j.toString());
327 response.setCharacterEncoding("UTF-8");
328 request.setCharacterEncoding("UTF-8");
329 PrintWriter out = response.getWriter();
331 out.write(e.getMessage());
336 @SuppressWarnings("unchecked")
337 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
338 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
340 PolicyController controller = getPolicyControllerInstance();
341 this.container = new PDPGroupContainer(controller.getPapEngine());
342 ObjectMapper mapper = new ObjectMapper();
343 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
344 JsonNode root = mapper.readTree(request.getReader());
345 StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
346 JsonNode removePolicyData = root.get("data");
347 policyContainer = new PDPPolicyContainer(group);
348 if(removePolicyData.size() > 0){
349 for(int i = 0 ; i < removePolicyData.size(); i++){
350 String data = removePolicyData.get(i).toString();
351 this.policyContainer.removeItem(data);
353 Set<PDPPolicy> changedPolicies = new HashSet<>();
354 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
355 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
356 updatedGroupObject.setPolicies(changedPolicies);
357 updatedGroupObject.setOnapPdps(group.getOnapPdps());
358 updatedGroupObject.setPipConfigs(group.getPipConfigs());
359 updatedGroupObject.setStatus(group.getStatus());
360 this.container.updateGroup(updatedGroupObject);
363 response.setCharacterEncoding("UTF-8");
364 response.setContentType("application / json");
365 request.setCharacterEncoding("UTF-8");
367 PrintWriter out = response.getWriter();
369 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
370 JSONObject j = new JSONObject(msg);
372 out.write(j.toString());
377 response.setCharacterEncoding("UTF-8");
378 request.setCharacterEncoding("UTF-8");
379 PrintWriter out = response.getWriter();
381 out.write(e.getMessage());