2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * Modifications Copyright (C) 2019 Bell Canada
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.admin;
25 import com.att.research.xacml.util.XACMLProperties;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
29 import java.io.BufferedReader;
30 import java.io.BufferedWriter;
31 import java.io.ByteArrayInputStream;
33 import java.io.FileInputStream;
34 import java.io.FileOutputStream;
35 import java.io.FileWriter;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.OutputStream;
39 import java.io.PrintWriter;
40 import java.nio.charset.StandardCharsets;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.nio.file.Paths;
44 import java.util.ArrayList;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.List;
50 import java.util.Objects;
53 import javax.json.Json;
54 import javax.json.JsonArray;
55 import javax.json.JsonReader;
56 import javax.script.SimpleBindings;
57 import javax.servlet.ServletConfig;
58 import javax.servlet.ServletException;
59 import javax.servlet.annotation.WebInitParam;
60 import javax.servlet.annotation.WebServlet;
61 import javax.servlet.http.HttpServlet;
62 import javax.servlet.http.HttpServletRequest;
63 import javax.servlet.http.HttpServletResponse;
65 import org.apache.commons.compress.utils.IOUtils;
66 import org.apache.commons.fileupload.FileItem;
67 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
68 import org.apache.commons.fileupload.servlet.ServletFileUpload;
69 import org.apache.http.HttpStatus;
70 import org.elasticsearch.common.Strings;
71 import org.json.JSONArray;
72 import org.json.JSONException;
73 import org.json.JSONObject;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.components.HumanPolicyComponent;
77 import org.onap.policy.controller.PolicyController;
78 import org.onap.policy.controller.PolicyExportAndImportController;
79 import org.onap.policy.rest.XACMLRest;
80 import org.onap.policy.rest.XACMLRestProperties;
81 import org.onap.policy.rest.adapter.PolicyRestAdapter;
82 import org.onap.policy.rest.jpa.ActionBodyEntity;
83 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
84 import org.onap.policy.rest.jpa.PolicyEditorScopes;
85 import org.onap.policy.rest.jpa.PolicyEntity;
86 import org.onap.policy.rest.jpa.PolicyVersion;
87 import org.onap.policy.rest.jpa.UserInfo;
88 import org.onap.policy.utils.PeCryptoUtils;
89 import org.onap.policy.utils.PolicyUtils;
90 import org.onap.policy.utils.UserUtils.Pair;
91 import org.onap.policy.xacml.api.XACMLErrorConstants;
92 import org.onap.policy.xacml.util.XACMLPolicyScanner;
93 import org.onap.portalsdk.core.web.support.UserUtils;
98 initParams = {@WebInitParam(
99 name = "XACML_PROPERTIES_NAME",
100 value = "xacml.admin.properties",
101 description = "The location of the properties file holding configuration information.")})
102 public class PolicyManagerServlet extends HttpServlet {
103 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
104 private static final long serialVersionUID = -8453502699403909016L;
105 private static final String VERSION = "version";
106 private static final String NAME = "name";
107 private static final String DATE = "date";
108 private static final String SIZE = "size";
109 private static final String TYPE = "type";
110 private static final String ROLETYPE = "roleType";
111 private static final String CREATED_BY = "createdBy";
112 private static final String MODIFIED_BY = "modifiedBy";
113 private static final String CONTENTTYPE = "application/json";
114 private static final String SUPERADMIN = "super-admin";
115 private static final String SUPEREDITOR = "super-editor";
116 private static final String SUPERGUEST = "super-guest";
117 private static final String ADMIN = "admin";
118 private static final String EDITOR = "editor";
119 private static final String GUEST = "guest";
120 private static final String RESULT = "result";
121 private static final String DELETE = "delete";
122 private static final String EXCEPTION_OCCURED = "Exception Occured";
123 private static final String CONFIG = ".Config_";
124 private static final String CONFIG1 = ":Config_";
125 private static final String ACTION = ".Action_";
126 private static final String ACTION1 = ":Action_";
127 private static final String DECISION = ".Decision_";
128 private static final String DECISION1 = ":Decision_";
129 private static final String CONFIG2 = "Config_";
130 private static final String ACTION2 = "Action_";
131 private static final String DECISION2 = "Decision_";
132 private static final String FORWARD_SLASH = "/";
133 private static final String BACKSLASH = "\\";
134 private static final String ESCAPE_BACKSLASH = "\\\\";
135 private static final String BACKSLASH_8TIMES = "\\\\\\\\";
136 private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME =
137 "delete from PolicyVersion where policy_name ='";
138 private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
139 private static final String SPLIT_1 = "split_1";
140 private static final String SPLIT_0 = "split_0";
141 private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME =
142 "from PolicyEditorScopes where SCOPENAME like :scopeName";
143 private static final String SCOPE_NAME = "scopeName";
144 private static final String SUCCESS = "success";
145 private static final String SUB_SCOPENAME = "subScopename";
146 private static final String ALLSCOPES = "@All@";
147 private static final String PERCENT_AND_ID_GT_0 = "%' and id >0";
148 private static List<String> serviceTypeNamesList = new ArrayList<>();
149 private static JsonArray policyNames;
150 private static String testUserId = null;
167 private static PolicyController policyController;
169 private synchronized PolicyController getPolicyController() {
170 return policyController;
173 public static synchronized void setPolicyController(PolicyController policyController) {
174 PolicyManagerServlet.policyController = policyController;
177 public static JsonArray getPolicyNames() {
181 public static void setPolicyNames(JsonArray policyNames) {
182 PolicyManagerServlet.policyNames = policyNames;
185 public static List<String> getServiceTypeNamesList() {
186 return serviceTypeNamesList;
190 public void init(ServletConfig servletConfig) throws ServletException {
191 super.init(servletConfig);
193 // Common initialization
195 XACMLRest.xacmlInit(servletConfig);
196 // init aes key from prop or env
197 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
199 // Initialize ClosedLoop JSON
201 PolicyManagerServlet.initializeJsonLoad();
204 private static void initializeJsonLoad() {
205 Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
206 String location = closedLoopJsonLocation.toString();
207 if (!location.endsWith("json")) {
208 LOGGER.warn("JSONConfig file does not end with extension .json");
211 try (FileInputStream inputStream = new FileInputStream(location);
212 JsonReader jsonReader = Json.createReader(inputStream)) {
213 policyNames = jsonReader.readArray();
214 serviceTypeNamesList = new ArrayList<>();
215 for (int i = 0; i < policyNames.size(); i++) {
216 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
217 String name = policyName.getJsonString("serviceTypePolicyName").getString();
218 serviceTypeNamesList.add(name);
220 } catch (IOException e) {
221 LOGGER.error("Exception Occured while initializing the JSONConfig file" + e);
226 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
227 LOGGER.debug("doPost");
229 // if request contains multipart-form-data
230 if (ServletFileUpload.isMultipartContent(request)) {
231 uploadFile(request, response);
233 // all other post request has json params in body
235 fileOperation(request, response);
237 } catch (Exception e) {
239 setError(e, response);
240 } catch (Exception e1) {
241 LOGGER.error(EXCEPTION_OCCURED + e1);
246 // Set Error Message for Exception
247 private void setError(Exception exception, HttpServletResponse response) throws IOException {
249 JSONObject responseJsonObject = error(exception.getMessage());
250 response.setContentType(CONTENTTYPE);
251 PrintWriter out = response.getWriter();
252 out.print(responseJsonObject);
254 } catch (Exception x) {
255 LOGGER.error(EXCEPTION_OCCURED + x);
256 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
260 // Policy Import Functionality
261 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
263 Map<String, InputStream> files = new HashMap<>();
265 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
266 for (FileItem item : items) {
267 if (!item.isFormField()) {
268 // Process form file field (input type="file").
269 files.put(item.getName(), item.getInputStream());
270 processFormFile(request, item);
274 JSONObject responseJsonObject;
275 responseJsonObject = this.success();
276 response.setContentType(CONTENTTYPE);
277 PrintWriter out = response.getWriter();
278 out.print(responseJsonObject);
280 } catch (Exception e) {
281 LOGGER.debug("Cannot write file");
282 throw new ServletException("Cannot write file", e);
286 private void processFormFile(HttpServletRequest request, FileItem item) {
288 if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) {
289 File file = new File(item.getName());
290 try (OutputStream outputStream = new FileOutputStream(file)) {
291 IOUtils.copy(item.getInputStream(), outputStream);
292 newFile = file.toString();
293 PolicyExportAndImportController importController = new PolicyExportAndImportController();
294 importController.importRepositoryFile(newFile, request);
295 } catch (Exception e) {
296 LOGGER.error("Upload error : " + e);
298 } else if (!item.getName().endsWith(".xls")) {
299 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
300 } else { // uploaded file size is greater than allowed
301 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
305 // File Operation Functionality
306 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
307 JSONObject responseJsonObject;
308 StringBuilder sb = new StringBuilder();
309 try (BufferedReader br = request.getReader()) {
311 while ((str = br.readLine()) != null) {
314 } catch (Exception e) {
315 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
316 responseJsonObject = error(e.getMessage());
317 setResponse(response, responseJsonObject);
321 JSONObject jsonObject = new JSONObject(sb.toString());
322 JSONObject params = jsonObject.getJSONObject("params");
323 Mode mode = Mode.valueOf(params.getString("mode"));
325 String userId = UserUtils.getUserSession(request).getOrgUserId();
327 "********************Logging UserID while doing actions on Editor tab****************************");
329 "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString());
331 "************************************************************************************************");
332 responseJsonObject = operateBasedOnMode(mode, params, request);
333 } catch (Exception e) {
334 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
335 responseJsonObject = error(e.getMessage());
337 setResponse(response, responseJsonObject);
340 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
341 response.setContentType(CONTENTTYPE);
342 try (PrintWriter out = response.getWriter()) {
343 out.print(responseJsonObject);
345 } catch (IOException e) {
346 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
350 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request)
351 throws ServletException {
352 JSONObject responseJsonObject;
356 responseJsonObject = addFolder(params, request);
359 responseJsonObject = copy(params, request);
362 responseJsonObject = delete(params, request);
366 responseJsonObject = editFile(params);
369 responseJsonObject = list(params, request);
372 responseJsonObject = rename(params, request);
374 case DESCRIBEPOLICYFILE:
375 responseJsonObject = describePolicy(params);
378 responseJsonObject = switchVersion(params, request);
381 responseJsonObject = searchPolicyList(params, request);
384 throw new ServletException("not implemented");
386 if (responseJsonObject == null) {
387 responseJsonObject = error("generic error : responseJsonObject is null");
389 return responseJsonObject;
392 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
393 List<Object> policyData = new ArrayList<>();
394 JSONArray policyList = null;
395 if (params.has("policyList")) {
396 policyList = (JSONArray) params.get("policyList");
398 PolicyController controller = getPolicyControllerInstance();
399 List<JSONObject> resultList = new ArrayList<>();
401 if (!lookupPolicyData(request, policyData, policyList, controller, resultList)) {
402 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
404 } catch (Exception e) {
406 "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e);
409 return new JSONObject().put(RESULT, resultList);
412 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
413 PolicyController controller, List<JSONObject> resultList) {
415 Set<String> scopes;// Get the Login Id of the User from Request
416 String userId = UserUtils.getUserSession(request).getOrgUserId();
417 List<Object> userRoles = controller.getRoles(userId);
418 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
421 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
422 if (scopes.isEmpty()) {
425 for (String scope : scopes) {
426 addScope(scopes, scope);
429 if (policyList != null) {
430 for (int i = 0; i < policyList.length(); i++) {
431 String policyName = policyList.get(i).toString().replace(".xml", "");
432 String version = policyName.substring(policyName.lastIndexOf('.') + 1);
433 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
434 parsePolicyList(resultList, controller, policyName, version);
437 getPolicyDataForSuperRoles(policyData, controller, resultList, roles, scopes);
442 private void getPolicyDataForSuperRoles(List<Object> policyData, PolicyController controller,
443 List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
444 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
445 policyData = controller.getData(PolicyVersion.class);
447 List<Object> filterData = controller.getData(PolicyVersion.class);
448 for (Object filter : filterData) {
449 addFilterData(policyData, scopes, (PolicyVersion) filter);
453 if (!policyData.isEmpty()) {
454 updateResultList(policyData, resultList);
458 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
460 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
461 if (scopes.contains(scopeName)) {
462 policyData.add(filter);
464 } catch (Exception e) {
465 LOGGER.error("Exception occured while filtering policyversion data" + e);
469 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
470 for (Object data : policyData) {
471 PolicyVersion policy = (PolicyVersion) data;
472 JSONObject el = new JSONObject();
473 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
474 el.put(DATE, policy.getModifiedDate());
475 el.put(VERSION, policy.getActiveVersion());
477 el.put(TYPE, "file");
478 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
479 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
484 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName,
486 if (policyName.contains(BACKSLASH)) {
487 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
489 String policyVersionQuery =
490 "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
491 SimpleBindings pvParams = new SimpleBindings();
492 pvParams.put("policyName", policyName);
493 pvParams.put(VERSION, version);
494 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
495 if (!activeData.isEmpty()) {
496 PolicyVersion policy = (PolicyVersion) activeData.get(0);
497 JSONObject el = new JSONObject();
498 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
499 el.put(DATE, policy.getModifiedDate());
500 el.put(VERSION, policy.getActiveVersion());
502 el.put(TYPE, "file");
503 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
504 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
509 private void addScope(Set<String> scopes, String scope) {
510 List<Object> scopesList = queryPolicyEditorScopes(scope);
511 if (!scopesList.isEmpty()) {
512 for (Object scopeItem : scopesList) {
513 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopeItem;
514 scopes.add(tempScope.getScopeName());
519 // Switch Version Functionality
520 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException {
521 String path = params.getString("path");
522 String userId = null;
524 userId = UserUtils.getUserSession(request).getOrgUserId();
525 } catch (Exception e) {
526 LOGGER.error("Exception Occured while reading userid from cookie" + e);
529 String removeExtension = path.replace(".xml", "");
530 if (path.startsWith(FORWARD_SLASH)) {
531 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
533 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
537 PolicyController controller = getPolicyControllerInstance();
538 if (!params.toString().contains("activeVersion")) {
539 return controller.switchVersionPolicyContent(policyName);
541 String activeVersion = params.getString("activeVersion");
542 String highestVersion = params.get("highestVersion").toString();
543 if (Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)) {
544 return error("The Version shouldn't be greater than Highest Value");
546 activePolicy = policyName + "." + activeVersion + ".xml";
547 String[] splitDbCheckName = modifyPolicyName(activePolicy);
548 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
549 SimpleBindings policyParams = new SimpleBindings();
550 policyParams.put("splitDBCheckName_1", splitDbCheckName[1]);
551 policyParams.put("splitDBCheckName_0", splitDbCheckName[0]);
552 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
553 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
554 if (pentity.isDeleted()) {
555 return error("The Policy is Not Existing in Workspace");
557 if (policyName.contains(FORWARD_SLASH)) {
558 policyName = policyName.replace(FORWARD_SLASH, File.separator);
560 policyName = policyName.substring(policyName.indexOf(File.separator) + 1);
561 if (policyName.contains(BACKSLASH)) {
562 policyName = policyName.replace(File.separator, BACKSLASH);
564 policyName = splitDbCheckName[0].replace(".", File.separator) + File.separator + policyName;
565 final String watchPolicyName = policyName;
566 if (policyName.contains(FORWARD_SLASH)) {
567 policyName = policyName.replace(FORWARD_SLASH, File.separator);
569 if (policyName.contains(BACKSLASH)) {
570 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
572 String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + activeVersion + "' where policy_name ='" + policyName
574 // query the database
575 controller.executeQuery(query);
576 // Policy Notification
577 PolicyVersion entity = new PolicyVersion();
578 entity.setPolicyName(watchPolicyName);
579 entity.setActiveVersion(Integer.parseInt(activeVersion));
580 entity.setModifiedBy(userId);
581 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
586 private JSONObject describePolicy(JSONObject params) throws ServletException {
587 String path = params.getString("path");
589 if (path.startsWith(FORWARD_SLASH)) {
590 path = path.substring(1);
591 policyName = path.substring(path.lastIndexOf('/') + 1);
592 path = path.replace(FORWARD_SLASH, ".");
594 path = path.replace(FORWARD_SLASH, ".");
597 if (path.contains(CONFIG2)) {
598 path = path.replace(CONFIG, CONFIG1);
599 } else if (path.contains(ACTION2)) {
600 path = path.replace(ACTION, ACTION1);
601 } else if (path.contains(DECISION2)) {
602 path = path.replace(DECISION, DECISION1);
604 PolicyController controller = getPolicyControllerInstance();
605 String[] split = path.split(":");
606 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
607 SimpleBindings peParams = new SimpleBindings();
608 peParams.put(SPLIT_1, split[1]);
609 peParams.put(SPLIT_0, split[0]);
610 List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
611 if (queryData.isEmpty()) {
612 return error("Error Occured while Describing the Policy - query is empty");
614 PolicyEntity entity = (PolicyEntity) queryData.get(0);
617 temp = File.createTempFile(policyName, ".tmp");
618 } catch (IOException e) {
619 String message = "Failed to create temp file " + policyName + ".tmp";
620 LOGGER.error(message + e);
621 return error(message);
623 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
624 bw.write(entity.getPolicyData());
625 } catch (IOException e) {
626 LOGGER.error("Exception Occured while Describing the Policy" + e);
628 JSONObject object = HumanPolicyComponent.DescribePolicy(temp);
630 Files.delete(temp.toPath());
631 } catch (IOException e) {
632 LOGGER.warn("Failed to delete " + temp.getName() + e);
637 // Get the List of Policies and Scopes for Showing in Editor tab
638 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
640 return processPolicyList(params, request);
641 } catch (Exception e) {
642 LOGGER.error("list", e);
643 return error(e.getMessage());
647 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
648 PolicyController controller = getPolicyControllerInstance();
649 // Get the Login Id of the User from Request
650 String testUserID = getTestUserId();
651 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
652 List<Object> userRoles = controller.getRoles(userId);
653 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
654 List<String> roles = pair.u;
655 Set<String> scopes = pair.t;
656 Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
658 List<JSONObject> resultList = new ArrayList<>();
659 String path = params.getString("path");
660 if (path.contains("..xml")) {
661 path = path.replaceAll("..xml", "").trim();
664 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
666 && !(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST))) {
667 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
669 if (!FORWARD_SLASH.equals(path)) {
670 String tempScope = path.substring(1);
671 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
672 scopes.add(tempScope);
677 if (!FORWARD_SLASH.equals(path)) {
679 String scopeName = path.substring(path.indexOf('/') + 1);
680 activePolicyList(scopeName, resultList, roles, scopes, roleByScope);
681 } catch (Exception ex) {
682 LOGGER.error("Error Occurred While reading Policy Files List" + ex);
684 return new JSONObject().put(RESULT, resultList);
686 processRoles(scopes, roles, resultList, roleByScope);
687 return new JSONObject().put(RESULT, resultList);
690 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList,
691 Map<String, String> roleByScope) {
692 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
693 List<Object> scopesList = queryPolicyEditorScopes(null);
694 scopesList.stream().map(list -> (PolicyEditorScopes) list).filter(
695 scope -> !(scope.getScopeName().contains(File.separator)) && !scopes.contains(scope.getScopeName()))
697 JSONObject el = new JSONObject();
698 el.put(NAME, scope.getScopeName());
699 el.put(DATE, scope.getModifiedDate());
702 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
703 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
704 el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
708 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
709 scopes.stream().map(this::queryPolicyEditorScopes).filter(scopesList -> !scopesList.isEmpty())
710 .forEach(scopesList -> {
711 JSONObject el = new JSONObject();
712 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
713 el.put(NAME, scopeById.getScopeName());
714 el.put(DATE, scopeById.getModifiedDate());
717 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
718 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
719 if ((resultList).stream()
720 .noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
721 el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
728 private List<Object> queryPolicyEditorScopes(String scopeName) {
729 String scopeNameQuery;
730 SimpleBindings params = new SimpleBindings();
731 if (scopeName == null) {
732 scopeNameQuery = "from PolicyEditorScopes";
734 scopeNameQuery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
735 params.put(SCOPE_NAME, scopeName + "%");
737 PolicyController controller = getPolicyControllerInstance();
738 return getDataByQueryFromController(controller, scopeNameQuery, params);
741 // Get Active Policy List based on Scope Selection from Policy Version table
742 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
743 Set<String> scopes, Map<String, String> roleByScope) {
744 final PolicyController controller = getPolicyControllerInstance();
745 String scopeName = inScopeName;
746 if (scopeName.contains(FORWARD_SLASH)) {
747 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
749 if (scopeName.contains(BACKSLASH)) {
750 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
752 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
754 SimpleBindings params = new SimpleBindings();
755 params.put(SCOPE_NAME, scopeName + "%");
757 List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
758 List<Object> scopesList = getDataByQueryFromController(controller,
759 FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
760 for (Object list : scopesList) {
761 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
763 for (Object list : activePolicies) {
764 PolicyVersion policy = (PolicyVersion) list;
765 String scopeNameValue =
766 policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
767 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
768 String scopeNameCheck =
769 scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator)
771 if (!scopeNameValue.equals(scopeNameCheck)) {
774 JSONObject el = new JSONObject();
775 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
776 el.put(DATE, policy.getModifiedDate());
777 el.put(VERSION, policy.getActiveVersion());
779 el.put(TYPE, "file");
780 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
781 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
782 String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ? roleByScope.get(ALLSCOPES)
783 : roleByScope.get(scopeNameValue);
784 el.put(ROLETYPE, roleType);
786 } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) {
787 JSONObject el = new JSONObject();
788 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
789 el.put(DATE, policy.getModifiedDate());
790 el.put(VERSION, policy.getActiveVersion());
792 el.put(TYPE, "file");
793 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
794 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
800 private List<Object> getDataByQueryFromController(final PolicyController controller, final String query,
801 final SimpleBindings params) {
802 final List<Object> activePolicies;
803 if (PolicyController.isjUnit()) {
804 activePolicies = controller.getDataByQuery(query, null);
806 activePolicies = controller.getDataByQuery(query, params);
808 return activePolicies;
811 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById,
812 Map<String, String> roleByScope) {
813 String scope = scopeById.getScopeName();
814 if (!scope.contains(File.separator)) {
817 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
818 if (scopeName.contains(ESCAPE_BACKSLASH)) {
819 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
821 if (scope.contains(File.separator)) {
822 scope = scope.substring(targetScope.length() + 1);
823 if (scope.contains(File.separator)) {
824 scope = scope.substring(0, scope.indexOf(File.separator));
827 if (scopeName.equalsIgnoreCase(targetScope)) {
828 JSONObject el = new JSONObject();
830 el.put(DATE, scopeById.getModifiedDate());
833 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
834 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
835 String roleType = roleByScope.get(ALLSCOPES); // Set default role type to ALL_SCOPES
836 if (!Strings.isNullOrEmpty(roleByScope.get(scopeName))) {
837 roleType = roleByScope.get(scopeName);
838 } else if (!Strings.isNullOrEmpty(roleByScope.get(scopeName + File.separator + scope))) {
839 roleType = roleByScope.get(scopeName + File.separator + scope);
841 el.put(ROLETYPE, roleType);
847 private String getUserName(String loginId) {
848 PolicyController controller = getPolicyControllerInstance();
849 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
850 if (userInfo == null) {
853 return userInfo.getUserName();
857 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
859 return handlePolicyRename(params, request);
860 } catch (Exception e) {
861 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
862 return error(e.getMessage());
866 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
867 boolean isActive = false;
868 List<String> policyActiveInPdp = new ArrayList<>();
869 Set<String> scopeOfPolicyActiveInPdp = new HashSet<>();
870 String userId = UserUtils.getUserSession(request).getOrgUserId();
871 String oldPath = params.getString("path");
872 String newPath = params.getString("newPath");
873 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
874 newPath = newPath.substring(newPath.indexOf('/') + 1);
875 String checkValidation;
876 if (oldPath.endsWith(".xml")) {
877 checkValidation = newPath.replace(".xml", "");
879 checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
880 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1);
881 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
882 return error("Policy Rename Failed. The Name contains special characters.");
884 JSONObject result = policyRename(oldPath, newPath, userId);
885 if (!(Boolean) (result.getJSONObject(RESULT).get(SUCCESS))) {
889 String scopeName = oldPath;
890 String newScopeName = newPath;
891 if (scopeName.contains(FORWARD_SLASH)) {
892 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
893 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
895 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator) + 1);
896 if (scopeName.contains(BACKSLASH)) {
897 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
898 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
900 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
901 return error("Scope Rename Failed. The Name contains special characters.");
903 PolicyController controller = getPolicyControllerInstance();
904 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
905 SimpleBindings pvParams = new SimpleBindings();
906 pvParams.put(SCOPE_NAME, scopeName + "%");
907 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
908 List<Object> scopesList =
909 controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
910 for (Object object : activePolicies) {
911 PolicyVersion activeVersion = (PolicyVersion) object;
912 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "."
913 + activeVersion.getActiveVersion() + ".xml";
914 String policyNewPath = policyOldPath.replace(oldPath, newPath);
915 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
916 if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
918 policyActiveInPdp.add(policyOldPath);
919 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
920 scopeOfPolicyActiveInPdp.add(scope.replace(FORWARD_SLASH, File.separator));
923 boolean rename = activePolicies.size() != policyActiveInPdp.size();
924 if (policyActiveInPdp.isEmpty()) {
925 renameScope(scopesList, scopeName, newScopeName, controller);
927 renameScope(scopesList, scopeName, newScopeName, controller);
928 UserInfo userInfo = new UserInfo();
929 userInfo.setUserLoginId(userId);
930 scopeOfPolicyActiveInPdp.forEach(scope -> {
931 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
932 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
933 editorScopeEntity.setUserCreatedBy(userInfo);
934 editorScopeEntity.setUserModifiedBy(userInfo);
935 controller.saveData(editorScopeEntity);
939 return error("The Following policies rename failed. Since they are active in PDP Groups"
940 + policyActiveInPdp);
946 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName,
947 PolicyController controller) {
948 for (Object object : scopesList) {
949 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
950 String scopeName = inScopeName;
951 if (scopeName.contains(BACKSLASH_8TIMES)) {
952 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
953 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
955 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
956 editorScopeEntity.setScopeName(scope);
957 controller.updateData(editorScopeEntity);
961 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
964 PolicyController controller = getPolicyControllerInstance();
966 String policyVersionName = newPath.replace(".xml", "");
967 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
968 .replace(FORWARD_SLASH, File.separator);
970 String oldpolicyVersionName = oldPath.replace(".xml", "");
971 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.'))
972 .replace(FORWARD_SLASH, File.separator);
973 String newpolicyName = newPath.replace("/", ".");
974 String[] newPolicySplit = modifyPolicyName(newPath);
976 final String[] oldPolicySplit = modifyPolicyName(oldPath);
978 // Check PolicyEntity table with newPolicy Name
979 String policyEntityquery =
980 "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
981 SimpleBindings policyParams = new SimpleBindings();
982 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
983 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
984 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
985 if (!queryData.isEmpty()) {
986 return error("Policy rename failed. Since, the policy with same name already exists.");
989 // Query the Policy Entity with oldPolicy Name
990 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
991 String oldPolicyEntityQuery =
992 "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + ":oldPolicySplit_0";
993 SimpleBindings params = new SimpleBindings();
994 params.put("policyEntityCheck", policyEntityCheck + "%");
995 params.put("oldPolicySplit_0", oldPolicySplit[0]);
996 List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params);
997 if (oldEntityData.isEmpty()) {
999 "Policy rename failed due to policy not able to retrieve from database. Contact super-admin.");
1002 StringBuilder groupQuery = new StringBuilder();
1003 groupQuery.append("FROM PolicyGroupEntity where (");
1004 SimpleBindings geParams = new SimpleBindings();
1005 for (int i = 0; i < oldEntityData.size(); i++) {
1006 entity = (PolicyEntity) oldEntityData.get(i);
1008 groupQuery.append("policyid = :policyId");
1009 geParams.put("policyId", entity.getPolicyId());
1011 groupQuery.append(" or policyid = :policyId").append(i);
1012 geParams.put("policyId" + i, entity.getPolicyId());
1015 groupQuery.append(")");
1016 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
1017 if (!groupEntityData.isEmpty()) {
1018 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
1020 for (Object anOldEntityData : oldEntityData) {
1021 entity = (PolicyEntity) anOldEntityData;
1022 String checkEntityName = entity.getPolicyName().replace(".xml", "");
1023 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
1024 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
1025 if (checkEntityName.equals(originalPolicyName)) {
1026 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0],
1027 oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
1031 } catch (Exception e) {
1032 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
1033 return error(e.getMessage());
1037 private String[] modifyPolicyName(String pathName) {
1038 return modifyPolicyName(FORWARD_SLASH, pathName);
1041 private String[] modifyPolicyName(String separator, String pathName) {
1042 String policyName = pathName.replace(separator, ".");
1043 if (policyName.contains(CONFIG2)) {
1044 policyName = policyName.replace(CONFIG, CONFIG1);
1045 } else if (policyName.contains(ACTION2)) {
1046 policyName = policyName.replace(ACTION, ACTION1);
1047 } else if (policyName.contains(DECISION2)) {
1048 policyName = policyName.replace(DECISION, DECISION1);
1050 return policyName.split(":");
1053 private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removeNewPolicyExtension,
1054 String oldScope, String removeOldPolicyExtension, String policyName, String newPolicyName,
1055 String oldPolicyName, String userId) {
1057 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1058 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1059 PolicyController controller = getPolicyControllerInstance();
1061 String oldPolicyNameWithoutExtension = removeOldPolicyExtension;
1062 String newPolicyNameWithoutExtension = removeNewPolicyExtension;
1063 if (removeOldPolicyExtension.endsWith(".xml")) {
1064 oldPolicyNameWithoutExtension =
1065 oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
1066 newPolicyNameWithoutExtension =
1067 newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
1069 entity.setPolicyName(
1070 entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1071 entity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1072 newScope + "." + newPolicyNameWithoutExtension));
1073 entity.setScope(newScope);
1074 entity.setModifiedBy(userId);
1076 String oldConfigurationName = null;
1077 String newConfigurationName = null;
1078 if (newPolicyName.contains(CONFIG2)) {
1079 oldConfigurationName = configEntity.getConfigurationName();
1080 configEntity.setConfigurationName(
1081 configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1082 newScope + "." + newPolicyNameWithoutExtension));
1083 controller.updateData(configEntity);
1084 newConfigurationName = configEntity.getConfigurationName();
1085 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1086 if (file.exists()) {
1088 new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1089 file.renameTo(renameFile);
1091 } else if (newPolicyName.contains(ACTION2)) {
1092 oldConfigurationName = actionEntity.getActionBodyName();
1093 actionEntity.setActionBody(
1094 actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1095 newScope + "." + newPolicyNameWithoutExtension));
1096 controller.updateData(actionEntity);
1097 newConfigurationName = actionEntity.getActionBodyName();
1098 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1099 if (file.exists()) {
1101 new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1102 file.renameTo(renameFile);
1105 controller.updateData(entity);
1107 PolicyRestController restController = new PolicyRestController();
1108 restController.notifyOtherPapsToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1109 PolicyVersion versionEntity =
1110 (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName);
1111 versionEntity.setPolicyName(policyName);
1112 versionEntity.setModifiedBy(userId);
1113 controller.updateData(versionEntity);
1114 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1);
1115 String moveOldPolicyCheck = oldPolicyName.substring(oldPolicyName.lastIndexOf(File.separator) + 1);
1116 if (movePolicyCheck.equals(moveOldPolicyCheck)) {
1117 controller.watchPolicyFunction(versionEntity, oldPolicyName, "Move");
1119 controller.watchPolicyFunction(versionEntity, oldPolicyName, "Rename");
1121 } catch (Exception e) {
1122 LOGGER.error(EXCEPTION_OCCURED + e);
1127 private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
1128 String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException {
1129 String queryEntityName;
1130 PolicyController controller = getPolicyControllerInstance();
1131 PolicyEntity cloneEntity = new PolicyEntity();
1132 cloneEntity.setPolicyName(newpolicyName);
1133 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1134 String removenewPolicyExtension = inRemovenewPolicyExtension;
1135 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1136 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1137 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + removeoldPolicyExtension,
1138 newScope + "." + removenewPolicyExtension));
1139 cloneEntity.setScope(entity.getScope());
1140 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1141 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1142 String newConfigurationName = null;
1143 if (newpolicyName.contains(CONFIG2)) {
1144 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1145 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName()
1146 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1147 queryEntityName = configurationDataEntity.getConfigurationName();
1148 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1149 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1150 configurationDataEntity.setDeleted(false);
1151 configurationDataEntity.setCreatedBy(userId);
1152 configurationDataEntity.setModifiedBy(userId);
1153 controller.saveData(configurationDataEntity);
1154 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller
1155 .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1156 cloneEntity.setConfigurationData(configEntiy);
1157 newConfigurationName = configEntiy.getConfigurationName();
1158 try (FileWriter fw =
1159 new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1160 BufferedWriter bw = new BufferedWriter(fw)) {
1161 bw.write(configEntiy.getConfigBody());
1162 } catch (IOException e) {
1163 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1166 } else if (newpolicyName.contains(ACTION2)) {
1167 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1168 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName()
1169 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1170 queryEntityName = actionBodyEntity.getActionBodyName();
1171 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1172 actionBodyEntity.setDeleted(false);
1173 actionBodyEntity.setCreatedBy(userId);
1174 actionBodyEntity.setModifiedBy(userId);
1175 controller.saveData(actionBodyEntity);
1176 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class,
1177 "actionBodyName", queryEntityName);
1178 cloneEntity.setActionBodyEntity(actionEntiy);
1179 newConfigurationName = actionEntiy.getActionBodyName();
1180 try (FileWriter fw =
1181 new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1182 BufferedWriter bw = new BufferedWriter(fw)) {
1183 bw.write(actionEntiy.getActionBody());
1184 } catch (IOException e) {
1185 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1190 cloneEntity.setDeleted(entity.isDeleted());
1191 cloneEntity.setCreatedBy(userId);
1192 cloneEntity.setModifiedBy(userId);
1193 controller.saveData(cloneEntity);
1195 // Notify others paps regarding clone policy.
1196 PolicyRestController restController = new PolicyRestController();
1197 restController.notifyOtherPapsToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1201 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1203 String userId = UserUtils.getUserSession(request).getOrgUserId();
1204 String oldPath = params.getString("path");
1205 String newPath = params.getString("newPath");
1206 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
1207 newPath = newPath.substring(newPath.indexOf('/') + 1);
1209 String policyVersionName = newPath.replace(".xml", "");
1210 String version = policyVersionName.substring(policyVersionName.indexOf('.') + 1);
1211 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
1212 .replace(FORWARD_SLASH, File.separator);
1214 String newPolicyName = newPath.replace(FORWARD_SLASH, ".");
1216 String newPolicyCheck = newPolicyName;
1217 if (newPolicyCheck.contains(CONFIG2)) {
1218 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1219 } else if (newPolicyCheck.contains(ACTION2)) {
1220 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1221 } else if (newPolicyCheck.contains(DECISION2)) {
1222 newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
1224 if (!newPolicyCheck.contains(":")) {
1225 return error("Policy Clone Failed. The Name contains special characters.");
1227 String[] newPolicySplit = newPolicyCheck.split(":");
1229 String checkValidation = newPolicySplit[1].replace(".xml", "");
1231 checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
1232 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
1233 return error("Policy Clone Failed. The Name contains special characters.");
1236 String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
1238 final String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
1240 PolicyController controller = getPolicyControllerInstance();
1242 PolicyEntity entity = null;
1243 boolean success = false;
1245 // Check PolicyEntity table with newPolicy Name
1246 String policyEntityquery =
1247 "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1248 SimpleBindings policyParams = new SimpleBindings();
1249 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1250 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1251 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1252 if (!queryData.isEmpty()) {
1253 return error("Policy already exists with same name");
1256 // Query the Policy Entity with oldPolicy Name
1257 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1258 SimpleBindings peParams = new SimpleBindings();
1259 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1260 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1261 queryData = getDataByQueryFromController(controller, policyEntityquery, peParams);
1262 if (!queryData.isEmpty()) {
1263 entity = (PolicyEntity) queryData.get(0);
1265 if (entity != null) {
1266 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0],
1267 newPolicySplit[1], entity, userId);
1271 PolicyVersion entityItem = new PolicyVersion();
1272 entityItem.setActiveVersion(Integer.parseInt(version));
1273 entityItem.setHigherVersion(Integer.parseInt(version));
1274 entityItem.setPolicyName(policyName);
1275 entityItem.setCreatedBy(userId);
1276 entityItem.setModifiedBy(userId);
1277 entityItem.setModifiedDate(new Date());
1278 controller.saveData(entityItem);
1280 LOGGER.debug("copy from: {} to: {}" + oldPath + newPath);
1282 } catch (Exception e) {
1283 LOGGER.error("copy", e);
1284 return error(e.getMessage());
1288 // Delete Policy or Scope Functionality
1289 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1290 PolicyController controller = getPolicyControllerInstance();
1291 PolicyRestController restController = new PolicyRestController();
1292 PolicyEntity policyEntity = null;
1293 String policyNamewithoutExtension;
1295 String userId = UserUtils.getUserSession(request).getOrgUserId();
1296 String deleteVersion = "";
1297 String path = params.getString("path");
1298 LOGGER.debug("delete {}" + path);
1299 if (params.has("deleteVersion")) {
1300 deleteVersion = params.getString("deleteVersion");
1302 path = path.substring(path.indexOf('/') + 1);
1303 String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
1304 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1306 SimpleBindings policyParams = new SimpleBindings();
1307 if (path.endsWith(".xml")) {
1308 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1309 String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
1310 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1311 policyParams.put(SPLIT_1, split[1] + "%");
1312 policyParams.put(SPLIT_0, split[0]);
1314 policyNamewithoutExtension = path.replace(File.separator, ".");
1315 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension or scope = :exactScope";
1316 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + ".%");
1317 policyParams.put("exactScope", policyNamewithoutExtension);
1320 List<Object> policyEntityObjects = controller.getDataByQuery(query, policyParams);
1321 String activePolicyName = null;
1322 boolean pdpCheck = false;
1323 if (path.endsWith(".xml")) {
1324 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1325 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1));
1326 if ("ALL".equals(deleteVersion)) {
1327 if (!policyEntityObjects.isEmpty()) {
1328 for (Object object : policyEntityObjects) {
1329 policyEntity = (PolicyEntity) object;
1330 String groupEntityquery =
1331 "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'";
1332 SimpleBindings pgeParams = new SimpleBindings();
1333 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1334 if (!groupobject.isEmpty()) {
1336 activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1338 deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
1339 policyNamewithoutExtension);
1343 // Policy Notification
1344 PolicyVersion versionEntity = new PolicyVersion();
1345 versionEntity.setPolicyName(policyNamewithoutExtension);
1346 versionEntity.setModifiedBy(userId);
1347 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1349 // Delete from policyVersion table
1350 String getActivePdpPolicyVersion = activePolicyName.replace(".xml", "");
1351 getActivePdpPolicyVersion =
1352 getActivePdpPolicyVersion.substring(getActivePdpPolicyVersion.lastIndexOf('.') + 1);
1353 String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePdpPolicyVersion
1354 + "' , highest_version='" + getActivePdpPolicyVersion + "' where policy_name ='"
1355 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1356 controller.executeQuery(policyVersionQuery);
1358 "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
1359 + activePolicyName);
1361 // No Active Policy in PDP. So, deleting all entries from policyVersion table
1362 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1363 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1364 controller.executeQuery(policyVersionQuery);
1366 } else if ("CURRENT".equals(deleteVersion)) {
1367 String currentVersionPolicyName =
1368 policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator) + 1);
1369 String currentVersionScope =
1370 policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator))
1371 .replace(File.separator, ".");
1372 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and "
1373 + "scope = :currentVersionScope";
1375 SimpleBindings peParams = new SimpleBindings();
1376 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1377 peParams.put("currentVersionScope", currentVersionScope);
1379 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1380 if (!policyEntitys.isEmpty()) {
1381 policyEntity = (PolicyEntity) policyEntitys.get(0);
1383 if (policyEntity == null) {
1387 String groupEntityquery =
1388 "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1389 SimpleBindings geParams = new SimpleBindings();
1390 geParams.put("policyEntityId", policyEntity.getPolicyId());
1391 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1392 if (!groupobject.isEmpty()) {
1393 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"
1394 + policyEntity.getScope() + "." + policyEntity.getPolicyName() + "'");
1397 // Delete the entity from Elastic Search Database
1398 deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
1399 policyNamewithoutExtension);
1402 int highestVersion = 0;
1403 if (!policyEntityObjects.isEmpty()) {
1404 for (Object object : policyEntityObjects) {
1405 policyEntity = (PolicyEntity) object;
1406 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1407 int policyEntityVersion = Integer
1408 .parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.') + 1));
1409 if (policyEntityVersion > highestVersion && policyEntityVersion != version) {
1410 highestVersion = policyEntityVersion;
1415 // Policy Notification
1416 PolicyVersion entity = new PolicyVersion();
1417 entity.setPolicyName(policyNamewithoutExtension);
1418 entity.setActiveVersion(highestVersion);
1419 entity.setModifiedBy(userId);
1420 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1423 if (highestVersion != 0) {
1424 updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + highestVersion
1425 + "' , highest_version='" + highestVersion + "' where policy_name ='"
1426 + policyNamewithoutExtension.replace("\\", "\\\\") + "'";
1428 updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1429 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1431 controller.executeQuery(updatequery);
1433 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1434 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1435 controller.executeQuery(policyVersionQuery);
1439 List<String> activePoliciesInPdp = new ArrayList<>();
1440 if (policyEntityObjects.isEmpty()) {
1441 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1442 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1443 controller.executeQuery(policyScopeQuery);
1446 for (Object object : policyEntityObjects) {
1447 policyEntity = (PolicyEntity) object;
1448 String groupEntityQuery = "from PolicyGroupEntity where policyid = :policyEntityId";
1449 SimpleBindings geParams = new SimpleBindings();
1450 geParams.put("policyEntityId", policyEntity.getPolicyId());
1451 List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams);
1452 if (!groupobject.isEmpty()) {
1454 activePoliciesInPdp.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
1456 // Delete the entity from Elastic Search Database
1457 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1458 restController.deleteElasticData(searchFileName);
1459 // Delete the entity from Policy Entity table
1460 controller.deleteData(policyEntity);
1461 policyNamewithoutExtension = policyEntity.getPolicyName();
1462 if (policyNamewithoutExtension.contains(CONFIG2)) {
1463 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1464 + policyEntity.getConfigurationData().getConfigurationName()));
1465 controller.deleteData(policyEntity.getConfigurationData());
1466 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1467 policyEntity.getConfigurationData().getConfigurationName());
1468 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1469 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1470 + policyEntity.getActionBodyEntity().getActionBodyName()));
1471 controller.deleteData(policyEntity.getActionBodyEntity());
1472 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1473 policyEntity.getActionBodyEntity().getActionBodyName());
1477 // Delete from policyVersion and policyEditor Scope table
1478 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"
1479 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + File.separator + PERCENT_AND_ID_GT_0;
1480 controller.executeQuery(policyVersionQuery);
1482 // Policy Notification
1483 PolicyVersion entity = new PolicyVersion();
1484 entity.setPolicyName(path);
1485 entity.setModifiedBy(userId);
1486 controller.watchPolicyFunction(entity, path, "DeleteScope");
1488 // Add Active Policies List to PolicyVersionTable
1489 for (String anActivePoliciesInPdp : activePoliciesInPdp) {
1490 String activePdpPolicyName = anActivePoliciesInPdp.replace(".xml", "");
1491 int activePdpPolicyVersion = Integer
1492 .parseInt(activePdpPolicyName.substring(activePdpPolicyName.lastIndexOf('.') + 1));
1493 activePdpPolicyName = activePdpPolicyName.substring(0, activePdpPolicyName.lastIndexOf('.'))
1494 .replace(".", File.separator);
1495 PolicyVersion insertActivePdpVersion = new PolicyVersion();
1496 insertActivePdpVersion.setPolicyName(activePdpPolicyName);
1497 insertActivePdpVersion.setHigherVersion(activePdpPolicyVersion);
1498 insertActivePdpVersion.setActiveVersion(activePdpPolicyVersion);
1499 insertActivePdpVersion.setCreatedBy(userId);
1500 insertActivePdpVersion.setModifiedBy(userId);
1501 controller.saveData(insertActivePdpVersion);
1503 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"
1504 + activePoliciesInPdp);
1506 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1507 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1508 controller.executeQuery(policyScopeQuery);
1513 } catch (Exception e) {
1514 LOGGER.error(DELETE, e);
1515 return error(e.getMessage());
1519 private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller,
1520 final PolicyRestController restController, final PolicyEntity policyEntity,
1521 final String policyNamewithoutExtension) throws IOException {
1522 // Delete the entity from Elastic Search Database
1523 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1524 restController.deleteElasticData(searchFileName);
1525 // Delete the entity from Policy Entity table
1526 controller.deleteData(policyEntity);
1527 if (policyNamewithoutExtension.contains(CONFIG2)) {
1528 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1529 + policyEntity.getConfigurationData().getConfigurationName()));
1530 controller.deleteData(policyEntity.getConfigurationData());
1531 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1532 policyEntity.getConfigurationData().getConfigurationName());
1533 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1534 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1535 + policyEntity.getActionBodyEntity().getActionBodyName()));
1536 controller.deleteData(policyEntity.getActionBodyEntity());
1537 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1538 policyEntity.getActionBodyEntity().getActionBodyName());
1543 private JSONObject editFile(JSONObject params) throws ServletException {
1546 final PolicyController controller = getPolicyControllerInstance();
1547 final String mode = params.getString("mode");
1548 String path = params.getString("path");
1549 LOGGER.debug("editFile path: {}" + path);
1551 String domain = path.substring(1, path.lastIndexOf('/'));
1552 domain = domain.replace(FORWARD_SLASH, ".");
1554 path = path.substring(1);
1555 path = path.replace(FORWARD_SLASH, ".");
1557 String[] split = modifyPolicyName(path);
1559 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1560 SimpleBindings peParams = new SimpleBindings();
1561 peParams.put(SPLIT_1, split[1]);
1562 peParams.put(SPLIT_0, split[0]);
1563 List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
1564 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1565 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1567 Object policy = XACMLPolicyScanner.readPolicy(stream);
1568 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1569 policyAdapter.setData(policy);
1571 if ("viewPolicy".equalsIgnoreCase(mode)) {
1572 policyAdapter.setReadOnly(true);
1573 policyAdapter.setEditPolicy(false);
1575 policyAdapter.setReadOnly(false);
1576 policyAdapter.setEditPolicy(true);
1579 policyAdapter.setDomainDir(domain);
1580 policyAdapter.setPolicyData(policy);
1581 String policyName = path.replace(".xml", "");
1582 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1583 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1));
1585 PolicyAdapter setPolicyAdapter = PolicyAdapter.getInstance();
1586 Objects.requireNonNull(setPolicyAdapter).configure(policyAdapter, entity);
1588 policyAdapter.setParentPath(null);
1589 ObjectMapper mapper = new ObjectMapper();
1590 String json = mapper.writeValueAsString(policyAdapter);
1591 JsonNode jsonNode = mapper.readTree(json);
1593 return new JSONObject().put(RESULT, jsonNode);
1594 } catch (Exception e) {
1595 LOGGER.error("editFile", e);
1596 return error(e.getMessage());
1601 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1602 PolicyController controller = getPolicyControllerInstance();
1604 String name = getNameFromParams(params);
1605 String validateName =
1606 name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
1607 if (!name.isEmpty()) {
1608 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1609 if (!validate.contains(SUCCESS)) {
1610 return error(validate);
1612 LOGGER.debug("addFolder path: {} name: {}" + params.getString("path") + name);
1613 if (name.startsWith(File.separator)) {
1614 name = name.substring(1);
1616 PolicyEditorScopes entity =
1617 (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
1618 if (entity != null) {
1619 return error("Scope Already Exists");
1621 String userId = UserUtils.getUserSession(request).getOrgUserId();
1622 UserInfo userInfo = new UserInfo();
1623 userInfo.setUserLoginId(userId);
1624 PolicyEditorScopes newScope = new PolicyEditorScopes();
1625 newScope.setScopeName(name);
1626 newScope.setUserCreatedBy(userInfo);
1627 newScope.setUserModifiedBy(userInfo);
1628 controller.saveData(newScope);
1631 } catch (Exception e) {
1632 LOGGER.error("addFolder", e);
1633 return error(e.getMessage());
1637 private String getNameFromParams(final JSONObject params) {
1640 if (params.has(SUB_SCOPENAME)) {
1641 if (!"".equals(params.getString(SUB_SCOPENAME))) {
1642 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator
1643 + params.getString(SUB_SCOPENAME);
1646 name = params.getString(NAME);
1648 } catch (Exception e) {
1649 name = params.getString(NAME);
1650 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occurred While Adding Scope" + e);
1655 // Return Error Object
1656 private JSONObject error(String msg) throws ServletException {
1658 JSONObject result = new JSONObject();
1659 result.put(SUCCESS, false);
1660 result.put("error", msg);
1661 return new JSONObject().put(RESULT, result);
1662 } catch (JSONException e) {
1663 throw new ServletException(e);
1667 // Return Success Object
1668 private JSONObject success() throws ServletException {
1670 JSONObject result = new JSONObject();
1671 result.put(SUCCESS, true);
1672 result.put("error", (Object) null);
1673 return new JSONObject().put(RESULT, result);
1674 } catch (JSONException e) {
1675 throw new ServletException(e);
1679 private PolicyController getPolicyControllerInstance() {
1680 return policyController != null ? getPolicyController() : new PolicyController();
1683 private String getTestUserId() {
1687 public static void setTestUserId(String testUserId) {
1688 PolicyManagerServlet.testUserId = testUserId;