2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 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;
28 import java.io.BufferedReader;
29 import java.io.BufferedWriter;
30 import java.io.ByteArrayInputStream;
32 import java.io.FileInputStream;
33 import java.io.FileOutputStream;
34 import java.io.FileWriter;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.io.PrintWriter;
39 import java.nio.charset.StandardCharsets;
40 import java.nio.file.Files;
41 import java.nio.file.Path;
42 import java.nio.file.Paths;
43 import java.util.ArrayList;
44 import java.util.Date;
45 import java.util.HashMap;
46 import java.util.HashSet;
47 import java.util.List;
49 import java.util.Objects;
51 import javax.json.Json;
52 import javax.json.JsonArray;
53 import javax.json.JsonReader;
54 import javax.script.SimpleBindings;
55 import javax.servlet.ServletConfig;
56 import javax.servlet.ServletException;
57 import javax.servlet.annotation.WebInitParam;
58 import javax.servlet.annotation.WebServlet;
59 import javax.servlet.http.HttpServlet;
60 import javax.servlet.http.HttpServletRequest;
61 import javax.servlet.http.HttpServletResponse;
62 import org.apache.commons.compress.utils.IOUtils;
63 import org.apache.commons.fileupload.FileItem;
64 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
65 import org.apache.commons.fileupload.servlet.ServletFileUpload;
66 import org.apache.commons.lang3.StringUtils;
67 import org.apache.http.HttpStatus;
68 import org.elasticsearch.common.Strings;
69 import org.json.JSONArray;
70 import org.json.JSONException;
71 import org.json.JSONObject;
72 import org.onap.policy.common.logging.flexlogger.FlexLogger;
73 import org.onap.policy.common.logging.flexlogger.Logger;
74 import org.onap.policy.components.HumanPolicyComponent;
75 import org.onap.policy.controller.PolicyController;
76 import org.onap.policy.controller.PolicyExportAndImportController;
77 import org.onap.policy.rest.XacmlRest;
78 import org.onap.policy.rest.XacmlRestProperties;
79 import org.onap.policy.rest.adapter.PolicyRestAdapter;
80 import org.onap.policy.rest.jpa.ActionBodyEntity;
81 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
82 import org.onap.policy.rest.jpa.PolicyEditorScopes;
83 import org.onap.policy.rest.jpa.PolicyEntity;
84 import org.onap.policy.rest.jpa.PolicyVersion;
85 import org.onap.policy.rest.jpa.UserInfo;
86 import org.onap.policy.utils.PeCryptoUtils;
87 import org.onap.policy.utils.PolicyUtils;
88 import org.onap.policy.utils.UserUtils.Pair;
89 import org.onap.policy.xacml.api.XACMLErrorConstants;
90 import org.onap.policy.xacml.util.XACMLPolicyScanner;
91 import org.onap.portalsdk.core.domain.User;
92 import org.onap.portalsdk.core.web.support.UserUtils;
97 initParams = {@WebInitParam(
98 name = "XACML_PROPERTIES_NAME",
99 value = "xacml.admin.properties",
100 description = "The location of the properties file holding configuration information.")})
101 public class PolicyManagerServlet extends HttpServlet {
102 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
103 private static final long serialVersionUID = -8453502699403909016L;
104 private static final String VERSION = "version";
105 private static final String NAME = "name";
106 private static final String DATE = "date";
107 private static final String SIZE = "size";
108 private static final String TYPE = "type";
109 private static final String ROLETYPE = "roleType";
110 private static final String CREATED_BY = "createdBy";
111 private static final String MODIFIED_BY = "modifiedBy";
112 private static final String CONTENTTYPE = "application/json";
113 private static final String SUPERADMIN = "super-admin";
114 private static final String SUPEREDITOR = "super-editor";
115 private static final String SUPERGUEST = "super-guest";
116 private static final String ADMIN = "admin";
117 private static final String EDITOR = "editor";
118 private static final String GUEST = "guest";
119 private static final String RESULT = "result";
120 private static final String DELETE = "delete";
121 private static final String EXCEPTION_OCCURED = "Exception Occured";
122 private static final String CONFIG = ".Config_";
123 private static final String CONFIG1 = ":Config_";
124 private static final String ACTION = ".Action_";
125 private static final String ACTION1 = ":Action_";
126 private static final String DECISION = ".Decision_";
127 private static final String DECISION1 = ":Decision_";
128 private static final String CONFIG2 = "Config_";
129 private static final String ACTION2 = "Action_";
130 private static final String DECISION2 = "Decision_";
131 private static final String FORWARD_SLASH = "/";
132 private static final String BACKSLASH = "\\";
133 private static final String ESCAPE_BACKSLASH = "\\\\";
134 private static final String BACKSLASH_8TIMES = "\\\\\\\\";
135 private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME =
136 "delete from PolicyVersion where policy_name ='";
137 private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
138 private static final String SPLIT_1 = "split_1";
139 private static final String SPLIT_0 = "split_0";
140 private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME =
141 "from PolicyEditorScopes where SCOPENAME like :scopeName";
142 private static final String SCOPE_NAME = "scopeName";
143 private static final String SUCCESS = "success";
144 private static final String SUB_SCOPENAME = "subScopename";
145 private static final String ALLSCOPES = "@All@";
146 private static final String PERCENT_AND_ID_GT_0 = "%' and id >0";
147 private static List<String> serviceTypeNamesList = new ArrayList<>();
148 private static JsonArray policyNames;
149 private static String testUserId = null;
166 private static PolicyController policyController;
168 private synchronized PolicyController getPolicyController() {
169 return policyController;
172 public static synchronized void setPolicyController(PolicyController policyController) {
173 PolicyManagerServlet.policyController = policyController;
176 public static JsonArray getPolicyNames() {
180 public static void setPolicyNames(JsonArray policyNames) {
181 PolicyManagerServlet.policyNames = policyNames;
184 public static List<String> getServiceTypeNamesList() {
185 return serviceTypeNamesList;
189 public void init(ServletConfig servletConfig) throws ServletException {
190 super.init(servletConfig);
192 // Common initialization
194 XacmlRest.xacmlInit(servletConfig);
195 // init aes key from prop or env
196 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
198 // Initialize ClosedLoop JSON
200 PolicyManagerServlet.initializeJsonLoad();
203 private static void initializeJsonLoad() {
204 Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_CLOSEDLOOP));
205 String location = closedLoopJsonLocation.toString();
206 if (!location.endsWith("json")) {
207 LOGGER.warn("JSONConfig file does not end with extension .json");
210 try (FileInputStream inputStream = new FileInputStream(location);
211 JsonReader jsonReader = Json.createReader(inputStream)) {
212 policyNames = jsonReader.readArray();
213 serviceTypeNamesList = new ArrayList<>();
214 for (int i = 0; i < policyNames.size(); i++) {
215 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
216 String name = policyName.getJsonString("serviceTypePolicyName").getString();
217 serviceTypeNamesList.add(name);
219 } catch (IOException e) {
220 LOGGER.error("Exception Occured while initializing the JSONConfig file" + e);
225 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
226 LOGGER.debug("doPost");
228 // if request contains multipart-form-data
229 if (isMultipartContent(request)) {
230 uploadFile(request, response);
232 // all other post request has json params in body
234 fileOperation(request, response);
236 } catch (Exception e) {
238 setError(e, response);
239 } catch (Exception e1) {
240 LOGGER.error(EXCEPTION_OCCURED + e1);
245 protected boolean isMultipartContent(HttpServletRequest request) {
246 return ServletFileUpload.isMultipartContent(request);
249 // Set Error Message for Exception
250 private void setError(Exception exception, HttpServletResponse response) throws IOException {
252 JSONObject responseJsonObject = error(exception.getMessage());
253 response.setContentType(CONTENTTYPE);
254 PrintWriter out = response.getWriter();
255 out.print(responseJsonObject);
257 } catch (Exception x) {
258 LOGGER.error(EXCEPTION_OCCURED + x);
259 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
263 // Policy Import Functionality
264 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
266 Map<String, InputStream> files = new HashMap<>();
268 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
269 for (FileItem item : items) {
270 if (!item.isFormField()) {
271 // Process form file field (input type="file").
272 files.put(item.getName(), item.getInputStream());
273 resp = processFormFile(request, item, response);
277 response.setContentType(CONTENTTYPE);
278 PrintWriter out = response.getWriter();
279 JSONObject responseJsonObject;
280 if (!StringUtils.isBlank(resp)) {
281 responseJsonObject = this.error("Import Issue " + resp);
283 responseJsonObject = this.success();
285 out.print(responseJsonObject);
287 } catch (Exception e) {
288 LOGGER.debug("Cannot write file");
289 throw new ServletException("Cannot write file", e);
293 private String processFormFile(HttpServletRequest request, FileItem item, HttpServletResponse response) {
295 String outPutResp = null;
296 if (item.getName().endsWith(".xls") && item.getSize() <= getFileSizeLimit()) {
297 File file = new File(item.getName());
298 try (OutputStream outputStream = new FileOutputStream(file)) {
299 IOUtils.copy(item.getInputStream(), outputStream);
300 newFile = file.toString();
301 PolicyExportAndImportController importController = new PolicyExportAndImportController();
302 return importController.importRepositoryFile(newFile, request);
303 } catch (Exception e) {
304 LOGGER.error("Upload error : " + e);
306 } else if (!item.getName().endsWith(".xls")) {
307 outPutResp = "Non .xls filetype uploaded: " + item.getName();
308 LOGGER.error(outPutResp);
309 } else { // uploaded file size is greater than allowed
310 outPutResp = "Upload file size limit exceeded! File size (Bytes) is: " + item.getSize();
311 LOGGER.error(outPutResp);
316 protected long copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
317 return IOUtils.copy(inputStream, outputStream);
320 protected long getFileSizeLimit() {
321 return PolicyController.getFileSizeLimit();
324 // File Operation Functionality
325 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
326 JSONObject responseJsonObject;
327 StringBuilder sb = new StringBuilder();
328 try (BufferedReader br = request.getReader()) {
330 while ((str = br.readLine()) != null) {
333 } catch (Exception e) {
334 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
335 responseJsonObject = error(e.getMessage());
336 setResponse(response, responseJsonObject);
340 JSONObject jsonObject = new JSONObject(sb.toString());
341 JSONObject params = jsonObject.getJSONObject("params");
342 Mode mode = Mode.valueOf(params.getString("mode"));
344 String userId = getUserSession(request).getOrgUserId();
346 "********************Logging UserID while doing actions on Editor tab****************************");
348 "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString());
350 "************************************************************************************************");
351 responseJsonObject = operateBasedOnMode(mode, params, request);
352 } catch (Exception e) {
353 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
354 responseJsonObject = error(e.getMessage());
356 setResponse(response, responseJsonObject);
359 protected User getUserSession(HttpServletRequest request) {
360 return UserUtils.getUserSession(request);
363 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
364 response.setContentType(CONTENTTYPE);
365 try (PrintWriter out = response.getWriter()) {
366 out.print(responseJsonObject);
368 } catch (IOException e) {
369 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
373 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request)
374 throws ServletException {
375 JSONObject responseJsonObject;
379 responseJsonObject = addFolder(params, request);
382 responseJsonObject = copy(params, request);
385 responseJsonObject = delete(params, request);
389 responseJsonObject = editFile(params);
392 responseJsonObject = list(params, request);
395 responseJsonObject = rename(params, request);
397 case DESCRIBEPOLICYFILE:
398 responseJsonObject = describePolicy(params);
401 responseJsonObject = switchVersion(params, request);
404 responseJsonObject = searchPolicyList(params, request);
407 throw new ServletException("not implemented");
409 if (responseJsonObject == null) {
410 responseJsonObject = error("generic error : responseJsonObject is null");
412 return responseJsonObject;
415 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
416 JSONArray policyList = null;
417 if (params.has("policyList")) {
418 policyList = (JSONArray) params.get("policyList");
420 PolicyController controller = getPolicyControllerInstance();
421 List<JSONObject> resultList = new ArrayList<>();
423 if (!lookupPolicyData(request, new ArrayList<>(), policyList, controller, resultList)) {
424 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
426 } catch (Exception e) {
428 "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e);
431 return new JSONObject().put(RESULT, resultList);
434 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
435 PolicyController controller, List<JSONObject> resultList) {
436 String userId = getUserSession(request).getOrgUserId();
437 List<Object> userRoles = controller.getRoles(userId);
438 Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles);
439 List<String> roles = pair.second;
440 Set<String> scopes = pair.first;
441 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
442 if (scopes.isEmpty()) {
445 for (String scope : scopes) {
446 addScope(scopes, scope);
449 if (policyList != null) {
450 for (int i = 0; i < policyList.length(); i++) {
451 String policyName = policyList.get(i).toString().replace(".xml", "");
452 String version = policyName.substring(policyName.lastIndexOf('.') + 1);
453 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
454 parsePolicyList(resultList, controller, policyName, version);
457 getPolicyDataForSuperRoles(policyData, controller, resultList, roles, scopes);
462 protected Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
463 return org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
466 private void getPolicyDataForSuperRoles(List<Object> policyData, PolicyController controller,
467 List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
468 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
469 policyData = controller.getData(PolicyVersion.class);
471 List<Object> filterData = controller.getData(PolicyVersion.class);
472 for (Object filter : filterData) {
473 addFilterData(policyData, scopes, (PolicyVersion) filter);
477 if (!policyData.isEmpty()) {
478 updateResultList(policyData, resultList);
482 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
484 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
485 if (scopes.contains(scopeName)) {
486 policyData.add(filter);
488 } catch (Exception e) {
489 LOGGER.error("Exception occured while filtering policyversion data" + e);
493 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
494 for (Object data : policyData) {
495 PolicyVersion policy = (PolicyVersion) data;
496 JSONObject el = new JSONObject();
497 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
498 el.put(DATE, policy.getModifiedDate());
499 el.put(VERSION, policy.getActiveVersion());
501 el.put(TYPE, "file");
502 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
503 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
508 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName,
510 if (policyName.contains(BACKSLASH)) {
511 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
513 String policyVersionQuery =
514 "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
515 SimpleBindings pvParams = new SimpleBindings();
516 pvParams.put("policyName", policyName);
517 pvParams.put(VERSION, version);
518 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
519 if (!activeData.isEmpty()) {
520 PolicyVersion policy = (PolicyVersion) activeData.get(0);
521 JSONObject el = new JSONObject();
522 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
523 el.put(DATE, policy.getModifiedDate());
524 el.put(VERSION, policy.getActiveVersion());
526 el.put(TYPE, "file");
527 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
528 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
533 private void addScope(Set<String> scopes, String scope) {
534 List<Object> scopesList = queryPolicyEditorScopes(scope);
535 if (!scopesList.isEmpty()) {
536 for (Object scopeItem : scopesList) {
537 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopeItem;
538 scopes.add(tempScope.getScopeName());
543 // Switch Version Functionality
544 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException {
545 String path = params.getString("path");
546 String userId = null;
548 userId = getUserSession(request).getOrgUserId();
549 } catch (Exception e) {
550 LOGGER.error("Exception Occured while reading userid from cookie" + e);
553 String removeExtension = path.replace(".xml", "");
554 if (path.startsWith(FORWARD_SLASH)) {
555 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
557 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
561 PolicyController controller = getPolicyControllerInstance();
562 if (!params.toString().contains("activeVersion")) {
563 return controller.switchVersionPolicyContent(policyName);
565 String activeVersion = params.getString("activeVersion");
566 String highestVersion = params.get("highestVersion").toString();
567 if (Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)) {
568 return error("The Version shouldn't be greater than Highest Value");
570 activePolicy = policyName + "." + activeVersion + ".xml";
571 String[] splitDbCheckName = modifyPolicyName(activePolicy);
572 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
573 SimpleBindings policyParams = new SimpleBindings();
574 policyParams.put("splitDBCheckName_1", splitDbCheckName[1]);
575 policyParams.put("splitDBCheckName_0", splitDbCheckName[0]);
576 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
577 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
578 if (pentity.isDeleted()) {
579 return error("The Policy is Not Existing in Workspace");
581 if (policyName.contains(FORWARD_SLASH)) {
582 policyName = policyName.replace(FORWARD_SLASH, File.separator);
584 policyName = policyName.substring(policyName.indexOf(File.separator) + 1);
585 if (policyName.contains(BACKSLASH)) {
586 policyName = policyName.replace(File.separator, BACKSLASH);
588 policyName = splitDbCheckName[0].replace(".", File.separator) + File.separator + policyName;
589 final String watchPolicyName = policyName;
590 if (policyName.contains(FORWARD_SLASH)) {
591 policyName = policyName.replace(FORWARD_SLASH, File.separator);
593 if (policyName.contains(BACKSLASH)) {
594 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
596 String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + activeVersion + "' where policy_name ='" + policyName
598 // query the database
599 controller.executeQuery(query);
600 // Policy Notification
601 PolicyVersion entity = new PolicyVersion();
602 entity.setPolicyName(watchPolicyName);
603 entity.setActiveVersion(Integer.parseInt(activeVersion));
604 entity.setModifiedBy(userId);
605 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
610 private JSONObject describePolicy(JSONObject params) throws ServletException {
611 String path = params.getString("path");
613 if (path.startsWith(FORWARD_SLASH)) {
614 path = path.substring(1);
615 policyName = path.substring(path.lastIndexOf('/') + 1);
616 path = path.replace(FORWARD_SLASH, ".");
618 path = path.replace(FORWARD_SLASH, ".");
621 if (path.contains(CONFIG2)) {
622 path = path.replace(CONFIG, CONFIG1);
623 } else if (path.contains(ACTION2)) {
624 path = path.replace(ACTION, ACTION1);
625 } else if (path.contains(DECISION2)) {
626 path = path.replace(DECISION, DECISION1);
628 String[] split = path.split(":");
629 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
630 SimpleBindings peParams = new SimpleBindings();
631 peParams.put(SPLIT_1, split[1]);
632 peParams.put(SPLIT_0, split[0]);
633 List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
634 if (queryData.isEmpty()) {
635 return error("Error Occured while Describing the Policy - query is empty");
637 PolicyEntity entity = (PolicyEntity) queryData.get(0);
640 temp = File.createTempFile(policyName, ".tmp");
641 } catch (IOException e) {
642 String message = "Failed to create temp file " + policyName + ".tmp";
643 LOGGER.error(message + e);
644 return error(message);
646 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
647 bw.write(entity.getPolicyData());
648 } catch (IOException e) {
649 LOGGER.error("Exception Occured while Describing the Policy" + e);
651 JSONObject object = HumanPolicyComponent.DescribePolicy(temp);
653 Files.delete(temp.toPath());
654 } catch (IOException e) {
655 LOGGER.warn("Failed to delete " + temp.getName() + e);
660 // Get the List of Policies and Scopes for Showing in Editor tab
661 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
663 return processPolicyList(params, request);
664 } catch (Exception e) {
665 LOGGER.error("list", e);
666 return error(e.getMessage());
670 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
671 // Get the Login Id of the User from Request
672 String testUserID = getTestUserId();
673 String userId = testUserID != null ? testUserID : getUserSession(request).getOrgUserId();
674 List<Object> userRoles = getPolicyControllerInstance().getRoles(userId);
675 Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles);
676 List<String> roles = pair.second;
677 Set<String> scopes = pair.first;
678 Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
680 List<JSONObject> resultList = new ArrayList<>();
681 String path = params.getString("path");
682 if (path.contains("..xml")) {
683 path = path.replaceAll("..xml", "").trim();
686 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
688 && !(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST))) {
689 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
691 if (!FORWARD_SLASH.equals(path)) {
692 String tempScope = path.substring(1);
693 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
694 scopes.add(tempScope);
699 if (!FORWARD_SLASH.equals(path)) {
701 String scopeName = path.substring(path.indexOf('/') + 1);
702 activePolicyList(scopeName, resultList, roles, scopes, roleByScope);
703 } catch (Exception ex) {
704 LOGGER.error("Error Occurred While reading Policy Files List" + ex);
706 return new JSONObject().put(RESULT, resultList);
708 processRoles(scopes, roles, resultList, roleByScope);
709 return new JSONObject().put(RESULT, resultList);
712 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList,
713 Map<String, String> roleByScope) {
714 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
715 List<Object> scopesList = queryPolicyEditorScopes(null);
716 scopesList.stream().map(list -> (PolicyEditorScopes) list).filter(
717 scope -> !(scope.getScopeName().contains(File.separator)) && !scopes.contains(scope.getScopeName()))
719 JSONObject el = new JSONObject();
720 el.put(NAME, scope.getScopeName());
721 el.put(DATE, scope.getModifiedDate());
724 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
725 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
726 el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
730 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
731 scopes.stream().map(this::queryPolicyEditorScopes).filter(scopesList -> !scopesList.isEmpty())
732 .forEach(scopesList -> {
733 JSONObject el = new JSONObject();
734 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
735 el.put(NAME, scopeById.getScopeName());
736 el.put(DATE, scopeById.getModifiedDate());
739 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
740 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
741 if ((resultList).stream()
742 .noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
743 el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
750 private List<Object> queryPolicyEditorScopes(String scopeName) {
751 String scopeNameQuery;
752 SimpleBindings params = new SimpleBindings();
753 if (scopeName == null) {
754 scopeNameQuery = "from PolicyEditorScopes";
756 scopeNameQuery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
757 params.put(SCOPE_NAME, scopeName + "%");
759 PolicyController controller = getPolicyControllerInstance();
760 return getDataByQueryFromController(controller, scopeNameQuery, params);
763 // Get Active Policy List based on Scope Selection from Policy Version table
764 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
765 Set<String> scopes, Map<String, String> roleByScope) {
766 String scopeName = inScopeName;
767 if (scopeName.contains(FORWARD_SLASH)) {
768 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
770 if (scopeName.contains(BACKSLASH)) {
771 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
773 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
775 SimpleBindings params = new SimpleBindings();
776 params.put(SCOPE_NAME, scopeName + "%");
778 List<Object> activePolicies = getDataByQueryFromController(getPolicyControllerInstance(), query, params);
779 List<Object> scopesList = getDataByQueryFromController(getPolicyControllerInstance(),
780 FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
781 for (Object list : scopesList) {
782 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
784 for (Object list : activePolicies) {
785 PolicyVersion policy = (PolicyVersion) list;
786 String scopeNameValue =
787 policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
788 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
789 String scopeNameCheck =
790 scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator)
792 if (!scopeNameValue.equals(scopeNameCheck)) {
795 JSONObject el = new JSONObject();
796 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
797 el.put(DATE, policy.getModifiedDate());
798 el.put(VERSION, policy.getActiveVersion());
800 el.put(TYPE, "file");
801 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
802 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
803 String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ? roleByScope.get(ALLSCOPES)
804 : roleByScope.get(scopeNameValue);
805 el.put(ROLETYPE, roleType);
807 } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) {
808 JSONObject el = new JSONObject();
809 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
810 el.put(DATE, policy.getModifiedDate());
811 el.put(VERSION, policy.getActiveVersion());
813 el.put(TYPE, "file");
814 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
815 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
821 private List<Object> getDataByQueryFromController(final PolicyController controller, final String query,
822 final SimpleBindings params) {
823 final List<Object> activePolicies;
824 if (PolicyController.isjUnit()) {
825 activePolicies = controller.getDataByQuery(query, null);
827 activePolicies = controller.getDataByQuery(query, params);
829 return activePolicies;
832 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById,
833 Map<String, String> roleByScope) {
834 String scope = scopeById.getScopeName();
835 if (!scope.contains(File.separator)) {
838 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
839 if (scopeName.contains(ESCAPE_BACKSLASH)) {
840 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
842 if (scope.contains(File.separator)) {
843 scope = scope.substring(targetScope.length() + 1);
844 if (scope.contains(File.separator)) {
845 scope = scope.substring(0, scope.indexOf(File.separator));
848 if (scopeName.equalsIgnoreCase(targetScope)) {
849 JSONObject el = new JSONObject();
851 el.put(DATE, scopeById.getModifiedDate());
854 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
855 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
856 String roleType = roleByScope.get(ALLSCOPES); // Set default role type to ALL_SCOPES
857 if (!Strings.isNullOrEmpty(roleByScope.get(scopeName))) {
858 roleType = roleByScope.get(scopeName);
859 } else if (!Strings.isNullOrEmpty(roleByScope.get(scopeName + File.separator + scope))) {
860 roleType = roleByScope.get(scopeName + File.separator + scope);
862 el.put(ROLETYPE, roleType);
868 private String getUserName(String loginId) {
869 UserInfo userInfo = (UserInfo) getPolicyControllerInstance().getEntityItem(UserInfo.class, "userLoginId",
871 if (userInfo == null) {
874 return userInfo.getUserName();
878 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
880 return handlePolicyRename(params, request);
881 } catch (Exception e) {
882 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
883 return error(e.getMessage());
887 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
888 boolean isActive = false;
889 List<String> policyActiveInPdp = new ArrayList<>();
890 Set<String> scopeOfPolicyActiveInPdp = new HashSet<>();
891 String userId = getUserSession(request).getOrgUserId();
892 String oldPath = params.getString("path");
893 String newPath = params.getString("newPath");
894 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
895 newPath = newPath.substring(newPath.indexOf('/') + 1);
896 String checkValidation;
897 if (oldPath.endsWith(".xml")) {
898 checkValidation = newPath.replace(".xml", "");
900 checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
901 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1);
902 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
903 return error("Policy Rename Failed. The Name contains special characters.");
905 JSONObject result = policyRename(oldPath, newPath, userId);
906 if (!(Boolean) (result.getJSONObject(RESULT).get(SUCCESS))) {
910 String scopeName = oldPath;
911 String newScopeName = newPath;
912 if (scopeName.contains(FORWARD_SLASH)) {
913 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
914 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
916 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator) + 1);
917 if (scopeName.contains(BACKSLASH)) {
918 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
919 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
921 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
922 return error("Scope Rename Failed. The Name contains special characters.");
924 PolicyController controller = getPolicyControllerInstance();
925 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
926 SimpleBindings pvParams = new SimpleBindings();
927 pvParams.put(SCOPE_NAME, scopeName + "%");
928 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
929 List<Object> scopesList =
930 controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
931 for (Object object : activePolicies) {
932 PolicyVersion activeVersion = (PolicyVersion) object;
933 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "."
934 + activeVersion.getActiveVersion() + ".xml";
935 String policyNewPath = policyOldPath.replace(oldPath, newPath);
936 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
937 if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
939 policyActiveInPdp.add(policyOldPath);
940 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
941 scopeOfPolicyActiveInPdp.add(scope.replace(FORWARD_SLASH, File.separator));
944 boolean rename = activePolicies.size() != policyActiveInPdp.size();
945 if (policyActiveInPdp.isEmpty()) {
946 renameScope(scopesList, scopeName, newScopeName, controller);
948 renameScope(scopesList, scopeName, newScopeName, controller);
949 UserInfo userInfo = new UserInfo();
950 userInfo.setUserLoginId(userId);
951 scopeOfPolicyActiveInPdp.forEach(scope -> {
952 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
953 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
954 editorScopeEntity.setUserCreatedBy(userInfo);
955 editorScopeEntity.setUserModifiedBy(userInfo);
956 controller.saveData(editorScopeEntity);
960 return error("The Following policies rename failed. Since they are active in PDP Groups"
961 + policyActiveInPdp);
967 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName,
968 PolicyController controller) {
969 for (Object object : scopesList) {
970 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
971 String scopeName = inScopeName;
972 if (scopeName.contains(BACKSLASH_8TIMES)) {
973 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
974 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
976 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
977 editorScopeEntity.setScopeName(scope);
978 controller.updateData(editorScopeEntity);
982 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
985 PolicyController controller = getPolicyControllerInstance();
987 String policyVersionName = newPath.replace(".xml", "");
988 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
989 .replace(FORWARD_SLASH, File.separator);
991 String oldpolicyVersionName = oldPath.replace(".xml", "");
992 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.'))
993 .replace(FORWARD_SLASH, File.separator);
994 String newpolicyName = newPath.replace("/", ".");
995 String[] newPolicySplit = modifyPolicyName(newPath);
997 final String[] oldPolicySplit = modifyPolicyName(oldPath);
999 // Check PolicyEntity table with newPolicy Name
1000 String policyEntityquery =
1001 "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1002 SimpleBindings policyParams = new SimpleBindings();
1003 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1004 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1005 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1006 if (!queryData.isEmpty()) {
1007 return error("Policy rename failed. Since, the policy with same name already exists.");
1010 // Query the Policy Entity with oldPolicy Name
1011 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
1012 String oldPolicyEntityQuery =
1013 "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + ":oldPolicySplit_0";
1014 SimpleBindings params = new SimpleBindings();
1015 params.put("policyEntityCheck", policyEntityCheck + "%");
1016 params.put("oldPolicySplit_0", oldPolicySplit[0]);
1017 List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params);
1018 if (oldEntityData.isEmpty()) {
1020 "Policy rename failed due to policy not able to retrieve from database. Contact super-admin.");
1023 StringBuilder groupQuery = new StringBuilder();
1024 groupQuery.append("FROM PolicyGroupEntity where (");
1025 SimpleBindings geParams = new SimpleBindings();
1026 for (int i = 0; i < oldEntityData.size(); i++) {
1027 entity = (PolicyEntity) oldEntityData.get(i);
1029 groupQuery.append("policyid = :policyId");
1030 geParams.put("policyId", entity.getPolicyId());
1032 groupQuery.append(" or policyid = :policyId").append(i);
1033 geParams.put("policyId" + i, entity.getPolicyId());
1036 groupQuery.append(")");
1037 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
1038 if (!groupEntityData.isEmpty()) {
1039 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
1041 for (Object anOldEntityData : oldEntityData) {
1042 entity = (PolicyEntity) anOldEntityData;
1043 String checkEntityName = entity.getPolicyName().replace(".xml", "");
1044 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
1045 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
1046 if (checkEntityName.equals(originalPolicyName)) {
1047 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0],
1048 oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
1052 } catch (Exception e) {
1053 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
1054 return error(e.getMessage());
1058 private String[] modifyPolicyName(String pathName) {
1059 return modifyPolicyName(FORWARD_SLASH, pathName);
1062 private String[] modifyPolicyName(String separator, String pathName) {
1063 String policyName = pathName.replace(separator, ".");
1064 if (policyName.contains(CONFIG2)) {
1065 policyName = policyName.replace(CONFIG, CONFIG1);
1066 } else if (policyName.contains(ACTION2)) {
1067 policyName = policyName.replace(ACTION, ACTION1);
1068 } else if (policyName.contains(DECISION2)) {
1069 policyName = policyName.replace(DECISION, DECISION1);
1071 return policyName.split(":");
1074 private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removeNewPolicyExtension,
1075 String oldScope, String removeOldPolicyExtension, String policyName, String newPolicyName,
1076 String oldPolicyName, String userId) {
1078 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1079 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1080 PolicyController controller = getPolicyControllerInstance();
1082 String oldPolicyNameWithoutExtension = removeOldPolicyExtension;
1083 String newPolicyNameWithoutExtension = removeNewPolicyExtension;
1084 if (removeOldPolicyExtension.endsWith(".xml")) {
1085 oldPolicyNameWithoutExtension =
1086 oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
1087 newPolicyNameWithoutExtension =
1088 newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
1090 entity.setPolicyName(
1091 entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1092 entity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1093 newScope + "." + newPolicyNameWithoutExtension));
1094 entity.setScope(newScope);
1095 entity.setModifiedBy(userId);
1097 String oldConfigurationName = null;
1098 String newConfigurationName = null;
1099 if (newPolicyName.contains(CONFIG2)) {
1100 oldConfigurationName = configEntity.getConfigurationName();
1101 configEntity.setConfigurationName(
1102 configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1103 newScope + "." + newPolicyNameWithoutExtension));
1104 controller.updateData(configEntity);
1105 newConfigurationName = configEntity.getConfigurationName();
1106 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1107 if (file.exists()) {
1109 new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1110 file.renameTo(renameFile);
1112 } else if (newPolicyName.contains(ACTION2)) {
1113 oldConfigurationName = actionEntity.getActionBodyName();
1114 actionEntity.setActionBody(
1115 actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1116 newScope + "." + newPolicyNameWithoutExtension));
1117 controller.updateData(actionEntity);
1118 newConfigurationName = actionEntity.getActionBodyName();
1119 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1120 if (file.exists()) {
1122 new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1123 file.renameTo(renameFile);
1126 controller.updateData(entity);
1128 PolicyRestController restController = new PolicyRestController();
1129 restController.notifyOtherPapsToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1130 PolicyVersion versionEntity =
1131 (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName);
1132 versionEntity.setPolicyName(policyName);
1133 versionEntity.setModifiedBy(userId);
1134 controller.updateData(versionEntity);
1135 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1);
1136 String moveOldPolicyCheck = oldPolicyName.substring(oldPolicyName.lastIndexOf(File.separator) + 1);
1137 if (movePolicyCheck.equals(moveOldPolicyCheck)) {
1138 controller.watchPolicyFunction(versionEntity, oldPolicyName, "Move");
1140 controller.watchPolicyFunction(versionEntity, oldPolicyName, "Rename");
1142 } catch (Exception e) {
1143 LOGGER.error(EXCEPTION_OCCURED + e);
1148 private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
1149 String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException {
1150 String queryEntityName;
1151 PolicyController controller = getPolicyControllerInstance();
1152 PolicyEntity cloneEntity = new PolicyEntity();
1153 cloneEntity.setPolicyName(newpolicyName);
1154 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1155 String removenewPolicyExtension = inRemovenewPolicyExtension;
1156 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1157 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1158 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + removeoldPolicyExtension,
1159 newScope + "." + removenewPolicyExtension));
1160 cloneEntity.setScope(entity.getScope());
1161 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1162 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1163 String newConfigurationName = null;
1164 if (newpolicyName.contains(CONFIG2)) {
1165 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1166 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName()
1167 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1168 queryEntityName = configurationDataEntity.getConfigurationName();
1169 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1170 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1171 configurationDataEntity.setDeleted(false);
1172 configurationDataEntity.setCreatedBy(userId);
1173 configurationDataEntity.setModifiedBy(userId);
1174 controller.saveData(configurationDataEntity);
1175 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller
1176 .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1177 cloneEntity.setConfigurationData(configEntiy);
1178 newConfigurationName = configEntiy.getConfigurationName();
1179 try (FileWriter fw =
1180 new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1181 BufferedWriter bw = new BufferedWriter(fw)) {
1182 bw.write(configEntiy.getConfigBody());
1183 } catch (IOException e) {
1184 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1187 } else if (newpolicyName.contains(ACTION2)) {
1188 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1189 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName()
1190 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1191 queryEntityName = actionBodyEntity.getActionBodyName();
1192 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1193 actionBodyEntity.setDeleted(false);
1194 actionBodyEntity.setCreatedBy(userId);
1195 actionBodyEntity.setModifiedBy(userId);
1196 controller.saveData(actionBodyEntity);
1197 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class,
1198 "actionBodyName", queryEntityName);
1199 cloneEntity.setActionBodyEntity(actionEntiy);
1200 newConfigurationName = actionEntiy.getActionBodyName();
1201 try (FileWriter fw =
1202 new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1203 BufferedWriter bw = new BufferedWriter(fw)) {
1204 bw.write(actionEntiy.getActionBody());
1205 } catch (IOException e) {
1206 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1211 cloneEntity.setDeleted(entity.isDeleted());
1212 cloneEntity.setCreatedBy(userId);
1213 cloneEntity.setModifiedBy(userId);
1214 controller.saveData(cloneEntity);
1216 // Notify others paps regarding clone policy.
1217 PolicyRestController restController = new PolicyRestController();
1218 restController.notifyOtherPapsToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1222 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1224 String userId = getUserSession(request).getOrgUserId();
1225 String oldPath = params.getString("path");
1226 String newPath = params.getString("newPath");
1227 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
1228 newPath = newPath.substring(newPath.indexOf('/') + 1);
1230 String policyVersionName = newPath.replace(".xml", "");
1231 String version = policyVersionName.substring(policyVersionName.indexOf('.') + 1);
1232 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
1233 .replace(FORWARD_SLASH, File.separator);
1235 String newPolicyName = newPath.replace(FORWARD_SLASH, ".");
1237 String newPolicyCheck = newPolicyName;
1238 if (newPolicyCheck.contains(CONFIG2)) {
1239 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1240 } else if (newPolicyCheck.contains(ACTION2)) {
1241 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1242 } else if (newPolicyCheck.contains(DECISION2)) {
1243 newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
1245 if (!newPolicyCheck.contains(":")) {
1246 return error("Policy Clone Failed. The Name contains special characters.");
1248 String[] newPolicySplit = newPolicyCheck.split(":");
1250 String checkValidation = newPolicySplit[1].replace(".xml", "");
1252 checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
1253 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
1254 return error("Policy Clone Failed. The Name contains special characters.");
1257 String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
1259 final String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
1261 PolicyController controller = getPolicyControllerInstance();
1263 PolicyEntity entity = null;
1264 boolean success = false;
1266 // Check PolicyEntity table with newPolicy Name
1267 String policyEntityquery =
1268 "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1269 SimpleBindings policyParams = new SimpleBindings();
1270 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1271 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1272 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1273 if (!queryData.isEmpty()) {
1274 return error("Policy already exists with same name");
1277 // Query the Policy Entity with oldPolicy Name
1278 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1279 SimpleBindings peParams = new SimpleBindings();
1280 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1281 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1282 queryData = getDataByQueryFromController(controller, policyEntityquery, peParams);
1283 if (!queryData.isEmpty()) {
1284 entity = (PolicyEntity) queryData.get(0);
1286 if (entity != null) {
1287 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0],
1288 newPolicySplit[1], entity, userId);
1292 PolicyVersion entityItem = new PolicyVersion();
1293 entityItem.setActiveVersion(Integer.parseInt(version));
1294 entityItem.setHigherVersion(Integer.parseInt(version));
1295 entityItem.setPolicyName(policyName);
1296 entityItem.setCreatedBy(userId);
1297 entityItem.setModifiedBy(userId);
1298 entityItem.setModifiedDate(new Date());
1299 controller.saveData(entityItem);
1301 LOGGER.debug("copy from: {} to: {}" + oldPath + newPath);
1303 } catch (Exception e) {
1304 LOGGER.error("copy", e);
1305 return error(e.getMessage());
1309 // Delete Policy or Scope Functionality
1310 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1311 PolicyController controller = getPolicyControllerInstance();
1312 PolicyRestController restController = new PolicyRestController();
1313 PolicyEntity policyEntity = null;
1314 String policyNamewithoutExtension;
1316 String userId = getUserSession(request).getOrgUserId();
1317 String deleteVersion = "";
1318 String path = params.getString("path");
1319 LOGGER.debug("delete {}" + path);
1320 if (params.has("deleteVersion")) {
1321 deleteVersion = params.getString("deleteVersion");
1323 path = path.substring(path.indexOf('/') + 1);
1324 String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
1325 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1327 SimpleBindings policyParams = new SimpleBindings();
1328 if (path.endsWith(".xml")) {
1329 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1330 String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
1331 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1332 policyParams.put(SPLIT_1, split[1] + "%");
1333 policyParams.put(SPLIT_0, split[0]);
1335 policyNamewithoutExtension = path.replace(File.separator, ".");
1336 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension or scope = :exactScope";
1337 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + ".%");
1338 policyParams.put("exactScope", policyNamewithoutExtension);
1341 List<Object> policyEntityObjects = controller.getDataByQuery(query, policyParams);
1342 String activePolicyName = null;
1343 boolean pdpCheck = false;
1344 if (path.endsWith(".xml")) {
1345 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1346 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1));
1347 if ("ALL".equals(deleteVersion)) {
1348 if (!policyEntityObjects.isEmpty()) {
1349 for (Object object : policyEntityObjects) {
1350 policyEntity = (PolicyEntity) object;
1351 String groupEntityquery =
1352 "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'";
1353 SimpleBindings pgeParams = new SimpleBindings();
1354 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1355 if (!groupobject.isEmpty()) {
1357 activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1359 deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
1360 policyNamewithoutExtension);
1364 // Policy Notification
1365 PolicyVersion versionEntity = new PolicyVersion();
1366 versionEntity.setPolicyName(policyNamewithoutExtension);
1367 versionEntity.setModifiedBy(userId);
1368 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1370 // Delete from policyVersion table
1371 String getActivePdpPolicyVersion = activePolicyName.replace(".xml", "");
1372 getActivePdpPolicyVersion =
1373 getActivePdpPolicyVersion.substring(getActivePdpPolicyVersion.lastIndexOf('.') + 1);
1374 String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePdpPolicyVersion
1375 + "' , highest_version='" + getActivePdpPolicyVersion + "' where policy_name ='"
1376 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1377 controller.executeQuery(policyVersionQuery);
1379 "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
1380 + activePolicyName);
1382 // No Active Policy in PDP. So, deleting all entries from policyVersion table
1383 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1384 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1385 controller.executeQuery(policyVersionQuery);
1387 } else if ("CURRENT".equals(deleteVersion)) {
1388 String currentVersionPolicyName =
1389 policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator) + 1);
1390 String currentVersionScope =
1391 policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator))
1392 .replace(File.separator, ".");
1393 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and "
1394 + "scope = :currentVersionScope";
1396 SimpleBindings peParams = new SimpleBindings();
1397 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1398 peParams.put("currentVersionScope", currentVersionScope);
1400 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1401 if (!policyEntitys.isEmpty()) {
1402 policyEntity = (PolicyEntity) policyEntitys.get(0);
1404 if (policyEntity == null) {
1408 String groupEntityquery =
1409 "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1410 SimpleBindings geParams = new SimpleBindings();
1411 geParams.put("policyEntityId", policyEntity.getPolicyId());
1412 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1413 if (!groupobject.isEmpty()) {
1414 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"
1415 + policyEntity.getScope() + "." + policyEntity.getPolicyName() + "'");
1418 // Delete the entity from Elastic Search Database
1419 deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
1420 policyNamewithoutExtension);
1423 int highestVersion = 0;
1424 if (!policyEntityObjects.isEmpty()) {
1425 for (Object object : policyEntityObjects) {
1426 policyEntity = (PolicyEntity) object;
1427 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1428 int policyEntityVersion = Integer
1429 .parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.') + 1));
1430 if (policyEntityVersion > highestVersion && policyEntityVersion != version) {
1431 highestVersion = policyEntityVersion;
1436 // Policy Notification
1437 PolicyVersion entity = new PolicyVersion();
1438 entity.setPolicyName(policyNamewithoutExtension);
1439 entity.setActiveVersion(highestVersion);
1440 entity.setModifiedBy(userId);
1441 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1444 if (highestVersion != 0) {
1445 updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + highestVersion
1446 + "' , highest_version='" + highestVersion + "' where policy_name ='"
1447 + policyNamewithoutExtension.replace("\\", "\\\\") + "'";
1449 updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1450 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1452 controller.executeQuery(updatequery);
1454 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1455 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1456 controller.executeQuery(policyVersionQuery);
1460 List<String> activePoliciesInPdp = new ArrayList<>();
1461 if (policyEntityObjects.isEmpty()) {
1462 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1463 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1464 controller.executeQuery(policyScopeQuery);
1467 for (Object object : policyEntityObjects) {
1468 policyEntity = (PolicyEntity) object;
1469 String groupEntityQuery = "from PolicyGroupEntity where policyid = :policyEntityId";
1470 SimpleBindings geParams = new SimpleBindings();
1471 geParams.put("policyEntityId", policyEntity.getPolicyId());
1472 List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams);
1473 if (!groupobject.isEmpty()) {
1475 activePoliciesInPdp.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
1477 // Delete the entity from Elastic Search Database
1478 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1479 restController.deleteElasticData(searchFileName);
1480 // Delete the entity from Policy Entity table
1481 controller.deleteData(policyEntity);
1482 policyNamewithoutExtension = policyEntity.getPolicyName();
1483 if (policyNamewithoutExtension.contains(CONFIG2)) {
1484 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1485 + policyEntity.getConfigurationData().getConfigurationName()));
1486 controller.deleteData(policyEntity.getConfigurationData());
1487 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1488 policyEntity.getConfigurationData().getConfigurationName());
1489 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1490 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1491 + policyEntity.getActionBodyEntity().getActionBodyName()));
1492 controller.deleteData(policyEntity.getActionBodyEntity());
1493 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1494 policyEntity.getActionBodyEntity().getActionBodyName());
1498 // Delete from policyVersion and policyEditor Scope table
1499 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"
1500 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + File.separator + PERCENT_AND_ID_GT_0;
1501 controller.executeQuery(policyVersionQuery);
1503 // Policy Notification
1504 PolicyVersion entity = new PolicyVersion();
1505 entity.setPolicyName(path);
1506 entity.setModifiedBy(userId);
1507 controller.watchPolicyFunction(entity, path, "DeleteScope");
1509 // Add Active Policies List to PolicyVersionTable
1510 for (String anActivePoliciesInPdp : activePoliciesInPdp) {
1511 String activePdpPolicyName = anActivePoliciesInPdp.replace(".xml", "");
1512 int activePdpPolicyVersion = Integer
1513 .parseInt(activePdpPolicyName.substring(activePdpPolicyName.lastIndexOf('.') + 1));
1514 activePdpPolicyName = activePdpPolicyName.substring(0, activePdpPolicyName.lastIndexOf('.'))
1515 .replace(".", File.separator);
1516 PolicyVersion insertActivePdpVersion = new PolicyVersion();
1517 insertActivePdpVersion.setPolicyName(activePdpPolicyName);
1518 insertActivePdpVersion.setHigherVersion(activePdpPolicyVersion);
1519 insertActivePdpVersion.setActiveVersion(activePdpPolicyVersion);
1520 insertActivePdpVersion.setCreatedBy(userId);
1521 insertActivePdpVersion.setModifiedBy(userId);
1522 controller.saveData(insertActivePdpVersion);
1524 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"
1525 + activePoliciesInPdp);
1527 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1528 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1529 controller.executeQuery(policyScopeQuery);
1534 } catch (Exception e) {
1535 LOGGER.error(DELETE, e);
1536 return error(e.getMessage());
1540 private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller,
1541 final PolicyRestController restController, final PolicyEntity policyEntity,
1542 final String policyNamewithoutExtension) throws IOException {
1543 // Delete the entity from Elastic Search Database
1544 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1545 restController.deleteElasticData(searchFileName);
1546 // Delete the entity from Policy Entity table
1547 controller.deleteData(policyEntity);
1548 if (policyNamewithoutExtension.contains(CONFIG2)) {
1549 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1550 + policyEntity.getConfigurationData().getConfigurationName()));
1551 controller.deleteData(policyEntity.getConfigurationData());
1552 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1553 policyEntity.getConfigurationData().getConfigurationName());
1554 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1555 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1556 + policyEntity.getActionBodyEntity().getActionBodyName()));
1557 controller.deleteData(policyEntity.getActionBodyEntity());
1558 restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
1559 policyEntity.getActionBodyEntity().getActionBodyName());
1564 private JSONObject editFile(JSONObject params) throws ServletException {
1567 final String mode = params.getString("mode");
1568 String path = params.getString("path");
1569 LOGGER.debug("editFile path: {}" + path);
1571 String domain = path.substring(1, path.lastIndexOf('/'));
1572 domain = domain.replace(FORWARD_SLASH, ".");
1574 path = path.substring(1);
1575 path = path.replace(FORWARD_SLASH, ".");
1577 String[] split = modifyPolicyName(path);
1579 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1580 SimpleBindings peParams = new SimpleBindings();
1581 peParams.put(SPLIT_1, split[1]);
1582 peParams.put(SPLIT_0, split[0]);
1583 List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
1584 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1585 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1587 Object policy = XACMLPolicyScanner.readPolicy(stream);
1588 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1589 policyAdapter.setData(policy);
1591 if ("viewPolicy".equalsIgnoreCase(mode)) {
1592 policyAdapter.setReadOnly(true);
1593 policyAdapter.setEditPolicy(false);
1595 policyAdapter.setReadOnly(false);
1596 policyAdapter.setEditPolicy(true);
1599 policyAdapter.setDomainDir(domain);
1600 policyAdapter.setPolicyData(policy);
1601 String policyName = path.replace(".xml", "");
1602 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1603 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1));
1605 PolicyAdapter setPolicyAdapter = PolicyAdapter.getInstance();
1606 Objects.requireNonNull(setPolicyAdapter).configure(policyAdapter, entity);
1608 policyAdapter.setParentPath(null);
1609 ObjectMapper mapper = new ObjectMapper();
1610 String json = mapper.writeValueAsString(policyAdapter);
1611 JsonNode jsonNode = mapper.readTree(json);
1613 return new JSONObject().put(RESULT, jsonNode);
1614 } catch (Exception e) {
1615 LOGGER.error("editFile", e);
1616 return error(e.getMessage());
1621 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1623 String name = getNameFromParams(params);
1624 String validateName =
1625 name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
1626 if (!name.isEmpty()) {
1627 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1628 if (!validate.contains(SUCCESS)) {
1629 return error(validate);
1631 LOGGER.debug("addFolder path: {} name: {}" + params.getString("path") + name);
1632 if (name.startsWith(File.separator)) {
1633 name = name.substring(1);
1635 PolicyEditorScopes entity =
1636 (PolicyEditorScopes) getPolicyControllerInstance().getEntityItem(
1637 PolicyEditorScopes.class, SCOPE_NAME, name);
1638 if (entity != null) {
1639 return error("Scope Already Exists");
1641 String userId = getUserSession(request).getOrgUserId();
1642 UserInfo userInfo = new UserInfo();
1643 userInfo.setUserLoginId(userId);
1644 PolicyEditorScopes newScope = new PolicyEditorScopes();
1645 newScope.setScopeName(name);
1646 newScope.setUserCreatedBy(userInfo);
1647 newScope.setUserModifiedBy(userInfo);
1648 getPolicyControllerInstance().saveData(newScope);
1651 } catch (Exception e) {
1652 LOGGER.error("addFolder", e);
1653 return error(e.getMessage());
1657 private String getNameFromParams(final JSONObject params) {
1660 if (params.has(SUB_SCOPENAME)) {
1661 if (!"".equals(params.getString(SUB_SCOPENAME))) {
1662 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator
1663 + params.getString(SUB_SCOPENAME);
1666 name = params.getString(NAME);
1668 } catch (Exception e) {
1669 name = params.getString(NAME);
1670 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occurred While Adding Scope" + e);
1675 // Return Error Object
1676 private JSONObject error(String msg) throws ServletException {
1678 JSONObject result = new JSONObject();
1679 result.put(SUCCESS, false);
1680 result.put("error", msg);
1681 return new JSONObject().put(RESULT, result);
1682 } catch (JSONException e) {
1683 throw new ServletException(e);
1687 // Return Success Object
1688 private JSONObject success() throws ServletException {
1690 JSONObject result = new JSONObject();
1691 result.put(SUCCESS, true);
1692 result.put("error", (Object) null);
1693 return new JSONObject().put(RESULT, result);
1694 } catch (JSONException e) {
1695 throw new ServletException(e);
1699 private PolicyController getPolicyControllerInstance() {
1700 return policyController != null ? getPolicyController() : new PolicyController();
1703 private String getTestUserId() {
1707 public static void setTestUserId(String testUserId) {
1708 PolicyManagerServlet.testUserId = testUserId;