aboutsummaryrefslogtreecommitdiffstats
path: root/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler
diff options
context:
space:
mode:
Diffstat (limited to 'ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler')
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java102
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java458
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java63
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java323
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java210
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java157
6 files changed, 1313 insertions, 0 deletions
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java
new file mode 100644
index 000000000..efaed9ffc
--- /dev/null
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pap.xacml.rest.handler;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.policy.common.logging.ECOMPLoggingContext;
+import org.openecomp.policy.pap.xacml.rest.service.ImportService;
+import org.openecomp.policy.pap.xacml.rest.service.MetricService;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+
+public class APIRequestHandler {
+
+ private EcompPDPGroup newGroup;
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{
+ // Request from the API to get Dictionary Items
+ if ("api".equalsIgnoreCase(apiflag)) {
+ DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance();
+ dictionaryHandler.doDictionaryAPIGet(request, response);
+ return;
+ }
+ // Request from the API to get the gitPath
+ if ("gitPath".equalsIgnoreCase(apiflag)) {
+ PushPolicyHandler pushHandler = new PushPolicyHandler();
+ pushHandler.getGitPath(request, response);
+ return;
+ }
+ // Request from the API to get the ActiveVersion from the PolicyVersion table
+ if ("version".equalsIgnoreCase(apiflag)){
+ PushPolicyHandler pushHandler = new PushPolicyHandler();
+ pushHandler.getActiveVersion(request, response);
+ return;
+ }
+ // Request from the API to get the URI from the gitpath
+ if ("uri".equalsIgnoreCase(apiflag)){
+ PushPolicyHandler pushHandler = new PushPolicyHandler();
+ pushHandler.getSelectedURI(request, response);
+ return;
+ }
+ if ("getMetrics".equalsIgnoreCase(apiflag)){
+ MetricService.doGetPolicyMetrics(request, response);
+ return;
+ }
+ }
+
+ public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException {
+ if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service)){
+ ImportService importService = new ImportService();
+ importService.doImportMicroServicePut(request, response);
+ return;
+ }
+ if ("dictionaryItem".equalsIgnoreCase(service)) {
+ DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance();
+ dictionaryHandler.doDictionaryAPIPut(request, response);
+ return;
+ } else {
+ SavePolicyHandler savePolicy = SavePolicyHandler.getInstance();
+ savePolicy.doPolicyAPIPut(request, response);
+ }
+ }
+
+ public void doDelete(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext, String apiflag) throws Exception {
+ DeleteHandler deleteHandler = DeleteHandler.getInstance();
+ if ("deletePapApi".equalsIgnoreCase(apiflag)) {
+ deleteHandler.doAPIDeleteFromPAP(request, response, loggingContext);
+ return;
+ } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) {
+ deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext);
+ setNewGroup(deleteHandler.getDeletedGroup());
+ return;
+ }
+ }
+
+ private void setNewGroup(EcompPDPGroup newGroup) {
+ this.newGroup = newGroup;
+ }
+
+ public EcompPDPGroup getNewGroup() {
+ return newGroup;
+ }
+}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java
new file mode 100644
index 000000000..15e1faa04
--- /dev/null
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java
@@ -0,0 +1,458 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pap.xacml.rest.handler;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Query;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.policy.common.logging.ECOMPLoggingContext;
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
+import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
+import org.openecomp.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
+import org.openecomp.policy.pap.xacml.rest.model.RemoveGroupPolicy;
+import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.att.research.xacml.util.XACMLProperties;
+
+public class DeleteHandler {
+
+ private EcompPDPGroup newgroup;
+
+ private static String papDbDriver = null;
+ private static String papDbUrl = null;
+ private static String papDbUser = null;
+ private static String papDbPassword = null;
+
+ public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws Exception {
+ // get the request content into a String
+ String json = null;
+ java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+ PolicyLogger.info("JSON request from API: " + json);
+ // convert Object sent as JSON into local object
+ StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
+ String policyName = policy.getPolicyName();
+ Boolean policyVersionDeleted = false;
+ String removeXMLExtension;
+ int currentVersion;
+ String removeVersionExtension;
+ String splitPolicyName = null;
+ String[] split = null;
+ String status = "error";
+ PolicyEntity policyEntity = null;
+ JPAUtils jpaUtils = null;
+
+ papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
+ papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
+ papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
+ papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
+ Connection con = null;
+
+ try {
+ jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
+ response.addHeader("error", "jpautils");
+ response.addHeader("operation", "delete");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ }
+ if (jpaUtils.dbLockdownIgnoreErrors()) {
+ PolicyLogger.warn("Policies are locked down");
+ response.addHeader("operation", "delete");
+ response.addHeader("lockdown", "true");
+ response.setStatus(HttpServletResponse.SC_ACCEPTED);
+ return;
+ }
+ EntityManager em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
+ Query policyEntityQuery = null;
+ try{
+ if(policyName.endsWith(".xml")){
+ removeXMLExtension = policyName.replace(".xml", "");
+ currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1));
+ removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf("."));
+ boolean queryCheck = true;
+ if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
+ if(policyName.contains("Config_")){
+ splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_");
+ }else if(policyName.contains("Action_")){
+ splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_");
+ }else if(policyName.contains("Decision_")){
+ splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_");
+ }
+ split = splitPolicyName.split(":");
+ policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope");
+ }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
+ if(policyName.contains("Config_")){
+ splitPolicyName = policyName.replace(".Config_", ":Config_");
+ }else if(policyName.contains("Action_")){
+ splitPolicyName = policyName.replace(".Action_", ":Action_");
+ }else if(policyName.contains("Decision_")){
+ splitPolicyName = policyName.replace(".Decision_", ":Decision_");
+ }
+ split = splitPolicyName.split(":");
+ queryCheck = false;
+ policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope");
+ }
+
+ if(queryCheck){
+ policyEntityQuery.setParameter("pName", "%"+split[1]+"%");
+ }else{
+ policyEntityQuery.setParameter("pName", split[1]);
+ }
+
+ policyEntityQuery.setParameter("pScope", split[0]);
+ List<?> peResult = policyEntityQuery.getResultList();
+ if(!peResult.isEmpty()){
+ Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
+ getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator));
+ List<?> pvResult = getPolicyVersion.getResultList();
+ PolicyVersion pVersion = (PolicyVersion) pvResult.get(0);
+ int highestVersion = 0;
+ em.getTransaction().begin();
+ Class.forName(papDbDriver);
+ con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
+
+ if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
+ boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
+ if(!groupCheck){
+ for(Object peData : peResult){
+ policyEntity = (PolicyEntity) peData;
+ status = deletePolicyEntityData(em, policyEntity);
+ }
+ }else{
+ status = "PolicyInPDP";
+ }
+ if(status.equals("error")){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }else if(status.equals("PolicyInPDP")){
+ PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ return;
+ }else{
+ try{
+ policyVersionDeleted = true;
+ em.remove(pVersion);
+ }catch(Exception e){
+ policyVersionDeleted = false;
+ }
+ }
+ }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){
+ boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
+ if(!groupCheck){
+ policyEntity = (PolicyEntity) peResult.get(0);
+ status = deletePolicyEntityData(em, policyEntity);
+ }else{
+ status = "PolicyInPDP";
+ }
+
+ if(status.equals("error")){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }else if(status.equals("PolicyInPDP")){
+ PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ return;
+ }else{
+ if(currentVersion > 1){
+ if(!peResult.isEmpty()){
+ for(Object object : peResult){
+ policyEntity = (PolicyEntity) object;
+ String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
+ int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
+ if(policyEntityVersion > highestVersion){
+ highestVersion = policyEntityVersion;
+ }
+ }
+ }
+ pVersion.setActiveVersion(highestVersion);
+ pVersion.setHigherVersion(highestVersion);
+ try{
+ policyVersionDeleted = true;
+ em.persist(pVersion);
+ }catch(Exception e){
+ policyVersionDeleted = false;
+ }
+ }else{
+ try{
+ policyVersionDeleted = true;
+ em.remove(pVersion);
+ }catch(Exception e){
+ policyVersionDeleted = false;
+ }
+ }
+ }
+ }
+ }else{
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ }
+ em.getTransaction().commit();
+ }catch(Exception e){
+ em.getTransaction().rollback();
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
+ response.addHeader("error", "deleteDB");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ } finally {
+ em.close();
+ con.close();
+ }
+
+ if (policyVersionDeleted) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ response.addHeader("operation", "delete");
+ return;
+ } else {
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ }
+
+ public String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity) throws SQLException{
+ PolicyElasticSearchController controller = new PolicyElasticSearchController();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ String policyName = policyEntity.getPolicyName();
+ try{
+ if(policyName.contains("Config_")){
+ em.remove(policyEntity.getConfigurationData());
+ }else if(policyName.contains("Action_")){
+ em.remove(policyEntity.getActionBodyEntity());
+ }
+ String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
+ policyData.setNewFileName(searchPolicyName);
+ controller.deleteElk(policyData);
+ em.remove(policyEntity);
+ }catch(Exception e){
+ return "error";
+ }
+ return "success";
+ }
+
+ public boolean checkPolicyGroupEntity(EntityManager em, Connection con, List<?> peResult) throws SQLException{
+ for(Object peData : peResult){
+ PolicyEntity policyEntity = (PolicyEntity) peData;
+ Statement st = null;
+ ResultSet rs = null;
+ st = con.createStatement();
+ rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'");
+ boolean gEntityList = rs.next();
+ rs.close();
+ if(gEntityList){
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws IOException {
+ String policyName = request.getParameter("policyName");
+ String groupId = request.getParameter("groupId");
+ String responseString = null;
+ // for PUT operations the group may or may not need to exist before the operation can be done
+ EcompPDPGroup group = null;
+ try {
+ group = XACMLPapServlet.getPAPEngine().getGroup(groupId);
+ } catch (PAPException e) {
+ PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e);
+ }
+ if (group == null) {
+ String message = "Unknown groupId '" + groupId + "'";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ response.addHeader("error", "UnknownGroup");
+ response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+ return;
+ } else {
+ loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
+ if (policyName.contains("xml")) {
+ PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue.");
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
+ + "policyName must be the full name of the file to be deleted including version and extension";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
+ + "policyName must be the full name of the file to be deleted including version and extension");
+ response.addHeader("error", message);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
+ RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
+ PDPPolicy policy = group.getPolicy(policyName);
+ if (policy != null) {
+
+ if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
+ if (preSafetyCheck(policy)) {
+ PolicyLogger.debug("Precheck Successful.");
+ }
+ }
+
+ removePolicy.prepareToRemove(policy);
+ EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject();
+ responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
+ PolicyLogger.error(message);
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
+ response.addHeader("error", message);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
+ }
+ if (responseString.equals("success")) {
+ PolicyLogger.info("Policy successfully deleted!");
+ PolicyLogger.audit("Policy successfully deleted!");
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ response.addHeader("operation", "delete");
+ return;
+ } else if (responseString.equals("No Group")) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error", "groupUpdate");
+ response.addHeader("message", message);
+ return;
+ } else if (responseString.equals("DB Error")) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error", "deleteDB");
+ return;
+ } else {
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
+ response.addHeader("error", "unknown");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ }
+
+ private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){
+ PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
+ String response = null;
+ loggingContext.setServiceName("API:PAP.DeleteHandler");
+ EcompPDPGroup existingGroup = null;
+ try {
+ existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId());
+ } catch (PAPException e1) {
+ PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1);
+ }
+ if (group == null || ! (group instanceof StdPDPGroup) || ! (group.getId().equals(existingGroup.getId()))) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingGroup.getId() + " objectFromJSON="+group);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ response = "No Group";
+ return response;
+ }
+ // The Path on the PAP side is not carried on the RESTful interface with the AC
+ // (because it is local to the PAP)
+ // so we need to fill that in before submitting the group for update
+ ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
+ try{
+ acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete");
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
+ +"group="+existingGroup.getId());
+ response = "DB Error";
+ return response;
+ }
+ try {
+ XACMLPapServlet.getPAPEngine().updateGroup(group);
+ } catch (PAPException e) {
+ PolicyLogger.error("Exception occured While Updating PDP Groups"+e);
+ response = "error in updateGroup method";
+ }
+ PolicyLogger.debug("Group '" + group.getId() + "' updated");
+ acPutTransaction.commitTransaction();
+ // Group changed, which might include changing the policies
+ try {
+ newgroup = existingGroup;
+ } catch (Exception e) {
+ PolicyLogger.error("Exception occured in Group Change Method"+e);
+ response = "error in groupChanged method";
+ }
+ if (response==null){
+ response = "success";
+ PolicyLogger.audit("Policy successfully deleted!");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended");
+ return response;
+ }
+
+ public EcompPDPGroup getDeletedGroup(){
+ return newgroup;
+ }
+
+ public boolean preSafetyCheck(PDPPolicy policy) {
+ return true;
+ }
+
+ public static DeleteHandler getInstance() {
+ try {
+ Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName()));
+ DeleteHandler instance = (DeleteHandler) deleteHandler.newInstance();
+ return instance;
+ } catch (Exception e) {
+ PolicyLogger.error(e.getMessage());
+ }
+ return null;
+ }
+
+}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java
new file mode 100644
index 000000000..43342dd65
--- /dev/null
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pap.xacml.rest.handler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+import com.att.research.xacml.util.XACMLProperties;
+
+public interface DictionaryHandler {
+ String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName();
+
+ /*
+ * Get Instance
+ */
+ public static DictionaryHandler getInstance(){
+ try {
+ Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS));
+ DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance();
+ return instance;
+ } catch (Exception e) {
+ PolicyLogger.error(e.getMessage());
+ }
+ return null;
+ }
+
+ /*
+ * Get Equivalent for Dictionary Services.
+ */
+ public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response);
+ /*
+ * Put Equivalent for Dictionary Services.
+ */
+ public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response);
+
+ /**
+ * Can be used to extend the services.
+ *
+ * getflag=true indicates Get Request.
+ * getflag=false indicates Put Request.
+ * @return
+ */
+ public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag);
+}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java
new file mode 100644
index 000000000..8b462bad2
--- /dev/null
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java
@@ -0,0 +1,323 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pap.xacml.rest.handler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+import org.openecomp.policy.pap.xacml.rest.service.DictionaryService;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+public class DictionaryHandlerImpl implements DictionaryHandler{
+ /*
+ * Get Equivalent for Dictionary Services.
+ */
+ public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) {
+ String dictionaryType = request.getParameter("dictionaryType");
+ try {
+ DictionaryService dictionary = new DictionaryService();
+ switch (dictionaryType) {
+ case "EcompName":
+ dictionary.getEcompDictionary(request, response);
+ break;
+ case "Attribute":
+ dictionary.getAttributeDictionary(request, response);
+ break;
+ case "Action":
+ dictionary.getActionPolicyDictionary(request, response);
+ break;
+ case "BRMSParamTemplate":
+ dictionary.getBRMSParamDictionary(request, response);
+ break;
+ case "VSCLAction":
+ dictionary.getVSCLAction(request, response);
+ break;
+ case "VNFType":
+ dictionary.getVnfType(request, response);
+ break;
+ case "PEPOptions":
+ dictionary.getPEPOptions(request, response);
+ break;
+ case "Varbind":
+ dictionary.getVarbind(request, response);
+ break;
+ case "Service":
+ dictionary.getServiceType(request, response);
+ break;
+ case "Site":
+ dictionary.getSiteType(request, response);
+ break;
+ case "Settings":
+ dictionary.getSettingsDictionary(request, response);
+ break;
+ case "DescriptiveScope":
+ dictionary.getDescriptiveDictionary(request, response);
+ break;
+ case "Enforcer":
+ dictionary.getEnforcerDictionary(request, response);
+ break;
+ case "ActionList":
+ dictionary.getActionListDictionary(request, response);
+ break;
+ case "ProtocolList":
+ dictionary.getProtocolListDictionary(request, response);
+ break;
+ case "Zone":
+ dictionary.getZoneDictionary(request, response);
+ break;
+ case "SecurityZone":
+ dictionary.getSecurityZoneDictionary(request, response);
+ break;
+ case "PrefixList":
+ dictionary.getPrefixListDictionary(request, response);
+ break;
+ case "AddressGroup":
+ dictionary.getAddressGroupDictionary(request, response);
+ break;
+ case "ServiceGroup":
+ dictionary.getServiceGroupDictionary(request, response);
+ break;
+ case "ServiceList":
+ dictionary.getServiceListDictionary(request, response);
+ break;
+ case "TermList":
+ case "RuleList":
+ case "FirewallRuleList":
+ case "Term":
+ dictionary.getTermListDictionary(request, response);
+ break;
+ case "MicroServiceLocation":
+ dictionary.getMicroServiceLocationDictionary(request, response);
+ break;
+ case "MicroServiceConfigName":
+ dictionary.getMicroServiceConfigNameDictionary(request, response);
+ break;
+ case "DCAEUUID":
+ dictionary.getDCAEUUIDDictionary(request, response);
+ break;
+ case "MicroServiceModels":
+ dictionary.getMicroServiceModelsDictionary(request, response);
+ break;
+ case "PolicyScopeService":
+ dictionary.getPSServiceDictionary(request, response);
+ break;
+ case "PolicyScopeResource":
+ dictionary.getPSResourceDictionary(request, response);
+ break;
+ case "PolicyScopeType":
+ dictionary.getPSTypeDictionary(request, response);
+ break;
+ case "PolicyScopeClosedLoop":
+ dictionary.getPSClosedLoopDictionary(request, response);
+ break;
+ case "GroupPolicyScopeList":
+ dictionary.getPSGroupScopeDictionary(request, response);
+ break;
+ case "RiskType":
+ dictionary.getRiskTypeDictionary(request, response);
+ break;
+ case "SafePolicyWarning":
+ dictionary.getSafePolicyWarningDictionary(request, response);
+ break;
+ case "MicroServiceDictionary":
+ dictionary.getMicroServiceDictionary(request, response);
+ break;
+ default:
+ extendedOptions(dictionaryType, request, response, true);
+ return;
+ }
+ } catch (Exception e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage();
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database.");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error", "dictionaryDBQuery");
+ response.addHeader("error", message);
+ return;
+ }
+ }
+
+ /**
+ * Can be used to extend the services.
+ *
+ * getflag=true indicates Get Request.
+ * getflag=false indicates Put Request.
+ * @return
+ */
+ public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) {
+ // Default code
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request.";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request.");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.setHeader("error", "dictionary");
+ response.addHeader("error", message);
+ return null;
+ }
+
+ public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) {
+ String result = null;
+ String dictionaryType = request.getParameter("dictionaryType");
+ String operation = request.getParameter("operation");
+ try {
+ DictionaryService dictionary = new DictionaryService();
+ switch (dictionaryType) {
+ case "EcompName":
+ result = dictionary.saveEcompDictionary(request, response);
+ break;
+ case "Attribute":
+ result = dictionary.saveAttributeDictionary(request, response);
+ break;
+ case "Action":
+ result = dictionary.saveActionPolicyDictionary(request, response);
+ break;
+ case "BRMSParamTemplate":
+ result = dictionary.saveBRMSParamDictionary(request, response);
+ break;
+ case "VSCLAction":
+ result = dictionary.saveVSCLAction(request, response);
+ break;
+ case "VNFType":
+ result = dictionary.saveVnfType(request, response);
+ break;
+ case "PEPOptions":
+ result = dictionary.savePEPOptions(request, response);
+ break;
+ case "Varbind":
+ result = dictionary.saveVarbind(request, response);
+ break;
+ case "Service":
+ result = dictionary.saveServiceType(request, response);
+ break;
+ case "Site":
+ result = dictionary.saveSiteType(request, response);
+ break;
+ case "Settings":
+ result = dictionary.saveSettingsDictionary(request, response);
+ break;
+ case "DescriptiveScope":
+ result = dictionary.saveDescriptiveDictionary(request, response);
+ break;
+ case "Enforcer":
+ result = dictionary.saveEnforcerDictionary(request, response);
+ break;
+ case "ActionList":
+ result = dictionary.saveActionListDictionary(request, response);
+ break;
+ case "ProtocolList":
+ result = dictionary.saveProtocolListDictionary(request, response);
+ break;
+ case "Zone":
+ result = dictionary.saveZoneDictionary(request, response);
+ break;
+ case "SecurityZone":
+ result = dictionary.saveSecurityZoneDictionary(request, response);
+ break;
+ case "PrefixList":
+ result = dictionary.savePrefixListDictionary(request, response);
+ break;
+ case "AddressGroup":
+ result = dictionary.saveAddressGroupDictionary(request, response);
+ break;
+ case "ServiceGroup":
+ result = dictionary.saveServiceGroupDictionary(request, response);
+ break;
+ case "ServiceList":
+ result = dictionary.saveServiceListDictionary(request, response);
+ break;
+ case "TermList":
+ case "RuleList":
+ case "FirewallRuleList":
+ case "Term":
+ result = dictionary.saveTermListDictionary(request, response);
+ break;
+ case "MicroServiceLocation":
+ result = dictionary.saveMicroServiceLocationDictionary(request, response);
+ break;
+ case "MicroServiceConfigName":
+ result = dictionary.saveMicroServiceConfigNameDictionary(request, response);
+ break;
+ case "DCAEUUID":
+ result = dictionary.saveDCAEUUIDDictionary(request, response);
+ break;
+ case "MicroServiceModels":
+ result = dictionary.saveMicroServiceModelsDictionary(request, response);
+ break;
+ case "PolicyScopeService":
+ result = dictionary.savePSServiceDictionary(request, response);
+ break;
+ case "PolicyScopeResource":
+ result = dictionary.savePSResourceDictionary(request, response);
+ break;
+ case "PolicyScopeType":
+ result = dictionary.savePSTypeDictionary(request, response);
+ break;
+ case "PolicyScopeClosedLoop":
+ result = dictionary.savePSClosedLoopDictionary(request, response);
+ break;
+ case "GroupPolicyScopeList":
+ result = dictionary.savePSGroupScopeDictionary(request, response);
+ break;
+ case "RiskType":
+ result = dictionary.saveRiskTypeDictionary(request, response);
+ break;
+ case "SafePolicyWarning":
+ result = dictionary.saveSafePolicyWarningDictionary(request, response);
+ break;
+ case "MicroServiceDictionary":
+ result = dictionary.saveMicroServiceDictionary(request, response);
+ break;
+ default:
+ result = extendedOptions(dictionaryType, request, response, false);
+ if(result==null){
+ return;
+ }else{
+ break;
+ }
+ }
+ } catch (Exception e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage();
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database.");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error", message);
+ return;
+ }
+ if (result.equalsIgnoreCase("Success")) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ if (operation.equalsIgnoreCase("update")) {
+ response.addHeader("operation", "updateDictionary");
+ } else {
+ response.addHeader("operation", "createDictionary");
+ }
+ } else if (result.equalsIgnoreCase("Duplicate")) {
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ response.addHeader("error", "dictionaryItemExists");
+ } else if (result.equalsIgnoreCase("DuplicateGroup")) {
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ response.addHeader("error", "duplicateGroup");
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database.";
+ PolicyLogger.error(message);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error", message);
+ }
+ }
+}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java
new file mode 100644
index 000000000..59fa60aec
--- /dev/null
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java
@@ -0,0 +1,210 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pap.xacml.rest.handler;
+
+import java.io.File;
+import java.net.URI;
+import java.net.URL;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Query;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
+import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
+
+import com.att.research.xacml.util.XACMLProperties;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
+public class PushPolicyHandler {
+
+ /*
+ * Get Active Version.
+ */
+ public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) {
+ EntityManager em = null;
+ if(XACMLPapServlet.getEmf()!=null){
+ em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
+ }
+ if (em==null){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit());
+ return;
+ }
+ String policyScope = request.getParameter("policyScope");
+ String filePrefix = request.getParameter("filePrefix");
+ String policyName = request.getParameter("policyName");
+
+ String pvName = policyScope + File.separator + filePrefix + policyName;
+ int activeVersion = 0;
+
+ //Get the Active Version to use in the ID
+ em.getTransaction().begin();
+ Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
+ query.setParameter("pname", pvName);
+
+ @SuppressWarnings("rawtypes")
+ List result = query.getResultList();
+ PolicyVersion versionEntity = null;
+ if (!result.isEmpty()) {
+ versionEntity = (PolicyVersion) result.get(0);
+ em.persist(versionEntity);
+ activeVersion = versionEntity.getActiveVersion();
+ em.getTransaction().commit();
+ } else {
+ PolicyLogger.debug("No PolicyVersion using policyName found");
+ }
+
+ //clean up connection
+ em.close();
+ if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("version", String.valueOf(activeVersion));
+ } else {
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ }
+ }
+
+ /*
+ * Get Git Path
+ */
+ public void getGitPath(HttpServletRequest request, HttpServletResponse response) {
+ String policyScope = request.getParameter("policyScope");
+ String filePrefix = request.getParameter("filePrefix");
+ String policyName = request.getParameter("policyName");
+ String activeVersion = request.getParameter("activeVersion");
+
+ Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
+ Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
+ Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());
+
+ //getting the fullpath of the gitPath and convert to string
+ String fullGitPath = gitPath.toAbsolutePath().toString();
+ String finalGitPath = null;
+
+ //creating the parentPath directory for the Admin Console use
+ if(fullGitPath.contains("\\")){
+ if(fullGitPath.contains("ECOMP-PAP-REST")){
+ finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
+ }else{
+ finalGitPath = fullGitPath.replace("ATT-PAP-REST", "ATT-ecomp-sdk-app");
+ }
+ }else{
+ finalGitPath = fullGitPath.replace("pap", "console");
+ }
+
+ finalGitPath += File.separator + policyScope + File.separator + filePrefix + policyName + "." + activeVersion + ".xml";
+ File file = new File(finalGitPath);
+ URI uri = file.toURI();
+
+ //
+ // Extract XACML policy information
+ //
+ Boolean isValid = false;
+ String policyId = null;
+ String description = null;
+ String version = null;
+
+ URL url;
+ try {
+ url = uri.toURL();
+ Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream());
+ if (rootElement == null ||
+ (
+ ! (rootElement instanceof PolicySetType) &&
+ ! (rootElement instanceof PolicyType)
+ ) ) {
+ PolicyLogger.warn("No root policy element in URI: " + uri.toString() + " : " + rootElement);
+ isValid = false;
+ } else {
+ if (rootElement instanceof PolicySetType) {
+ policyId = ((PolicySetType)rootElement).getPolicySetId();
+ description = ((PolicySetType)rootElement).getDescription();
+ isValid = true;
+ version = ((PolicySetType)rootElement).getVersion();
+ } else if (rootElement instanceof PolicyType) {
+ policyId = ((PolicyType)rootElement).getPolicyId();
+ description = ((PolicyType)rootElement).getDescription();
+ version = ((PolicyType)rootElement).getVersion();
+ isValid = true;
+ } else {
+ PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName());
+ }
+ }
+ } catch (Exception e) {
+ PolicyLogger.error("Exception Occured While Extracting Policy Information");
+ }
+ if (!finalGitPath.equalsIgnoreCase("") || policyId!=null || description!=null || version!=null || isValid!=null) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("gitPath", finalGitPath);
+ response.addHeader("policyId", policyId);
+ response.addHeader("description", description);
+ response.addHeader("version", version);
+ response.addHeader("isValid", isValid.toString());
+ }
+ }
+
+ /*
+ * Get Selected URI path.
+ */
+ public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) {
+ String gitPath = request.getParameter("gitPath");
+ File file = new File(gitPath);
+ PolicyLogger.debug("The fileItem is : " + file.toString());
+ URI selectedURI = file.toURI();
+ String uri = selectedURI.toString();
+ if (!uri.equalsIgnoreCase("")) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("selectedURI", uri);
+ } else {
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ }
+ }
+
+ public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){
+ return true;
+ }
+
+ public boolean preSafetyCheck(EcompPDPGroup policy, String configHome){
+ return true;
+ }
+
+ public static PushPolicyHandler getInstance() {
+ try {
+ Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName()));
+ PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance();
+ return instance;
+ } catch (Exception e) {
+ PolicyLogger.error(e.getMessage());
+ }
+ return null;
+ }
+}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java
new file mode 100644
index 000000000..65402d5c2
--- /dev/null
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java
@@ -0,0 +1,157 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.pap.xacml.rest.handler;
+
+import java.io.IOException;
+import java.util.HashMap;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
+import org.openecomp.policy.pap.xacml.rest.policycontroller.PolicyCreation;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
+import org.xml.sax.SAXException;
+
+import com.att.research.xacml.util.XACMLProperties;
+
+public class SavePolicyHandler {
+ private HashMap<String, String> ErrorHeaders = null;
+
+ public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ String operation = request.getParameter("operation");
+ String policyType = request.getParameter("policyType");
+ String apiflag = request.getParameter("apiflag");
+ PolicyCreation creation = new PolicyCreation();
+ if ( policyType != null ) {
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ if("update".equalsIgnoreCase(operation)){
+ policyAdapter.setEditPolicy(true);
+ }else{
+ policyAdapter.setEditPolicy(false);
+ }
+
+ // get the request content into a String
+ String json = null;
+ // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
+ java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+ PolicyLogger.info("JSON request from API: " + json);
+ // convert Object sent as JSON into local object
+ StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
+ //Set policyAdapter values including parentPath (Common to all policy types)
+ try {
+ policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
+
+ if(!extendedPolicyOptions(policyAdapter, response)){
+ creation.savePolicy(policyAdapter, response);
+ }
+ if ("update".equalsIgnoreCase(operation)) {
+ response.addHeader("operation", "update");
+ } else {
+ response.addHeader("operation", "create");
+ }
+ } catch (Exception e1) {
+ PolicyLogger.error(XACMLErrorConstants.ERROR_UNKNOWN +
+ "Could not set data to policy adapter "+ e1.getMessage());
+ }
+ }
+ }
+
+ private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ policyAdapter.setApiflag(apiflag);
+ /*
+ * set policy adapter values for Building JSON object containing policy data
+ */
+ //Common among policy types
+ policyAdapter.setPolicyName(policy.getPolicyName());
+ policyAdapter.setPolicyDescription(policy.getPolicyDescription());
+ policyAdapter.setEcompName(policy.getEcompName()); //Config Base and Decision Policies
+ policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
+
+ policyAdapter.setPolicyType(policyType);
+ policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes());
+ policyAdapter.setEditPolicy(policy.isEditPolicy());
+ policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf());
+ //Config Specific
+ policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall
+ policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base
+ policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base
+ policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop
+ policyAdapter.setConfigPolicyType(policy.getConfigPolicyType());
+ policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault
+ policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM
+ policyAdapter.setUuid(policy.getUuid()); //Micro Service
+ policyAdapter.setLocation(policy.getMsLocation()); //Micro Service
+ policyAdapter.setPriority(policy.getPriority()); //Micro Service
+ policyAdapter.setPolicyScope(policy.getDomainDir());
+ policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes
+ policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes
+ policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes
+ policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes
+ policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
+ policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies.
+ policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies.
+ //Action Policy Specific
+ policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue
+ policyAdapter.setActionPerformer(policy.getActionPerformer());
+ policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels());
+ policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo());
+ policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1());
+ policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2());
+ //Decision Policy Specific
+ policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
+ policyAdapter.setProviderComboBox(policy.getProviderComboBox());
+ policyAdapter.setDomainDir(policyAdapter.getPolicyScope());
+ policyAdapter.setDomain(policyAdapter.getPolicyScope());
+ return policyAdapter;
+ }
+
+ public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){
+ return false;
+ }
+
+ public void addErrorHeader(String key, String value){
+ if(ErrorHeaders==null){
+ ErrorHeaders= new HashMap<String, String>();
+ }
+ ErrorHeaders.put(key, value);
+ }
+
+ public static SavePolicyHandler getInstance() {
+ try {
+ Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName()));
+ SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance();
+ return instance;
+ } catch (Exception e) {
+ PolicyLogger.error(e.getMessage());
+ }
+ return null;
+ }
+}