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;
153 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
156 private static PolicyController policyController;
158 private synchronized PolicyController getPolicyController() {
159 return policyController;
162 public static synchronized void setPolicyController(PolicyController policyController) {
163 PolicyManagerServlet.policyController = policyController;
166 public static JsonArray getPolicyNames() {
170 public static void setPolicyNames(JsonArray policyNames) {
171 PolicyManagerServlet.policyNames = policyNames;
174 public static List<String> getServiceTypeNamesList() {
175 return serviceTypeNamesList;
179 public void init(ServletConfig servletConfig) throws ServletException {
180 super.init(servletConfig);
182 // Common initialization
184 XACMLRest.xacmlInit(servletConfig);
185 // init aes key from prop or env
186 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
188 // Initialize ClosedLoop JSON
190 PolicyManagerServlet.initializeJSONLoad();
193 private static void initializeJSONLoad() {
194 Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
195 String location = closedLoopJsonLocation.toString();
196 if (!location.endsWith("json")) {
197 LOGGER.warn("JSONConfig file does not end with extension .json");
200 try (FileInputStream inputStream = new FileInputStream(location);
201 JsonReader jsonReader = Json.createReader(inputStream)) {
202 policyNames = jsonReader.readArray();
203 serviceTypeNamesList = new ArrayList<>();
204 for (int i = 0; i < policyNames.size(); i++) {
205 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
206 String name = policyName.getJsonString("serviceTypePolicyName").getString();
207 serviceTypeNamesList.add(name);
209 } catch (IOException e) {
210 LOGGER.error("Exception Occured while initializing the JSONConfig file" + e);
215 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
216 LOGGER.debug("doPost");
218 // if request contains multipart-form-data
219 if (ServletFileUpload.isMultipartContent(request)) {
220 uploadFile(request, response);
222 // all other post request has json params in body
224 fileOperation(request, response);
226 } catch (Exception e) {
228 setError(e, response);
229 } catch (Exception e1) {
230 LOGGER.error(EXCEPTION_OCCURED + e1);
235 // Set Error Message for Exception
236 private void setError(Exception t, HttpServletResponse response) throws IOException {
238 JSONObject responseJsonObject = error(t.getMessage());
239 response.setContentType(CONTENTTYPE);
240 PrintWriter out = response.getWriter();
241 out.print(responseJsonObject);
243 } catch (Exception x) {
244 LOGGER.error(EXCEPTION_OCCURED + x);
245 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
249 // Policy Import Functionality
250 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
252 Map<String, InputStream> files = new HashMap<>();
254 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
255 for (FileItem item : items) {
256 if (!item.isFormField()) {
257 // Process form file field (input type="file").
258 files.put(item.getName(), item.getInputStream());
259 processFormFile(request, item);
263 JSONObject responseJsonObject;
264 responseJsonObject = this.success();
265 response.setContentType(CONTENTTYPE);
266 PrintWriter out = response.getWriter();
267 out.print(responseJsonObject);
269 } catch (Exception e) {
270 LOGGER.debug("Cannot write file");
271 throw new ServletException("Cannot write file", e);
275 private void processFormFile(HttpServletRequest request, FileItem item) {
277 if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) {
278 File file = new File(item.getName());
279 try (OutputStream outputStream = new FileOutputStream(file)) {
280 IOUtils.copy(item.getInputStream(), outputStream);
281 newFile = file.toString();
282 PolicyExportAndImportController importController = new PolicyExportAndImportController();
283 importController.importRepositoryFile(newFile, request);
284 } catch (Exception e) {
285 LOGGER.error("Upload error : " + e);
287 } else if (!item.getName().endsWith(".xls")) {
288 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
289 } else { // uploaded file size is greater than allowed
290 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
294 // File Operation Functionality
295 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
296 JSONObject responseJsonObject;
297 StringBuilder sb = new StringBuilder();
298 try (BufferedReader br = request.getReader()) {
300 while ((str = br.readLine()) != null) {
303 } catch (Exception e) {
304 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
305 responseJsonObject = error(e.getMessage());
306 setResponse(response, responseJsonObject);
310 JSONObject jObj = new JSONObject(sb.toString());
311 JSONObject params = jObj.getJSONObject("params");
312 Mode mode = Mode.valueOf(params.getString("mode"));
314 String userId = UserUtils.getUserSession(request).getOrgUserId();
316 "****************************************Logging UserID while doing actions on Editor tab*******************************************");
318 "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString());
320 "***********************************************************************************************************************************");
321 responseJsonObject = operateBasedOnMode(mode, params, request);
322 } catch (Exception e) {
323 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
324 responseJsonObject = error(e.getMessage());
326 setResponse(response, responseJsonObject);
329 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
330 response.setContentType(CONTENTTYPE);
331 try (PrintWriter out = response.getWriter()) {
332 out.print(responseJsonObject);
334 } catch (IOException e) {
335 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
339 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request)
340 throws ServletException {
341 JSONObject responseJsonObject;
345 responseJsonObject = addFolder(params, request);
348 responseJsonObject = copy(params, request);
351 responseJsonObject = delete(params, request);
355 responseJsonObject = editFile(params);
358 responseJsonObject = list(params, request);
361 responseJsonObject = rename(params, request);
363 case DESCRIBEPOLICYFILE:
364 responseJsonObject = describePolicy(params);
367 responseJsonObject = switchVersion(params, request);
370 responseJsonObject = searchPolicyList(params, request);
373 throw new ServletException("not implemented");
375 if (responseJsonObject == null) {
376 responseJsonObject = error("generic error : responseJsonObject is null");
378 return responseJsonObject;
381 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
382 List<Object> policyData = new ArrayList<>();
383 JSONArray policyList = null;
384 if (params.has("policyList")) {
385 policyList = (JSONArray) params.get("policyList");
387 PolicyController controller = getPolicyControllerInstance();
388 List<JSONObject> resultList = new ArrayList<>();
390 if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
391 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
393 } catch (Exception e) {
395 "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e);
398 return new JSONObject().put(RESULT, resultList);
401 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
402 PolicyController controller, List<JSONObject> resultList) {
404 Set<String> scopes;// Get the Login Id of the User from Request
405 String userId = UserUtils.getUserSession(request).getOrgUserId();
406 List<Object> userRoles = controller.getRoles(userId);
407 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
410 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
411 if (scopes.isEmpty()) {
414 for (String scope : scopes) {
415 addScope(scopes, scope);
418 if (policyList != null) {
419 for (int i = 0; i < policyList.length(); i++) {
420 String policyName = policyList.get(i).toString().replace(".xml", "");
421 String version = policyName.substring(policyName.lastIndexOf('.') + 1);
422 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
423 parsePolicyList(resultList, controller, policyName, version);
426 getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
431 private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller,
432 List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
433 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
434 policyData = controller.getData(PolicyVersion.class);
436 List<Object> filterData = controller.getData(PolicyVersion.class);
437 for (Object filter : filterData) {
438 addFilterData(policyData, scopes, (PolicyVersion) filter);
442 if (!policyData.isEmpty()) {
443 updateResultList(policyData, resultList);
447 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
449 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
450 if (scopes.contains(scopeName)) {
451 policyData.add(filter);
453 } catch (Exception e) {
454 LOGGER.error("Exception occured while filtering policyversion data" + e);
458 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
459 for (Object aPolicyData : policyData) {
460 PolicyVersion policy = (PolicyVersion) aPolicyData;
461 JSONObject el = new JSONObject();
462 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
463 el.put(DATE, policy.getModifiedDate());
464 el.put(VERSION, policy.getActiveVersion());
466 el.put(TYPE, "file");
467 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
468 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
473 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName,
475 if (policyName.contains(BACKSLASH)) {
476 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
478 String policyVersionQuery =
479 "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
480 SimpleBindings pvParams = new SimpleBindings();
481 pvParams.put("policyName", policyName);
482 pvParams.put(VERSION, version);
483 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
484 if (!activeData.isEmpty()) {
485 PolicyVersion policy = (PolicyVersion) activeData.get(0);
486 JSONObject el = new JSONObject();
487 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
488 el.put(DATE, policy.getModifiedDate());
489 el.put(VERSION, policy.getActiveVersion());
491 el.put(TYPE, "file");
492 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
493 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
498 private void addScope(Set<String> scopes, String scope) {
499 List<Object> scopesList = queryPolicyEditorScopes(scope);
500 if (!scopesList.isEmpty()) {
501 for (Object aScopesList : scopesList) {
502 PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
503 scopes.add(tempScope.getScopeName());
508 // Switch Version Functionality
509 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException {
510 String path = params.getString("path");
511 String userId = null;
513 userId = UserUtils.getUserSession(request).getOrgUserId();
514 } catch (Exception e) {
515 LOGGER.error("Exception Occured while reading userid from cookie" + e);
518 String removeExtension = path.replace(".xml", "");
519 if (path.startsWith(FORWARD_SLASH)) {
520 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
522 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
526 PolicyController controller = getPolicyControllerInstance();
527 if (!params.toString().contains("activeVersion")) {
528 return controller.switchVersionPolicyContent(policyName);
530 String activeVersion = params.getString("activeVersion");
531 String highestVersion = params.get("highestVersion").toString();
532 if (Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)) {
533 return error("The Version shouldn't be greater than Highest Value");
535 activePolicy = policyName + "." + activeVersion + ".xml";
536 String[] splitDBCheckName = modifyPolicyName(activePolicy);
537 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
538 SimpleBindings policyParams = new SimpleBindings();
539 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
540 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
541 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
542 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
543 if (pentity.isDeleted()) {
544 return error("The Policy is Not Existing in Workspace");
546 if (policyName.contains(FORWARD_SLASH)) {
547 policyName = policyName.replace(FORWARD_SLASH, File.separator);
549 policyName = policyName.substring(policyName.indexOf(File.separator) + 1);
550 if (policyName.contains(BACKSLASH)) {
551 policyName = policyName.replace(File.separator, BACKSLASH);
553 policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName;
554 String watchPolicyName = policyName;
555 if (policyName.contains(FORWARD_SLASH)) {
556 policyName = policyName.replace(FORWARD_SLASH, File.separator);
558 if (policyName.contains(BACKSLASH)) {
559 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
561 String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + activeVersion + "' where policy_name ='" + policyName
563 // query the database
564 controller.executeQuery(query);
565 // Policy Notification
566 PolicyVersion entity = new PolicyVersion();
567 entity.setPolicyName(watchPolicyName);
568 entity.setActiveVersion(Integer.parseInt(activeVersion));
569 entity.setModifiedBy(userId);
570 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
575 private JSONObject describePolicy(JSONObject params) throws ServletException {
577 String path = params.getString("path");
579 if (path.startsWith(FORWARD_SLASH)) {
580 path = path.substring(1);
581 policyName = path.substring(path.lastIndexOf('/') + 1);
582 path = path.replace(FORWARD_SLASH, ".");
584 path = path.replace(FORWARD_SLASH, ".");
587 if (path.contains(CONFIG2)) {
588 path = path.replace(CONFIG, CONFIG1);
589 } else if (path.contains(ACTION2)) {
590 path = path.replace(ACTION, ACTION1);
591 } else if (path.contains(DECISION2)) {
592 path = path.replace(DECISION, DECISION1);
594 PolicyController controller = getPolicyControllerInstance();
595 String[] split = path.split(":");
596 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
597 SimpleBindings peParams = new SimpleBindings();
598 peParams.put(SPLIT_1, split[1]);
599 peParams.put(SPLIT_0, split[0]);
600 List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
601 if (queryData.isEmpty()) {
602 return error("Error Occured while Describing the Policy - query is empty");
604 PolicyEntity entity = (PolicyEntity) queryData.get(0);
607 temp = File.createTempFile(policyName, ".tmp");
608 } catch (IOException e) {
609 String message = "Failed to create temp file " + policyName + ".tmp";
610 LOGGER.error(message + e);
611 return error(message);
613 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
614 bw.write(entity.getPolicyData());
615 } catch (IOException e) {
616 LOGGER.error("Exception Occured while Describing the Policy" + e);
618 object = HumanPolicyComponent.DescribePolicy(temp);
620 Files.delete(temp.toPath());
621 } catch (IOException e) {
622 LOGGER.warn("Failed to delete " + temp.getName() + e);
627 // Get the List of Policies and Scopes for Showing in Editor tab
628 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
630 return processPolicyList(params, request);
631 } catch (Exception e) {
632 LOGGER.error("list", e);
633 return error(e.getMessage());
637 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
638 PolicyController controller = getPolicyControllerInstance();
639 // Get the Login Id of the User from Request
640 String testUserID = getTestUserId();
641 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
642 List<Object> userRoles = controller.getRoles(userId);
643 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
644 List<String> roles = pair.u;
645 Set<String> scopes = pair.t;
646 Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
648 List<JSONObject> resultList = new ArrayList<>();
649 String path = params.getString("path");
650 if (path.contains("..xml")) {
651 path = path.replaceAll("..xml", "").trim();
654 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
656 && !(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST))) {
657 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
659 if (!FORWARD_SLASH.equals(path)) {
660 String tempScope = path.substring(1);
661 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
662 scopes.add(tempScope);
667 if (!FORWARD_SLASH.equals(path)) {
669 String scopeName = path.substring(path.indexOf('/') + 1);
670 activePolicyList(scopeName, resultList, roles, scopes, roleByScope);
671 } catch (Exception ex) {
672 LOGGER.error("Error Occurred While reading Policy Files List" + ex);
674 return new JSONObject().put(RESULT, resultList);
676 processRoles(scopes, roles, resultList, roleByScope);
677 return new JSONObject().put(RESULT, resultList);
680 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList,
681 Map<String, String> roleByScope) {
682 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
683 List<Object> scopesList = queryPolicyEditorScopes(null);
684 scopesList.stream().map(list -> (PolicyEditorScopes) list).filter(
685 scope -> !(scope.getScopeName().contains(File.separator)) && !scopes.contains(scope.getScopeName()))
687 JSONObject el = new JSONObject();
688 el.put(NAME, scope.getScopeName());
689 el.put(DATE, scope.getModifiedDate());
692 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
693 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
694 el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
698 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
699 scopes.stream().map(this::queryPolicyEditorScopes).filter(scopesList -> !scopesList.isEmpty())
700 .forEach(scopesList -> {
701 JSONObject el = new JSONObject();
702 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
703 el.put(NAME, scopeById.getScopeName());
704 el.put(DATE, scopeById.getModifiedDate());
707 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
708 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
709 if ((resultList).stream()
710 .noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
711 el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
718 private List<Object> queryPolicyEditorScopes(String scopeName) {
719 String scopeNameQuery;
720 SimpleBindings params = new SimpleBindings();
721 if (scopeName == null) {
722 scopeNameQuery = "from PolicyEditorScopes";
724 scopeNameQuery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
725 params.put(SCOPE_NAME, scopeName + "%");
727 PolicyController controller = getPolicyControllerInstance();
728 return getDataByQueryFromController(controller, scopeNameQuery, params);
731 // Get Active Policy List based on Scope Selection from Policy Version table
732 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
733 Set<String> scopes, Map<String, String> roleByScope) {
734 PolicyController controller = getPolicyControllerInstance();
735 String scopeName = inScopeName;
736 if (scopeName.contains(FORWARD_SLASH)) {
737 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
739 if (scopeName.contains(BACKSLASH)) {
740 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
742 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
744 SimpleBindings params = new SimpleBindings();
745 params.put(SCOPE_NAME, scopeName + "%");
747 List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
748 List<Object> scopesList = getDataByQueryFromController(controller,
749 FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
750 for (Object list : scopesList) {
751 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
753 for (Object list : activePolicies) {
754 PolicyVersion policy = (PolicyVersion) list;
755 String scopeNameValue =
756 policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
757 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
758 String scopeNameCheck =
759 scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator)
761 if (!scopeNameValue.equals(scopeNameCheck)) {
764 JSONObject el = new JSONObject();
765 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
766 el.put(DATE, policy.getModifiedDate());
767 el.put(VERSION, policy.getActiveVersion());
769 el.put(TYPE, "file");
770 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
771 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
772 String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ? roleByScope.get(ALLSCOPES)
773 : roleByScope.get(scopeNameValue);
774 el.put(ROLETYPE, roleType);
776 } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) {
777 JSONObject el = new JSONObject();
778 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
779 el.put(DATE, policy.getModifiedDate());
780 el.put(VERSION, policy.getActiveVersion());
782 el.put(TYPE, "file");
783 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
784 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
790 private List<Object> getDataByQueryFromController(final PolicyController controller, final String query,
791 final SimpleBindings params) {
792 final List<Object> activePolicies;
793 if (PolicyController.isjUnit()) {
794 activePolicies = controller.getDataByQuery(query, null);
796 activePolicies = controller.getDataByQuery(query, params);
798 return activePolicies;
801 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById,
802 Map<String, String> roleByScope) {
803 String scope = scopeById.getScopeName();
804 if (!scope.contains(File.separator)) {
807 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
808 if (scopeName.contains(ESCAPE_BACKSLASH)) {
809 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
811 if (scope.contains(File.separator)) {
812 scope = scope.substring(targetScope.length() + 1);
813 if (scope.contains(File.separator)) {
814 scope = scope.substring(0, scope.indexOf(File.separator));
817 if (scopeName.equalsIgnoreCase(targetScope)) {
818 JSONObject el = new JSONObject();
820 el.put(DATE, scopeById.getModifiedDate());
823 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
824 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
825 String roleType = roleByScope.get(ALLSCOPES); // Set default role type to ALL_SCOPES
826 if (!Strings.isNullOrEmpty(roleByScope.get(scopeName))) {
827 roleType = roleByScope.get(scopeName);
828 } else if (!Strings.isNullOrEmpty(roleByScope.get(scopeName + File.separator + scope))) {
829 roleType = roleByScope.get(scopeName + File.separator + scope);
831 el.put(ROLETYPE, roleType);
837 private String getUserName(String loginId) {
838 PolicyController controller = getPolicyControllerInstance();
839 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
840 if (userInfo == null) {
843 return userInfo.getUserName();
847 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
849 return handlePolicyRename(params, request);
850 } catch (Exception e) {
851 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
852 return error(e.getMessage());
856 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
857 boolean isActive = false;
858 List<String> policyActiveInPDP = new ArrayList<>();
859 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
860 String userId = UserUtils.getUserSession(request).getOrgUserId();
861 String oldPath = params.getString("path");
862 String newPath = params.getString("newPath");
863 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
864 newPath = newPath.substring(newPath.indexOf('/') + 1);
865 String checkValidation;
866 if (oldPath.endsWith(".xml")) {
867 checkValidation = newPath.replace(".xml", "");
869 checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
870 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1);
871 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
872 return error("Policy Rename Failed. The Name contains special characters.");
874 JSONObject result = policyRename(oldPath, newPath, userId);
875 if (!(Boolean) (result.getJSONObject(RESULT).get(SUCCESS))) {
879 String scopeName = oldPath;
880 String newScopeName = newPath;
881 if (scopeName.contains(FORWARD_SLASH)) {
882 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
883 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
885 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator) + 1);
886 if (scopeName.contains(BACKSLASH)) {
887 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
888 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
890 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
891 return error("Scope Rename Failed. The Name contains special characters.");
893 PolicyController controller = getPolicyControllerInstance();
894 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
895 SimpleBindings pvParams = new SimpleBindings();
896 pvParams.put(SCOPE_NAME, scopeName + "%");
897 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
898 List<Object> scopesList =
899 controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
900 for (Object object : activePolicies) {
901 PolicyVersion activeVersion = (PolicyVersion) object;
902 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "."
903 + activeVersion.getActiveVersion() + ".xml";
904 String policyNewPath = policyOldPath.replace(oldPath, newPath);
905 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
906 if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
908 policyActiveInPDP.add(policyOldPath);
909 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
910 scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
913 boolean rename = activePolicies.size() != policyActiveInPDP.size();
914 if (policyActiveInPDP.isEmpty()) {
915 renameScope(scopesList, scopeName, newScopeName, controller);
917 renameScope(scopesList, scopeName, newScopeName, controller);
918 UserInfo userInfo = new UserInfo();
919 userInfo.setUserLoginId(userId);
920 scopeOfPolicyActiveInPDP.forEach(scope -> {
921 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
922 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
923 editorScopeEntity.setUserCreatedBy(userInfo);
924 editorScopeEntity.setUserModifiedBy(userInfo);
925 controller.saveData(editorScopeEntity);
929 return error("The Following policies rename failed. Since they are active in PDP Groups"
930 + policyActiveInPDP);
936 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName,
937 PolicyController controller) {
938 for (Object object : scopesList) {
939 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
940 String scopeName = inScopeName;
941 if (scopeName.contains(BACKSLASH_8TIMES)) {
942 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
943 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
945 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
946 editorScopeEntity.setScopeName(scope);
947 controller.updateData(editorScopeEntity);
951 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
954 PolicyController controller = getPolicyControllerInstance();
956 String policyVersionName = newPath.replace(".xml", "");
957 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
958 .replace(FORWARD_SLASH, File.separator);
960 String oldpolicyVersionName = oldPath.replace(".xml", "");
961 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.'))
962 .replace(FORWARD_SLASH, File.separator);
963 String newpolicyName = newPath.replace("/", ".");
964 String[] newPolicySplit = modifyPolicyName(newPath);
966 String[] oldPolicySplit = modifyPolicyName(oldPath);
968 // Check PolicyEntity table with newPolicy Name
969 String policyEntityquery =
970 "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
971 SimpleBindings policyParams = new SimpleBindings();
972 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
973 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
974 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
975 if (!queryData.isEmpty()) {
976 return error("Policy rename failed. Since, the policy with same name already exists.");
979 // Query the Policy Entity with oldPolicy Name
980 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
981 String oldPolicyEntityQuery =
982 "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + ":oldPolicySplit_0";
983 SimpleBindings params = new SimpleBindings();
984 params.put("policyEntityCheck", policyEntityCheck + "%");
985 params.put("oldPolicySplit_0", oldPolicySplit[0]);
986 List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params);
987 if (oldEntityData.isEmpty()) {
989 "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
992 StringBuilder groupQuery = new StringBuilder();
993 groupQuery.append("FROM PolicyGroupEntity where (");
994 SimpleBindings geParams = new SimpleBindings();
995 for (int i = 0; i < oldEntityData.size(); i++) {
996 entity = (PolicyEntity) oldEntityData.get(i);
998 groupQuery.append("policyid = :policyId");
999 geParams.put("policyId", entity.getPolicyId());
1001 groupQuery.append(" or policyid = :policyId").append(i);
1002 geParams.put("policyId" + i, entity.getPolicyId());
1005 groupQuery.append(")");
1006 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
1007 if (!groupEntityData.isEmpty()) {
1008 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
1010 for (Object anOldEntityData : oldEntityData) {
1011 entity = (PolicyEntity) anOldEntityData;
1012 String checkEntityName = entity.getPolicyName().replace(".xml", "");
1013 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
1014 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
1015 if (checkEntityName.equals(originalPolicyName)) {
1016 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0],
1017 oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
1021 } catch (Exception e) {
1022 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
1023 return error(e.getMessage());
1027 private String[] modifyPolicyName(String pathName) {
1028 return modifyPolicyName(FORWARD_SLASH, pathName);
1031 private String[] modifyPolicyName(String separator, String pathName) {
1032 String policyName = pathName.replace(separator, ".");
1033 if (policyName.contains(CONFIG2)) {
1034 policyName = policyName.replace(CONFIG, CONFIG1);
1035 } else if (policyName.contains(ACTION2)) {
1036 policyName = policyName.replace(ACTION, ACTION1);
1037 } else if (policyName.contains(DECISION2)) {
1038 policyName = policyName.replace(DECISION, DECISION1);
1040 return policyName.split(":");
1043 private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removeNewPolicyExtension,
1044 String oldScope, String removeOldPolicyExtension, String policyName, String newPolicyName,
1045 String oldPolicyName, String userId) {
1047 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1048 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1049 PolicyController controller = getPolicyControllerInstance();
1051 String oldPolicyNameWithoutExtension = removeOldPolicyExtension;
1052 String newPolicyNameWithoutExtension = removeNewPolicyExtension;
1053 if (removeOldPolicyExtension.endsWith(".xml")) {
1054 oldPolicyNameWithoutExtension =
1055 oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
1056 newPolicyNameWithoutExtension =
1057 newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
1059 entity.setPolicyName(
1060 entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1061 entity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1062 newScope + "." + newPolicyNameWithoutExtension));
1063 entity.setScope(newScope);
1064 entity.setModifiedBy(userId);
1066 String oldConfigurationName = null;
1067 String newConfigurationName = null;
1068 if (newPolicyName.contains(CONFIG2)) {
1069 oldConfigurationName = configEntity.getConfigurationName();
1070 configEntity.setConfigurationName(
1071 configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1072 newScope + "." + newPolicyNameWithoutExtension));
1073 controller.updateData(configEntity);
1074 newConfigurationName = configEntity.getConfigurationName();
1075 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1076 if (file.exists()) {
1078 new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1079 file.renameTo(renameFile);
1081 } else if (newPolicyName.contains(ACTION2)) {
1082 oldConfigurationName = actionEntity.getActionBodyName();
1083 actionEntity.setActionBody(
1084 actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1085 newScope + "." + newPolicyNameWithoutExtension));
1086 controller.updateData(actionEntity);
1087 newConfigurationName = actionEntity.getActionBodyName();
1088 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1089 if (file.exists()) {
1091 new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1092 file.renameTo(renameFile);
1095 controller.updateData(entity);
1097 PolicyRestController restController = new PolicyRestController();
1098 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1099 PolicyVersion versionEntity =
1100 (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName);
1101 versionEntity.setPolicyName(policyName);
1102 versionEntity.setModifiedBy(userId);
1103 controller.updateData(versionEntity);
1104 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1);
1105 String moveOldPolicyCheck = oldPolicyName.substring(oldPolicyName.lastIndexOf(File.separator) + 1);
1106 if (movePolicyCheck.equals(moveOldPolicyCheck)) {
1107 controller.watchPolicyFunction(versionEntity, oldPolicyName, "Move");
1109 controller.watchPolicyFunction(versionEntity, oldPolicyName, "Rename");
1111 } catch (Exception e) {
1112 LOGGER.error(EXCEPTION_OCCURED + e);
1117 private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
1118 String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException {
1119 String queryEntityName;
1120 PolicyController controller = getPolicyControllerInstance();
1121 PolicyEntity cloneEntity = new PolicyEntity();
1122 cloneEntity.setPolicyName(newpolicyName);
1123 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1124 String removenewPolicyExtension = inRemovenewPolicyExtension;
1125 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1126 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1127 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + removeoldPolicyExtension,
1128 newScope + "." + removenewPolicyExtension));
1129 cloneEntity.setScope(entity.getScope());
1130 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1131 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1132 String newConfigurationName = null;
1133 if (newpolicyName.contains(CONFIG2)) {
1134 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1135 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName()
1136 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1137 queryEntityName = configurationDataEntity.getConfigurationName();
1138 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1139 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1140 configurationDataEntity.setDeleted(false);
1141 configurationDataEntity.setCreatedBy(userId);
1142 configurationDataEntity.setModifiedBy(userId);
1143 controller.saveData(configurationDataEntity);
1144 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller
1145 .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1146 cloneEntity.setConfigurationData(configEntiy);
1147 newConfigurationName = configEntiy.getConfigurationName();
1148 try (FileWriter fw =
1149 new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1150 BufferedWriter bw = new BufferedWriter(fw)) {
1151 bw.write(configEntiy.getConfigBody());
1152 } catch (IOException e) {
1153 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1156 } else if (newpolicyName.contains(ACTION2)) {
1157 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1158 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName()
1159 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1160 queryEntityName = actionBodyEntity.getActionBodyName();
1161 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1162 actionBodyEntity.setDeleted(false);
1163 actionBodyEntity.setCreatedBy(userId);
1164 actionBodyEntity.setModifiedBy(userId);
1165 controller.saveData(actionBodyEntity);
1166 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class,
1167 "actionBodyName", queryEntityName);
1168 cloneEntity.setActionBodyEntity(actionEntiy);
1169 newConfigurationName = actionEntiy.getActionBodyName();
1170 try (FileWriter fw =
1171 new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1172 BufferedWriter bw = new BufferedWriter(fw)) {
1173 bw.write(actionEntiy.getActionBody());
1174 } catch (IOException e) {
1175 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1180 cloneEntity.setDeleted(entity.isDeleted());
1181 cloneEntity.setCreatedBy(userId);
1182 cloneEntity.setModifiedBy(userId);
1183 controller.saveData(cloneEntity);
1185 // Notify others paps regarding clone policy.
1186 PolicyRestController restController = new PolicyRestController();
1187 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1191 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1193 String userId = UserUtils.getUserSession(request).getOrgUserId();
1194 String oldPath = params.getString("path");
1195 String newPath = params.getString("newPath");
1196 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
1197 newPath = newPath.substring(newPath.indexOf('/') + 1);
1199 String policyVersionName = newPath.replace(".xml", "");
1200 String version = policyVersionName.substring(policyVersionName.indexOf('.') + 1);
1201 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
1202 .replace(FORWARD_SLASH, File.separator);
1204 String newPolicyName = newPath.replace(FORWARD_SLASH, ".");
1206 String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
1208 String newPolicyCheck = newPolicyName;
1209 if (newPolicyCheck.contains(CONFIG2)) {
1210 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1211 } else if (newPolicyCheck.contains(ACTION2)) {
1212 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1213 } else if (newPolicyCheck.contains(DECISION2)) {
1214 newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
1216 if (!newPolicyCheck.contains(":")) {
1217 return error("Policy Clone Failed. The Name contains special characters.");
1219 String[] newPolicySplit = newPolicyCheck.split(":");
1221 String checkValidation = newPolicySplit[1].replace(".xml", "");
1223 checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
1224 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
1225 return error("Policy Clone Failed. The Name contains special characters.");
1228 String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
1230 PolicyController controller = getPolicyControllerInstance();
1232 PolicyEntity entity = null;
1233 boolean success = false;
1235 // Check PolicyEntity table with newPolicy Name
1236 String policyEntityquery =
1237 "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1238 SimpleBindings policyParams = new SimpleBindings();
1239 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1240 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1241 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1242 if (!queryData.isEmpty()) {
1243 return error("Policy already exists with same name");
1246 // Query the Policy Entity with oldPolicy Name
1247 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1248 SimpleBindings peParams = new SimpleBindings();
1249 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1250 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1251 queryData = getDataByQueryFromController(controller, policyEntityquery, peParams);
1252 if (!queryData.isEmpty()) {
1253 entity = (PolicyEntity) queryData.get(0);
1255 if (entity != null) {
1256 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0],
1257 newPolicySplit[1], entity, userId);
1261 PolicyVersion entityItem = new PolicyVersion();
1262 entityItem.setActiveVersion(Integer.parseInt(version));
1263 entityItem.setHigherVersion(Integer.parseInt(version));
1264 entityItem.setPolicyName(policyName);
1265 entityItem.setCreatedBy(userId);
1266 entityItem.setModifiedBy(userId);
1267 entityItem.setModifiedDate(new Date());
1268 controller.saveData(entityItem);
1270 LOGGER.debug("copy from: {} to: {}" + oldPath + newPath);
1272 } catch (Exception e) {
1273 LOGGER.error("copy", e);
1274 return error(e.getMessage());
1278 // Delete Policy or Scope Functionality
1279 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1280 PolicyController controller = getPolicyControllerInstance();
1281 PolicyRestController restController = new PolicyRestController();
1282 PolicyEntity policyEntity = null;
1283 String policyNamewithoutExtension;
1285 String userId = UserUtils.getUserSession(request).getOrgUserId();
1286 String deleteVersion = "";
1287 String path = params.getString("path");
1288 LOGGER.debug("delete {}" + path);
1289 if (params.has("deleteVersion")) {
1290 deleteVersion = params.getString("deleteVersion");
1292 path = path.substring(path.indexOf('/') + 1);
1293 String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
1294 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1296 SimpleBindings policyParams = new SimpleBindings();
1297 if (path.endsWith(".xml")) {
1298 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1299 String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
1300 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1301 policyParams.put(SPLIT_1, split[1] + "%");
1302 policyParams.put(SPLIT_0, split[0]);
1304 policyNamewithoutExtension = path.replace(File.separator, ".");
1305 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension or scope = :exactScope";
1306 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + ".%");
1307 policyParams.put("exactScope", policyNamewithoutExtension);
1310 List<Object> policyEntityObjects = controller.getDataByQuery(query, policyParams);
1311 String activePolicyName = null;
1312 boolean pdpCheck = false;
1313 if (path.endsWith(".xml")) {
1314 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1315 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1));
1316 if ("ALL".equals(deleteVersion)) {
1317 if (!policyEntityObjects.isEmpty()) {
1318 for (Object object : policyEntityObjects) {
1319 policyEntity = (PolicyEntity) object;
1320 String groupEntityquery =
1321 "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'";
1322 SimpleBindings pgeParams = new SimpleBindings();
1323 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1324 if (!groupobject.isEmpty()) {
1326 activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1328 deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
1329 policyNamewithoutExtension);
1333 // Policy Notification
1334 PolicyVersion versionEntity = new PolicyVersion();
1335 versionEntity.setPolicyName(policyNamewithoutExtension);
1336 versionEntity.setModifiedBy(userId);
1337 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1339 // Delete from policyVersion table
1340 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1341 getActivePDPPolicyVersion =
1342 getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1);
1343 String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion
1344 + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='"
1345 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1346 controller.executeQuery(policyVersionQuery);
1348 "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
1349 + activePolicyName);
1351 // No Active Policy in PDP. So, deleting all entries from policyVersion table
1352 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1353 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1354 controller.executeQuery(policyVersionQuery);
1356 } else if ("CURRENT".equals(deleteVersion)) {
1357 String currentVersionPolicyName =
1358 policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator) + 1);
1359 String currentVersionScope =
1360 policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator))
1361 .replace(File.separator, ".");
1362 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1364 SimpleBindings peParams = new SimpleBindings();
1365 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1366 peParams.put("currentVersionScope", currentVersionScope);
1368 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1369 if (!policyEntitys.isEmpty()) {
1370 policyEntity = (PolicyEntity) policyEntitys.get(0);
1372 if (policyEntity == null) {
1376 String groupEntityquery =
1377 "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1378 SimpleBindings geParams = new SimpleBindings();
1379 geParams.put("policyEntityId", policyEntity.getPolicyId());
1380 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1381 if (!groupobject.isEmpty()) {
1382 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"
1383 + policyEntity.getScope() + "." + policyEntity.getPolicyName() + "'");
1386 // Delete the entity from Elastic Search Database
1387 deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
1388 policyNamewithoutExtension);
1391 int highestVersion = 0;
1392 if (!policyEntityObjects.isEmpty()) {
1393 for (Object object : policyEntityObjects) {
1394 policyEntity = (PolicyEntity) object;
1395 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1396 int policyEntityVersion = Integer
1397 .parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.') + 1));
1398 if (policyEntityVersion > highestVersion && policyEntityVersion != version) {
1399 highestVersion = policyEntityVersion;
1404 // Policy Notification
1405 PolicyVersion entity = new PolicyVersion();
1406 entity.setPolicyName(policyNamewithoutExtension);
1407 entity.setActiveVersion(highestVersion);
1408 entity.setModifiedBy(userId);
1409 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1412 if (highestVersion != 0) {
1413 updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + highestVersion
1414 + "' , highest_version='" + highestVersion + "' where policy_name ='"
1415 + policyNamewithoutExtension.replace("\\", "\\\\") + "'";
1417 updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1418 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1420 controller.executeQuery(updatequery);
1422 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1423 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1424 controller.executeQuery(policyVersionQuery);
1428 List<String> activePoliciesInPDP = new ArrayList<>();
1429 if (policyEntityObjects.isEmpty()) {
1430 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1431 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1432 controller.executeQuery(policyScopeQuery);
1435 for (Object object : policyEntityObjects) {
1436 policyEntity = (PolicyEntity) object;
1437 String groupEntityQuery = "from PolicyGroupEntity where policyid = :policyEntityId";
1438 SimpleBindings geParams = new SimpleBindings();
1439 geParams.put("policyEntityId", policyEntity.getPolicyId());
1440 List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams);
1441 if (!groupobject.isEmpty()) {
1443 activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
1445 // Delete the entity from Elastic Search Database
1446 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1447 restController.deleteElasticData(searchFileName);
1448 // Delete the entity from Policy Entity table
1449 controller.deleteData(policyEntity);
1450 policyNamewithoutExtension = policyEntity.getPolicyName();
1451 if (policyNamewithoutExtension.contains(CONFIG2)) {
1452 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1453 + policyEntity.getConfigurationData().getConfigurationName()));
1454 controller.deleteData(policyEntity.getConfigurationData());
1455 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1456 policyEntity.getConfigurationData().getConfigurationName());
1457 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1458 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1459 + policyEntity.getActionBodyEntity().getActionBodyName()));
1460 controller.deleteData(policyEntity.getActionBodyEntity());
1461 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1462 policyEntity.getActionBodyEntity().getActionBodyName());
1466 // Delete from policyVersion and policyEditor Scope table
1467 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"
1468 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + File.separator + PERCENT_AND_ID_GT_0;
1469 controller.executeQuery(policyVersionQuery);
1471 // Policy Notification
1472 PolicyVersion entity = new PolicyVersion();
1473 entity.setPolicyName(path);
1474 entity.setModifiedBy(userId);
1475 controller.watchPolicyFunction(entity, path, "DeleteScope");
1477 // Add Active Policies List to PolicyVersionTable
1478 for (String anActivePoliciesInPDP : activePoliciesInPDP) {
1479 String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", "");
1480 int activePDPPolicyVersion = Integer
1481 .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
1482 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.'))
1483 .replace(".", File.separator);
1484 PolicyVersion insertActivePDPVersion = new PolicyVersion();
1485 insertActivePDPVersion.setPolicyName(activePDPPolicyName);
1486 insertActivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1487 insertActivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1488 insertActivePDPVersion.setCreatedBy(userId);
1489 insertActivePDPVersion.setModifiedBy(userId);
1490 controller.saveData(insertActivePDPVersion);
1492 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"
1493 + activePoliciesInPDP);
1495 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1496 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1497 controller.executeQuery(policyScopeQuery);
1502 } catch (Exception e) {
1503 LOGGER.error(DELETE, e);
1504 return error(e.getMessage());
1508 private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller,
1509 final PolicyRestController restController, final PolicyEntity policyEntity,
1510 final String policyNamewithoutExtension) throws IOException {
1511 // Delete the entity from Elastic Search Database
1512 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1513 restController.deleteElasticData(searchFileName);
1514 // Delete the entity from Policy Entity table
1515 controller.deleteData(policyEntity);
1516 if (policyNamewithoutExtension.contains(CONFIG2)) {
1517 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1518 + policyEntity.getConfigurationData().getConfigurationName()));
1519 controller.deleteData(policyEntity.getConfigurationData());
1520 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1521 policyEntity.getConfigurationData().getConfigurationName());
1522 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1523 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1524 + policyEntity.getActionBodyEntity().getActionBodyName()));
1525 controller.deleteData(policyEntity.getActionBodyEntity());
1526 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1527 policyEntity.getActionBodyEntity().getActionBodyName());
1532 private JSONObject editFile(JSONObject params) throws ServletException {
1535 PolicyController controller = getPolicyControllerInstance();
1536 String mode = params.getString("mode");
1537 String path = params.getString("path");
1538 LOGGER.debug("editFile path: {}" + path);
1540 String domain = path.substring(1, path.lastIndexOf('/'));
1541 domain = domain.replace(FORWARD_SLASH, ".");
1543 path = path.substring(1);
1544 path = path.replace(FORWARD_SLASH, ".");
1546 String[] split = modifyPolicyName(path);
1548 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1549 SimpleBindings peParams = new SimpleBindings();
1550 peParams.put(SPLIT_1, split[1]);
1551 peParams.put(SPLIT_0, split[0]);
1552 List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
1553 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1554 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1556 Object policy = XACMLPolicyScanner.readPolicy(stream);
1557 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1558 policyAdapter.setData(policy);
1560 if ("viewPolicy".equalsIgnoreCase(mode)) {
1561 policyAdapter.setReadOnly(true);
1562 policyAdapter.setEditPolicy(false);
1564 policyAdapter.setReadOnly(false);
1565 policyAdapter.setEditPolicy(true);
1568 policyAdapter.setDomainDir(domain);
1569 policyAdapter.setPolicyData(policy);
1570 String policyName = path.replace(".xml", "");
1571 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1572 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1));
1574 PolicyAdapter setPolicyAdapter = PolicyAdapter.getInstance();
1575 Objects.requireNonNull(setPolicyAdapter).configure(policyAdapter, entity);
1577 policyAdapter.setParentPath(null);
1578 ObjectMapper mapper = new ObjectMapper();
1579 String json = mapper.writeValueAsString(policyAdapter);
1580 JsonNode jsonNode = mapper.readTree(json);
1582 return new JSONObject().put(RESULT, jsonNode);
1583 } catch (Exception e) {
1584 LOGGER.error("editFile", e);
1585 return error(e.getMessage());
1590 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1591 PolicyController controller = getPolicyControllerInstance();
1593 String name = getNameFromParams(params);
1594 String validateName =
1595 name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
1596 if (!name.isEmpty()) {
1597 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1598 if (!validate.contains(SUCCESS)) {
1599 return error(validate);
1601 LOGGER.debug("addFolder path: {} name: {}" + params.getString("path") + name);
1602 if (name.startsWith(File.separator)) {
1603 name = name.substring(1);
1605 PolicyEditorScopes entity =
1606 (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
1607 if (entity != null) {
1608 return error("Scope Already Exists");
1610 String userId = UserUtils.getUserSession(request).getOrgUserId();
1611 UserInfo userInfo = new UserInfo();
1612 userInfo.setUserLoginId(userId);
1613 PolicyEditorScopes newScope = new PolicyEditorScopes();
1614 newScope.setScopeName(name);
1615 newScope.setUserCreatedBy(userInfo);
1616 newScope.setUserModifiedBy(userInfo);
1617 controller.saveData(newScope);
1620 } catch (Exception e) {
1621 LOGGER.error("addFolder", e);
1622 return error(e.getMessage());
1626 private String getNameFromParams(final JSONObject params) {
1629 if (params.has(SUB_SCOPENAME)) {
1630 if (!"".equals(params.getString(SUB_SCOPENAME))) {
1631 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator
1632 + params.getString(SUB_SCOPENAME);
1635 name = params.getString(NAME);
1637 } catch (Exception e) {
1638 name = params.getString(NAME);
1639 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occurred While Adding Scope" + e);
1644 // Return Error Object
1645 private JSONObject error(String msg) throws ServletException {
1647 JSONObject result = new JSONObject();
1648 result.put(SUCCESS, false);
1649 result.put("error", msg);
1650 return new JSONObject().put(RESULT, result);
1651 } catch (JSONException e) {
1652 throw new ServletException(e);
1656 // Return Success Object
1657 private JSONObject success() throws ServletException {
1659 JSONObject result = new JSONObject();
1660 result.put(SUCCESS, true);
1661 result.put("error", (Object) null);
1662 return new JSONObject().put(RESULT, result);
1663 } catch (JSONException e) {
1664 throw new ServletException(e);
1668 private PolicyController getPolicyControllerInstance() {
1669 return policyController != null ? getPolicyController() : new PolicyController();
1672 private String getTestUserId() {
1676 public static void setTestUserId(String testUserId) {
1677 PolicyManagerServlet.testUserId = testUserId;