2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
26 package org.openecomp.policy.admin;
28 import java.io.BufferedReader;
29 import java.io.BufferedWriter;
30 import java.io.ByteArrayInputStream;
32 import java.io.FileInputStream;
33 import java.io.FileNotFoundException;
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.Path;
42 import java.nio.file.Paths;
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.List;
50 import javax.json.Json;
51 import javax.json.JsonArray;
52 import javax.json.JsonReader;
53 import javax.servlet.ServletConfig;
54 import javax.servlet.ServletException;
55 import javax.servlet.annotation.WebInitParam;
56 import javax.servlet.annotation.WebServlet;
57 import javax.servlet.http.HttpServlet;
58 import javax.servlet.http.HttpServletRequest;
59 import javax.servlet.http.HttpServletResponse;
61 import org.apache.commons.compress.utils.IOUtils;
62 import org.apache.commons.fileupload.FileItem;
63 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
64 import org.apache.commons.fileupload.servlet.ServletFileUpload;
65 import org.apache.http.HttpStatus;
66 import org.json.JSONException;
67 import org.json.JSONObject;
68 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
69 import org.openecomp.policy.common.logging.flexlogger.Logger;
70 import org.openecomp.policy.components.HumanPolicyComponent;
71 import org.openecomp.policy.controller.PolicyController;
72 import org.openecomp.policy.controller.PolicyExportAndImportController;
73 import org.openecomp.policy.model.Roles;
74 import org.openecomp.policy.rest.XACMLRest;
75 import org.openecomp.policy.rest.XACMLRestProperties;
76 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
77 import org.openecomp.policy.rest.jpa.ActionBodyEntity;
78 import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
79 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
80 import org.openecomp.policy.rest.jpa.PolicyEntity;
81 import org.openecomp.policy.rest.jpa.PolicyVersion;
82 import org.openecomp.policy.rest.jpa.UserInfo;
83 import org.openecomp.policy.utils.PolicyUtils;
84 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
85 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
86 import org.openecomp.portalsdk.core.web.support.UserUtils;
88 import com.att.research.xacml.util.XACMLProperties;
89 import com.fasterxml.jackson.databind.JsonNode;
90 import com.fasterxml.jackson.databind.ObjectMapper;
93 @WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
94 public class PolicyManagerServlet extends HttpServlet {
95 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
96 private static final long serialVersionUID = -8453502699403909016L;
99 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT
102 private static String CONTENTTYPE = "application/json";
103 private static String SUPERADMIN = "super-admin";
104 private static String SUPEREDITOR = "super-editor";
105 private static String SUPERGUEST = "super-guest";
106 private static String ADMIN = "admin";
107 private static String EDITOR = "editor";
108 private static String GUEST = "guest";
109 private static String RESULT = "result";
111 private static Path closedLoopJsonLocation;
112 private static JsonArray policyNames;
114 public static JsonArray getPolicyNames() {
118 public static void setPolicyNames(JsonArray policyNames) {
119 PolicyManagerServlet.policyNames = policyNames;
122 private static List<String> serviceTypeNamesList = new ArrayList<String>();
124 public static List<String> getServiceTypeNamesList() {
125 return serviceTypeNamesList;
129 public void init(ServletConfig servletConfig) throws ServletException {
130 super.init(servletConfig);
132 // Common initialization
134 XACMLRest.xacmlInit(servletConfig);
136 //Initialize ClosedLoop JSON
138 PolicyManagerServlet.initializeJSONLoad();
141 protected static void initializeJSONLoad() {
142 closedLoopJsonLocation = Paths.get(XACMLProperties
143 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
144 FileInputStream inputStream = null;
145 String location = closedLoopJsonLocation.toString();
147 inputStream = new FileInputStream(location);
148 } catch (FileNotFoundException e) {
151 if (location.endsWith("json")) {
152 JsonReader jsonReader = null;
153 jsonReader = Json.createReader(inputStream);
154 policyNames = jsonReader.readArray();
155 serviceTypeNamesList = new ArrayList<String>();
156 for (int i = 0; i < policyNames.size(); i++) {
157 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
158 String name = policyName.getJsonString("serviceTypePolicyName").getString();
159 serviceTypeNamesList.add(name);
166 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
167 LOGGER.debug("doPost");
169 // if request contains multipart-form-data
170 if (ServletFileUpload.isMultipartContent(request)) {
171 uploadFile(request, response);
173 // all other post request has json params in body
175 fileOperation(request, response);
177 } catch (Exception e) {
178 setError(e, response);
182 //Set Error Message for Exception
183 private void setError(Exception t, HttpServletResponse response) throws IOException {
185 JSONObject responseJsonObject = error(t.getMessage());
186 response.setContentType(CONTENTTYPE);
187 PrintWriter out = response.getWriter();
188 out.print(responseJsonObject);
190 } catch (Exception x) {
191 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
195 //Policy Import Functionality
196 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
199 Map<String, InputStream> files = new HashMap<String, InputStream>();
201 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
202 for (FileItem item : items) {
203 if (!item.isFormField()) {
204 // Process form file field (input type="file").
205 files.put(item.getName(), item.getInputStream());
206 if(item.getName().endsWith(".xls")){
208 File file = new File(item.getName());
209 OutputStream outputStream = new FileOutputStream(file);
210 IOUtils.copy(item.getInputStream(), outputStream);
211 outputStream.close();
212 newFile = file.toString();
213 PolicyExportAndImportController importController = new PolicyExportAndImportController();
214 importController.importRepositoryFile(newFile, request);
216 LOGGER.error("Upload error : " + e);
222 JSONObject responseJsonObject = null;
223 responseJsonObject = this.success();
224 response.setContentType("application/json");
225 PrintWriter out = response.getWriter();
226 out.print(responseJsonObject);
228 } catch (Exception e) {
229 LOGGER.debug("Cannot write file");
230 throw new ServletException("Cannot write file", e);
234 //File Operation Functionality
235 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
236 JSONObject responseJsonObject = null;
238 StringBuilder sb = new StringBuilder();
239 BufferedReader br = request.getReader();
241 while ((str = br.readLine()) != null) {
245 JSONObject jObj = new JSONObject(sb.toString());
246 JSONObject params = jObj.getJSONObject("params");
247 Mode mode = Mode.valueOf(params.getString("mode"));
250 responseJsonObject = addFolder(params, request);
253 responseJsonObject = copy(params, request);
256 responseJsonObject = delete(params, request);
259 responseJsonObject = editFile(params);
262 responseJsonObject = editFile(params);
265 responseJsonObject = list(params, request);
268 responseJsonObject = rename(params, request);
270 case DESCRIBEPOLICYFILE:
271 responseJsonObject = describePolicy(params);
274 responseJsonObject = addFolder(params, request);
277 responseJsonObject = switchVersion(params, request);
280 throw new ServletException("not implemented");
282 if (responseJsonObject == null) {
283 responseJsonObject = error("generic error : responseJsonObject is null");
285 } catch (Exception e) {
286 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
287 responseJsonObject = error(e.getMessage());
289 response.setContentType("application/json");
290 PrintWriter out = response.getWriter();
291 out.print(responseJsonObject);
295 //Switch Version Functionality
296 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
297 String path = params.getString("path");
298 String userId = null;
300 userId = UserUtils.getUserSession(request).getOrgUserId();
301 } catch (Exception e) {
302 LOGGER.error("Exception Occured while reading userid from cookie" +e);
305 String removeExtension = path.replace(".xml", "");
306 if(path.startsWith("/")){
307 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
309 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
312 String activePolicy = null;
313 PolicyController controller = new PolicyController();
314 if(params.toString().contains("activeVersion")){
315 String activeVersion = params.getString("activeVersion");
316 String highestVersion = params.get("highestVersion").toString();
317 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
318 return error("The Version shouldn't be greater than Highest Value");
320 activePolicy = policyName + "." + activeVersion + ".xml";
321 String dbCheckName = activePolicy.replace("/", ".");
322 if(dbCheckName.contains("Config_")){
323 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
324 }else if(dbCheckName.contains("Action_")){
325 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
326 }else if(dbCheckName.contains("Decision_")){
327 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
329 String[] splitDBCheckName = dbCheckName.split(":");
330 String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'";
331 List<Object> policyEntity = controller.getDataByQuery(peQuery);
332 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
333 if(pentity.isDeleted()){
334 return error("The Policy is Not Existing in Workspace");
336 if(policyName.contains("/")){
337 policyName = policyName.replace("/", File.separator);
339 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
340 if(policyName.contains("\\")){
341 policyName = policyName.replace(File.separator, "\\");
343 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
344 String watchPolicyName = policyName;
345 if(policyName.contains("/")){
346 policyName = policyName.replace("/", File.separator);
348 if(policyName.contains("\\")){
349 policyName = policyName.replace("\\", "\\\\");
351 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
353 controller.executeQuery(query);
354 //Policy Notification
355 PolicyVersion entity = new PolicyVersion();
356 entity.setPolicyName(watchPolicyName);
357 entity.setActiveVersion(Integer.parseInt(activeVersion));
358 entity.setModifiedBy(userId);
359 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
364 return controller.switchVersionPolicyContent(policyName);
368 private JSONObject describePolicy(JSONObject params) throws ServletException{
369 JSONObject object = null;
370 String path = params.getString("path");
371 String policyName = null;
372 if(path.startsWith("/")){
373 path = path.substring(1);
374 policyName = path.substring(path.lastIndexOf("/") +1);
375 path = path.replace("/", ".");
377 path = path.replace("/", ".");
379 if(path.contains("Config_")){
380 path = path.replace(".Config_", ":Config_");
381 }else if(path.contains("Action_")){
382 path = path.replace(".Action_", ":Action_");
383 }else if(path.contains("Decision_")){
384 path = path.replace(".Decision_", ":Decision_");
386 PolicyController controller = new PolicyController();
387 String[] split = path.split(":");
388 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
389 List<Object> queryData = controller.getDataByQuery(query);
390 if(queryData != null){
391 PolicyEntity entity = (PolicyEntity) queryData.get(0);
394 temp = File.createTempFile(policyName, ".tmp");
395 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
396 bw.write(entity.getPolicyData());
398 object = HumanPolicyComponent.DescribePolicy(temp);
399 } catch (IOException e) {
405 return error("Error Occured while Describing the Policy");
411 //Get the List of Policies and Scopes for Showing in Editor tab
412 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
413 Set<String> scopes = null;
414 List<String> roles = null;
416 //Get the Login Id of the User from Request
417 String userId = UserUtils.getUserSession(request).getOrgUserId();
418 //Check if the Role and Scope Size are Null get the values from db.
419 List<Object> userRoles = PolicyController.getRoles(userId);
420 roles = new ArrayList<String>();
421 scopes = new HashSet<String>();
422 for(Object role: userRoles){
423 Roles userRole = (Roles) role;
424 roles.add(userRole.getRole());
425 if(userRole.getScope() != null){
426 if(userRole.getScope().contains(",")){
427 String[] multipleScopes = userRole.getScope().split(",");
428 for(int i =0; i < multipleScopes.length; i++){
429 scopes.add(multipleScopes[i]);
432 scopes.add(userRole.getScope());
436 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
437 if(scopes.isEmpty()){
438 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
442 List<JSONObject> resultList = new ArrayList<JSONObject>();
443 boolean onlyFolders = params.getBoolean("onlyFolders");
444 String path = params.getString("path");
445 if(path.contains("..xml")){
446 path = path.replaceAll("..xml", "").trim();
450 if("/".equals(path)){
451 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
452 List<Object> scopesList = queryPolicyEditorScopes(null);
453 for(Object list : scopesList){
454 PolicyEditorScopes scope = (PolicyEditorScopes) list;
455 if(!(scope.getScopeName().contains(File.separator))){
456 JSONObject el = new JSONObject();
457 el.put("name", scope.getScopeName());
458 el.put("date", scope.getCreatedDate());
460 el.put("type", "dir");
461 el.put("createdBy", scope.getUserCreatedBy().getUserName());
462 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
466 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
467 for(Object scope : scopes){
468 JSONObject el = new JSONObject();
469 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
470 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
471 el.put("name", scopeById.getScopeName());
472 el.put("date", scopeById.getCreatedDate());
474 el.put("type", "dir");
475 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
476 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
482 String scopeName = path.substring(path.indexOf("/") +1);
483 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
484 } catch (Exception ex) {
485 LOGGER.error("Error Occured While reading Policy Files List"+ex );
489 return new JSONObject().put(RESULT, resultList);
490 } catch (Exception e) {
491 LOGGER.error("list", e);
492 return error(e.getMessage());
496 private List<Object> queryPolicyEditorScopes(String scopeName){
497 String scopeNamequery = "";
498 if(scopeName == null){
499 scopeNamequery = "from PolicyEditorScopes";
501 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'";
503 PolicyController controller = new PolicyController();
504 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
508 //Get Active Policy List based on Scope Selection form Policy Version table
509 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
510 PolicyController controller = new PolicyController();
511 if(scopeName.contains("/")){
512 scopeName = scopeName.replace("/", File.separator);
514 if(scopeName.contains("\\")){
515 scopeName = scopeName.replace("\\", "\\\\\\\\");
517 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
518 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
519 List<Object> activePolicies = controller.getDataByQuery(query);
520 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
521 for(Object list : scopesList){
522 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
523 String scope = scopeById.getScopeName();
524 if(scope.contains(File.separator)){
525 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
526 if(scopeName.contains("\\\\")){
527 scopeName = scopeName.replace("\\\\", File.separator);
529 if(scope.contains(File.separator)){
530 scope = scope.substring(checkScope.length()+1);
531 if(scope.contains(File.separator)){
532 scope = scope.substring(0, scope.indexOf(File.separator));
535 if(scopeName.equalsIgnoreCase(checkScope)){
536 JSONObject el = new JSONObject();
537 el.put("name", scope);
538 el.put("date", scopeById.getModifiedDate());
540 el.put("type", "dir");
541 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
542 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
547 String scopeNameCheck = null;
548 for (Object list : activePolicies) {
549 PolicyVersion policy = (PolicyVersion) list;
550 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
551 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
552 if((scopeName.contains("\\\\"))){
553 scopeNameCheck = scopeName.replace("\\\\", File.separator);
555 scopeNameCheck = scopeName;
557 if(scopeNameValue.equals(scopeNameCheck)){
558 JSONObject el = new JSONObject();
559 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
560 el.put("date", policy.getModifiedDate());
561 el.put("version", policy.getActiveVersion());
563 el.put("type", "file");
564 el.put("createdBy", getUserName(policy.getCreatedBy()));
565 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
568 }else if(!scopes.isEmpty()){
569 if(scopes.contains(scopeNameValue)){
570 JSONObject el = new JSONObject();
571 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
572 el.put("date", policy.getModifiedDate());
573 el.put("version", policy.getActiveVersion());
575 el.put("type", "file");
576 el.put("createdBy", getUserName(policy.getCreatedBy()));
577 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
584 private String getUserName(String loginId){
585 PolicyController controller = new PolicyController();
586 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
587 return userInfo.getUserName();
591 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
593 String userId = UserUtils.getUserSession(request).getOrgUserId();
594 String oldPath = params.getString("path");
595 String newPath = params.getString("newPath");
596 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
597 newPath = newPath.substring(newPath.indexOf("/")+1);
598 if(oldPath.endsWith(".xml")){
599 policyRename(oldPath, newPath, userId);
601 String scopeName = oldPath;
602 String newScopeName = newPath;
603 if(scopeName.contains("/")){
604 scopeName = scopeName.replace("/", File.separator);
605 newScopeName = newScopeName.replace("/", File.separator);
607 if(scopeName.contains("\\")){
608 scopeName = scopeName.replace("\\", "\\\\\\\\");
609 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
611 PolicyController controller = new PolicyController();
612 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
613 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
614 List<Object> activePolicies = controller.getDataByQuery(query);
615 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
616 for(Object object : activePolicies){
617 PolicyVersion activeVersion = (PolicyVersion) object;
618 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
619 String policyNewPath = policyOldPath.replace(oldPath, newPath);
620 policyRename(policyOldPath, policyNewPath, userId);
622 for(Object object : scopesList){
623 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
624 if(scopeName.contains("\\\\\\\\")){
625 scopeName = scopeName.replace("\\\\\\\\", File.separator);
626 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
628 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
629 editorScopeEntity.setScopeName(scope);
630 controller.updateData(editorScopeEntity);
634 } catch (Exception e) {
635 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
636 return error(e.getMessage());
640 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
642 PolicyEntity entity = null;
643 PolicyController controller = new PolicyController();
645 String policyVersionName = newPath.replace(".xml", "");
646 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
648 String oldpolicyVersionName = oldPath.replace(".xml", "");
649 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
651 String newpolicyName = newPath.replace("/", ".");
652 String newPolicyCheck = newpolicyName;
653 if(newPolicyCheck.contains("Config_")){
654 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
655 }else if(newPolicyCheck.contains("Action_")){
656 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
657 }else if(newPolicyCheck.contains("Decision_")){
658 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
660 String[] newPolicySplit = newPolicyCheck.split(":");
662 String orignalPolicyName = oldPath.replace("/", ".");
663 String oldPolicyCheck = orignalPolicyName;
664 if(oldPolicyCheck.contains("Config_")){
665 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
666 }else if(oldPolicyCheck.contains("Action_")){
667 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
668 }else if(oldPolicyCheck.contains("Decision_")){
669 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
671 String[] oldPolicySplit = oldPolicyCheck.split(":");
673 //Check PolicyEntity table with newPolicy Name
674 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
675 System.out.println(policyEntityquery);
676 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
677 if(!queryData.isEmpty()){
678 entity = (PolicyEntity) queryData.get(0);
682 //if a policy exists with new name check if it is deleted or not
683 if(entity.isDeleted()){
684 //Check Policy Group Entity table if policy has been pushed or not
685 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
686 List<Object> object = controller.getDataByQuery(query);
687 if(object.isEmpty()){
688 //if PolicyGroupEntity data is empty delete the entry from database
689 controller.deleteData(entity);
690 //Query the Policy Entity with oldPolicy Name
691 String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
692 System.out.println(oldpolicyEntityquery);
693 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
694 if(!oldEntityData.isEmpty()){
695 entity = (PolicyEntity) oldEntityData.get(0);
697 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
699 return error("Policy rename failed due to policy with new name existing in PDP Group.");
702 return error("Policy rename failed due to same name existing.");
705 //Query the Policy Entity with oldPolicy Name
706 String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
707 System.out.println(oldpolicyEntityquery);
708 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
709 if(!oldEntityData.isEmpty()){
710 entity = (PolicyEntity) oldEntityData.get(0);
712 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
716 } catch (Exception e) {
717 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
718 return error(e.getMessage());
722 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
723 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
725 ConfigurationDataEntity configEntity;
726 ActionBodyEntity actionEntity;
727 PolicyController controller = new PolicyController();
728 configEntity = entity.getConfigurationData();
729 actionEntity = entity.getActionBodyEntity();
731 //Check Policy Group Entity table if policy has been pushed or not
732 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
733 List<Object> object = controller.getDataByQuery(query);
735 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
736 String newPolicyNameWithoutExtension = removenewPolicyExtension;
737 if(removeoldPolicyExtension.endsWith(".xml")){
738 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
739 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
741 entity.setPolicyName(entity.getPolicyName().replace(removeoldPolicyExtension, removenewPolicyExtension));
742 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
743 entity.setScope(newScope);
744 entity.setModifiedBy(userId);
745 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
746 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
747 if(newpolicyName.contains("Config_")){
748 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
749 controller.updateData(configEntity);
750 }else if(newpolicyName.contains("Action_")){
751 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
752 controller.updateData(actionEntity);
754 controller.updateData(entity);
756 //Mark as Deleted in PolicyEntiy table
757 entity.setDeleted(true);
758 controller.updateData(entity);
759 //Mark as Deleted in ConfigurationDataEntity table
760 configEntity.setDeleted(true);
761 controller.updateData(configEntity);
762 //Mark as Deleted in ActionDataEntity table
763 actionEntity.setDeleted(true);
764 controller.updateData(actionEntity);
766 cloneRecord(newpolicyName, oldScope, removeoldPolicyExtension, newScope, removenewPolicyExtension, entity, userId);
769 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
770 versionEntity.setPolicyName(policyName);
771 versionEntity.setModifiedBy(userId);
772 controller.updateData(versionEntity);
773 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
774 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
775 if(movePolicyCheck.equals(moveOldPolicyCheck)){
776 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
778 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
782 } catch (Exception e) {
784 return error(e.getMessage());
788 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
789 String queryEntityName = null;
790 PolicyController controller = new PolicyController();
791 PolicyEntity cloneEntity = new PolicyEntity();
792 cloneEntity.setPolicyName(newpolicyName);
793 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
794 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
795 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
796 cloneEntity.setScope(entity.getScope());
797 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
798 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
799 if(newpolicyName.contains("Config_")){
800 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
801 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
802 queryEntityName = configurationDataEntity.getConfigurationName();
803 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
804 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
805 configurationDataEntity.setDeleted(false);
806 configurationDataEntity.setCreatedBy(userId);
807 configurationDataEntity.setModifiedBy(userId);
808 controller.saveData(configurationDataEntity);
809 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
810 cloneEntity.setConfigurationData(configEntiy);
811 }else if(newpolicyName.contains("Action_")){
812 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
813 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
814 queryEntityName = actionBodyEntity.getActionBodyName();
815 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
816 actionBodyEntity.setDeleted(false);
817 actionBodyEntity.setCreatedBy(userId);
818 actionBodyEntity.setModifiedBy(userId);
819 controller.saveData(actionBodyEntity);
820 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
821 cloneEntity.setActionBodyEntity(actionEntiy);
823 cloneEntity.setDeleted(entity.isDeleted());
824 cloneEntity.setCreatedBy(userId);
825 cloneEntity.setModifiedBy(userId);
826 controller.saveData(cloneEntity);
832 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
834 String userId = UserUtils.getUserSession(request).getOrgUserId();
835 String oldPath = params.getString("path");
836 String newPath = params.getString("newPath");
837 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
838 newPath = newPath.substring(newPath.indexOf("/")+1);
840 String policyVersionName = newPath.replace(".xml", "");
841 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
842 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
844 String newpolicyName = newPath.replace("/", ".");
846 String orignalPolicyName = oldPath.replace("/", ".");
848 String newPolicyCheck = newpolicyName;
849 if(newPolicyCheck.contains("Config_")){
850 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
851 }else if(newPolicyCheck.contains("Action_")){
852 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
853 }else if(newPolicyCheck.contains("Decision_")){
854 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
856 String[] newPolicySplit = newPolicyCheck.split(":");
858 String oldPolicyCheck = orignalPolicyName;
859 if(oldPolicyCheck.contains("Config_")){
860 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
861 }else if(oldPolicyCheck.contains("Action_")){
862 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
863 }else if(oldPolicyCheck.contains("Decision_")){
864 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
866 String[] oldPolicySplit = oldPolicyCheck.split(":");
868 PolicyController controller = new PolicyController();
870 PolicyEntity entity = null;
871 boolean success = false;
873 //Check PolicyEntity table with newPolicy Name
874 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
875 System.out.println(policyEntityquery);
876 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
877 if(!queryData.isEmpty()){
878 entity = (PolicyEntity) queryData.get(0);
881 //if a policy exists with new name check if it is deleted or not
882 if(entity.isDeleted()){
883 //Check Policy Group Entity table if policy has been pushed or not
884 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
885 List<Object> object = controller.getDataByQuery(query);
887 //if PolicyGroupEntity data is empty delete the entry from database
888 controller.deleteData(entity);
889 //Query the Policy Entity with oldPolicy Name
890 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
891 System.out.println(policyEntityquery);
892 queryData = controller.getDataByQuery(policyEntityquery);
893 if(!queryData.isEmpty()){
894 entity = (PolicyEntity) queryData.get(0);
897 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
901 return error("Policy Clone failed due to policy with new name existing in PDP Group.");
904 return error("Policy Clone failed due to same name existing.");
907 //Query the Policy Entity with oldPolicy Name
908 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
909 System.out.println(policyEntityquery);
910 queryData = controller.getDataByQuery(policyEntityquery);
911 if(!queryData.isEmpty()){
912 entity = (PolicyEntity) queryData.get(0);
915 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
920 PolicyVersion entityItem = new PolicyVersion();
921 entityItem.setActiveVersion(Integer.parseInt(version));
922 entityItem.setHigherVersion(Integer.parseInt(version));
923 entityItem.setPolicyName(policyName);
924 entityItem.setCreatedBy(userId);
925 entityItem.setModifiedBy(userId);
926 controller.saveData(entityItem);
929 LOGGER.debug("copy from: {} to:Â {}" + oldPath +newPath);
932 } catch (Exception e) {
933 LOGGER.error("copy", e);
934 return error(e.getMessage());
938 //Delete Policy or Scope Functionality
939 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
940 PolicyController controller = new PolicyController();
941 PolicyRestController restController = new PolicyRestController();
942 PolicyEntity policyEntity = null;
943 String policyNamewithoutExtension;
945 String userId = UserUtils.getUserSession(request).getOrgUserId();
946 String deleteVersion = "";
947 String path = params.getString("path");
948 LOGGER.debug("delete {}" +path);
949 if(params.has("deleteVersion")){
950 deleteVersion = params.getString("deleteVersion");
952 path = path.substring(path.indexOf("/")+1);
953 String policyNamewithExtension = path.replace("/", File.separator);
954 String policyVersionName = policyNamewithExtension.replace(".xml", "");
956 if(path.endsWith(".xml")){
957 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
958 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
959 String splitPolicyName = null;
960 if(policyNamewithoutExtension.contains("Config_")){
961 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
962 }else if(policyNamewithoutExtension.contains("Action_")){
963 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
964 }else if(policyNamewithoutExtension.contains("Decision_")){
965 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
967 String[] split = splitPolicyName.split(":");
968 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
970 policyNamewithoutExtension = path.replace(File.separator, ".");
971 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
974 List<Object> policyEntityobjects = controller.getDataByQuery(query);
975 boolean pdpCheck = true;
976 if(path.endsWith(".xml")){
977 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
978 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
979 if("ALL".equals(deleteVersion)){
980 if(!policyEntityobjects.isEmpty()){
981 for(Object object : policyEntityobjects){
982 policyEntity = (PolicyEntity) object;
983 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
984 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
985 if(groupobject != null){
992 for(Object object : policyEntityobjects){
993 policyEntity = (PolicyEntity) object;
994 //Delete the entity from Elastic Search Database
995 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
996 restController.deleteElasticData(searchFileName);
997 //Delete the entity from Policy Entity table
998 controller.deleteData(policyEntity);
999 if(policyNamewithoutExtension.contains("Config_")){
1000 controller.deleteData(policyEntity.getConfigurationData());
1001 }else if(policyNamewithoutExtension.contains("Action_")){
1002 controller.deleteData(policyEntity.getActionBodyEntity());
1005 //Policy Notification
1006 PolicyVersion versionEntity = new PolicyVersion();
1007 versionEntity.setPolicyName(policyNamewithoutExtension);
1008 versionEntity.setModifiedBy(userId);
1009 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1010 //Delete from policyVersion table
1011 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1012 if(policyVersionQuery != null){
1013 controller.executeQuery(policyVersionQuery);
1016 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1018 }else if("CURRENT".equals(deleteVersion)){
1019 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1020 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1021 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1022 List<Object> policyEntitys = controller.getDataByQuery(query);
1023 if(!policyEntitys.isEmpty()){
1024 policyEntity = (PolicyEntity) policyEntitys.get(0);
1026 if(policyEntity != null){
1027 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1028 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1029 if(groupobject == null){
1030 //Delete the entity from Elastic Search Database
1031 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1032 restController.deleteElasticData(searchFileName);
1033 //Delete the entity from Policy Entity table
1034 controller.deleteData(policyEntity);
1035 if(policyNamewithoutExtension.contains("Config_")){
1036 controller.deleteData(policyEntity.getConfigurationData());
1037 }else if(policyNamewithoutExtension.contains("Action_")){
1038 controller.deleteData(policyEntity.getActionBodyEntity());
1042 int highestVersion = 0;
1043 if(policyEntityobjects.isEmpty()){
1044 for(Object object : policyEntityobjects){
1045 policyEntity = (PolicyEntity) object;
1046 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1047 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1048 if(policyEntityVersion > highestVersion){
1049 highestVersion = policyEntityVersion;
1054 //Policy Notification
1055 PolicyVersion entity = new PolicyVersion();
1056 entity.setPolicyName(policyNamewithoutExtension);
1057 entity.setActiveVersion(highestVersion);
1058 entity.setModifiedBy(userId);
1059 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1061 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1062 controller.executeQuery(updatequery);
1064 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1065 if(policyVersionQuery != null){
1066 controller.executeQuery(policyVersionQuery);
1070 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1075 if(!policyEntityobjects.isEmpty()){
1076 for(Object object : policyEntityobjects){
1077 policyEntity = (PolicyEntity) object;
1078 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1079 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1080 if(groupobject != null){
1085 for(Object object : policyEntityobjects){
1086 policyEntity = (PolicyEntity) object;
1087 //Delete the entity from Elastic Search Database
1088 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1089 restController.deleteElasticData(searchFileName);
1090 //Delete the entity from Policy Entity table
1091 controller.deleteData(policyEntity);
1092 policyNamewithoutExtension = policyEntity.getPolicyName();
1093 if(policyNamewithoutExtension.contains("Config_")){
1094 controller.deleteData(policyEntity.getConfigurationData());
1095 }else if(policyNamewithoutExtension.contains("Action_")){
1096 controller.deleteData(policyEntity.getActionBodyEntity());
1100 //Delete from policyVersion and policyEditor Scope table
1101 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1102 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1103 controller.executeQuery(policyVersionQuery);
1104 controller.executeQuery(policyScopeQuery);
1105 //Policy Notification
1106 PolicyVersion entity = new PolicyVersion();
1107 entity.setPolicyName(path);
1108 entity.setModifiedBy(userId);
1109 controller.watchPolicyFunction(entity, path, "DeleteScope");
1114 } catch (Exception e) {
1115 LOGGER.error("delete", e);
1116 return error(e.getMessage());
1121 private JSONObject editFile(JSONObject params) throws ServletException {
1124 PolicyController controller = new PolicyController();
1125 String mode = params.getString("mode");
1126 String path = params.getString("path");
1127 LOGGER.debug("editFile path: {}"+ path);
1129 String domain = path.substring(1, path.lastIndexOf("/"));
1130 domain = domain.replace("/", ".");
1132 path = path.substring(1);
1133 path = path.replace("/", ".");
1134 String dbCheckName = path;
1135 if(dbCheckName.contains("Config_")){
1136 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1137 }else if(dbCheckName.contains("Action_")){
1138 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1139 }else if(dbCheckName.contains("Decision_")){
1140 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1143 String[] split = dbCheckName.split(":");
1144 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1145 List<Object> queryData = controller.getDataByQuery(query);
1146 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1147 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1150 Object policy = XACMLPolicyScanner.readPolicy(stream);
1151 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1152 policyAdapter.setData(policy);
1154 if("viewPolicy".equalsIgnoreCase(mode)){
1155 policyAdapter.setReadOnly(true);
1156 policyAdapter.setEditPolicy(false);
1158 policyAdapter.setReadOnly(false);
1159 policyAdapter.setEditPolicy(true);
1161 policyAdapter.setDomain(domain);
1162 policyAdapter.setDomainDir(domain);
1163 policyAdapter.setPolicyData(policy);
1164 String policyName = path.replace(".xml", "");
1165 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1166 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1168 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1169 setpolicyAdapter.configure(policyAdapter,entity);
1171 policyAdapter.setParentPath(null);
1172 ObjectMapper mapper = new ObjectMapper();
1173 String json = mapper.writeValueAsString(policyAdapter);
1174 JsonNode jsonNode = mapper.readTree(json);
1176 return new JSONObject().put(RESULT, jsonNode);
1177 } catch (Exception e) {
1178 LOGGER.error("editFile", e);
1179 return error(e.getMessage());
1184 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1185 PolicyController controller = new PolicyController();
1188 String userId = UserUtils.getUserSession(request).getOrgUserId();
1189 String path = params.getString("path");
1191 if(params.has("subScopename")){
1192 if(!params.getString("subScopename").equals("")){
1193 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1196 name = params.getString("name");
1198 }catch(Exception e){
1199 name = params.getString("name");
1200 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1202 String validateName;
1203 if(name.contains(File.separator)){
1204 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1206 validateName = name;
1208 if(!name.isEmpty()){
1209 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1210 if(!validate.contains("success")){
1211 return error(validate);
1214 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1215 if(!name.equals("")){
1216 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1218 UserInfo userInfo = new UserInfo();
1219 userInfo.setUserLoginId(userId);
1220 PolicyEditorScopes newScope = new PolicyEditorScopes();
1221 String scopeName = null;
1222 if(name.startsWith(File.separator)){
1223 scopeName = name.substring(1);
1227 newScope.setScopeName(scopeName);
1228 newScope.setUserCreatedBy(userInfo);
1229 newScope.setUserModifiedBy(userInfo);
1230 controller.saveData(newScope);
1232 return error("Scope Already Exists");
1236 } catch (Exception e) {
1237 LOGGER.error("addFolder", e);
1238 return error(e.getMessage());
1242 //Return Error Object
1243 private JSONObject error(String msg) throws ServletException {
1245 JSONObject result = new JSONObject();
1246 result.put("success", false);
1247 result.put("error", msg);
1248 return new JSONObject().put(RESULT, result);
1249 } catch (JSONException e) {
1250 throw new ServletException(e);
1254 //Return Success Object
1255 private JSONObject success() throws ServletException {
1257 JSONObject result = new JSONObject();
1258 result.put("success", true);
1259 result.put("error", (Object) null);
1260 return new JSONObject().put(RESULT, result);
1261 } catch (JSONException e) {
1262 throw new ServletException(e);