diff options
Diffstat (limited to 'ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml')
72 files changed, 3907 insertions, 3597 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java index bde5e5f09..16340e5fe 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +23,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; @@ -32,16 +34,18 @@ import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; + import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDP; @@ -53,6 +57,15 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; public class ConsoleAndApiService { + private static final String SPACE_UNIMPLEMENTED = " UNIMPLEMENTED"; + private static final String XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS = "XACMLPapServlet doACPut commitTransaction"; + private static final String UNIMPLEMENTED = "UNIMPLEMENTED"; + private static final String APPLICATION_JSON = "application/json"; + private static final String CONTENT_TYPE = "content-type"; + private static final String TO_GROUP = ",to group="; + private static final String PDP_ID = "pdpId"; + private static final String XACML_PAP_SERVLET_DO_AC_PUT = "XACMLPapServlet.doACPut"; + private static final String UNKNOWN_GROUP_ID = "Unknown groupId '"; private static final Logger LOGGER = FlexLogger.getLogger(ConsoleAndApiService.class); private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); private static final String ADD_GROUP_ERROR = "addGroupError"; @@ -80,7 +93,7 @@ public class ConsoleAndApiService { */ public void doAcPost(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction doAcPostTransaction = null; + PolicyDbDaoTransaction doAcPostTransaction = null; try { String groupName = request.getParameter("groupName"); String groupDescription = request.getParameter("groupDescription"); @@ -98,9 +111,9 @@ public class ConsoleAndApiService { } catch (UnsupportedEncodingException e) { LOGGER.error(e); } - PolicyDBDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { - newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, + newGroupTransaction.createGroup(PolicyDbDao.createNewPdpGroupId(unescapedName), unescapedName, unescapedDescription, PAPSERVLETDOACPOST); papEngine.newGroup(unescapedName, unescapedDescription); loggingContext.metricStarted(); @@ -134,7 +147,7 @@ public class ConsoleAndApiService { LOGGER.error(e); } if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; // for fixing Header Manipulation of Fortify issue if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -168,7 +181,7 @@ public class ConsoleAndApiService { StdPDPGroup updatedGroup = null; StdPDPPolicy policyForSafetyCheck = new StdPDPPolicy(); for (String policyId : policyIdList) { - PolicyDBDaoTransaction addPolicyToGroupTransaction = + PolicyDbDaoTransaction addPolicyToGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // Copying the policy to the file system and updating groups @@ -224,13 +237,13 @@ public class ConsoleAndApiService { */ // Get new transaction to perform updateGroup() - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // Assume that this is an update of an existing PDP // Group loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); try { - acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut", userId); + acPutTransaction.updateGroup(updatedGroup, XACML_PAP_SERVLET_DO_AC_PUT, userId); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " Error occurred when notifying PAPs of a group change: " + e); @@ -276,8 +289,6 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); auditLogger.info(SUCCESS); LOGGER.info(TRANSENDED); - - return; } else if (request.getParameter("default") != null) { // Args: group=<groupId> default=true <= make default // change the current default group to be the one identified in @@ -289,7 +300,7 @@ public class ConsoleAndApiService { // It should never be the case that multiple groups are // currently marked as the default, but protect against that // anyway. - PolicyDBDaoTransaction setDefaultGroupTransaction = + PolicyDbDaoTransaction setDefaultGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { setDefaultGroupTransaction.changeDefaultGroup(group, PAPSERVLETDOACPOST); @@ -313,20 +324,19 @@ public class ConsoleAndApiService { } auditLogger.info(SUCCESS); LOGGER.info(TRANSENDED); - return; - } else if (request.getParameter("pdpId") != null) { + } else if (request.getParameter(PDP_ID) != null) { doAcPostTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group loggingContext.setServiceName("AC:PAP.movePDP"); - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); OnapPDP pdp = papEngine.getPDP(pdpId); - OnapPDPGroup originalGroup = papEngine.getPDPGroup(pdp); + final OnapPDPGroup originalGroup = papEngine.getPDPGroup(pdp); try { doAcPostTransaction.movePdp(pdp, group, PAPSERVLETDOACPOST); } catch (Exception e) { doAcPostTransaction.rollbackTransaction(); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, - " Error while moving pdp in the database: " + "pdp=" + pdp.getId() + ",to group=" + " Error while moving pdp in the database: " + "pdp=" + pdp.getId() + TO_GROUP + group.getId()); throw new PAPException(e.getMessage()); } @@ -348,14 +358,12 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " AC POST exception"); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } @@ -373,7 +381,7 @@ public class ConsoleAndApiService { OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { try { String parameterDefault = request.getParameter("default"); - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); String pdpGroup = request.getParameter("getPDPGroup"); if ("".equals(groupId)) { // request IS from AC but does not identify a group by name @@ -388,7 +396,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -417,7 +425,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -444,7 +452,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -475,7 +483,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET All groups req"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -496,7 +504,7 @@ public class ConsoleAndApiService { LOGGER.error(e); } if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; // for fixing Header Manipulation of Fortify issue if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -529,7 +537,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -551,13 +559,12 @@ public class ConsoleAndApiService { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " AC Get exception"); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } @@ -573,7 +580,7 @@ public class ConsoleAndApiService { */ public void doAcPut(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { String userId = request.getParameter("userId"); // for PUT operations the group may or may not need to exist before @@ -584,7 +591,7 @@ public class ConsoleAndApiService { // for remaining operations the group must exist before the // operation can be done if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); @@ -605,11 +612,10 @@ public class ConsoleAndApiService { auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); acPutTransaction.rollbackTransaction(); - return; - } else if (request.getParameter("pdpId") != null) { + } else if (request.getParameter(PDP_ID) != null) { // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP // or Update an Existing one - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); if (papEngine.getPDP(pdpId) == null) { loggingContext.setServiceName("AC:PAP.createPDP"); } else { @@ -658,18 +664,18 @@ public class ConsoleAndApiService { // this is a request to create a new PDP object try { acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), - pdp.getDescription(), pdp.getJmxPort(), "XACMLPapServlet.doACPut"); + pdp.getDescription(), pdp.getJmxPort(), XACML_PAP_SERVLET_DO_AC_PUT); papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " Error while adding pdp to group in the database: " + "pdp=" + (pdp.getId()) - + ",to group=" + group.getId()); + + TO_GROUP + group.getId()); throw new PAPException(e.getMessage()); } } else { // this is a request to update the pdp try { - acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut"); + acPutTransaction.updatePdp(pdp, XACML_PAP_SERVLET_DO_AC_PUT); papEngine.updatePDP(pdp); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, @@ -688,15 +694,14 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); acPutTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } else { try { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, XACMLPAPSERVLET, - " Error while adding pdp to group in the database: " + "pdp=null" + ",to group=" + " Error while adding pdp to group in the database: " + "pdp=null" + TO_GROUP + group.getId()); throw new PAPException("PDP is null"); } catch (Exception e) { @@ -708,12 +713,11 @@ public class ConsoleAndApiService { // <= add a PIP to pip config, or replace it if it already // exists (lenient operation) loggingContext.setServiceName("AC:PAP.putPIP"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + UNIMPLEMENTED); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); acPutTransaction.rollbackTransaction(); - return; } else { // Assume that this is an update of an existing PDP Group // ARGS: group=<groupId> <= Update an Existing Group @@ -739,7 +743,7 @@ public class ConsoleAndApiService { } catch (Exception e) { LOGGER.error(e); } - if (objectFromJson == null || !(objectFromJson instanceof StdPDPGroup) + if (!(objectFromJson instanceof StdPDPGroup) || !((StdPDPGroup) objectFromJson).getId().equals(group.getId())) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON=" + objectFromJson); @@ -760,7 +764,7 @@ public class ConsoleAndApiService { if ("delete".equals(((StdPDPGroup) objectFromJson).getOperation())) { acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, "XACMLPapServlet.doDelete", userId); } else { - acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, "XACMLPapServlet.doACPut", userId); + acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, XACML_PAP_SERVLET_DO_AC_PUT, userId); } } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " @@ -786,13 +790,12 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); acPutTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); // Group changed, which might include changing the policies getPapInstance().groupChanged(group, loggingContext); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } } catch (PAPException e) { LOGGER.debug(e); @@ -801,7 +804,6 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } @@ -817,18 +819,18 @@ public class ConsoleAndApiService { */ public void doAcDelete(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // for all DELETE operations the group must exist before the // operation can be done loggingContext.setServiceName("AC:PAP.delete"); OnapPDPGroup group = papEngine.getGroup(groupId); if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'"); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, UNKNOWN_GROUP_ID + groupId + "'"); removePdpOrGroupTransaction.rollbackTransaction(); return; } @@ -838,15 +840,14 @@ public class ConsoleAndApiService { // group=<groupId> policy=<policyId> [delete=<true|false>] <= // delete policy file from group loggingContext.setServiceName("AC:PAP.deletePolicy"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + SPACE_UNIMPLEMENTED); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); removePdpOrGroupTransaction.rollbackTransaction(); - return; - } else if (request.getParameter("pdpId") != null) { + } else if (request.getParameter(PDP_ID) != null) { // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); OnapPDP pdp = papEngine.getPDP(pdpId); removePdpFromGroup(removePdpOrGroupTransaction, pdp, papEngine); // adjust the status of the group, which may have changed when @@ -859,21 +860,19 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); removePdpOrGroupTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } else if (request.getParameter("pipId") != null) { // group=<groupId> pipId=<pipEngineId> <= delete PIP config for // given engine loggingContext.setServiceName("AC:PAP.deletePIPConfig"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + SPACE_UNIMPLEMENTED); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); removePdpOrGroupTransaction.rollbackTransaction(); - return; } else { // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> // <= delete a group and move all its PDPs to the given group @@ -901,11 +900,10 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); removePdpOrGroupTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } } catch (PAPException e) { removePdpOrGroupTransaction.rollbackTransaction(); @@ -913,11 +911,10 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } - private void deleteGroup(PolicyDBDaoTransaction removePdpOrGroupTransaction, OnapPDPGroup group, + private void deleteGroup(PolicyDbDaoTransaction removePdpOrGroupTransaction, OnapPDPGroup group, OnapPDPGroup moveToGroup, PAPPolicyEngine papEngine) throws PAPException { try { removePdpOrGroupTransaction.deleteGroup(group, moveToGroup, "XACMLPapServlet.doACDelete"); @@ -929,7 +926,7 @@ public class ConsoleAndApiService { } } - private void removePdpFromGroup(PolicyDBDaoTransaction removePdpOrGroupTransaction, OnapPDP pdp, + private void removePdpFromGroup(PolicyDbDaoTransaction removePdpOrGroupTransaction, OnapPDP pdp, PAPPolicyEngine papEngine) throws PAPException { try { removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(), "XACMLPapServlet.doACDelete"); @@ -959,6 +956,5 @@ public class ConsoleAndApiService { } catch (IOException e) { LOGGER.error("Error setting Error response Header ", e); } - return; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java index 5615b13cf..f2a31db3c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.XACMLProperties; import com.google.common.base.Joiner; + import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; @@ -32,6 +33,7 @@ import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.TreeSet; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; @@ -60,7 +62,6 @@ public class DataToNotifyPdp { // default constructor. } - private static Properties readPipProperties() throws IOException { if (pipProperties == null) { try (FileInputStream inputStream = new FileInputStream(Paths.get("pip.properties").toString())) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java index ce9cad408..0e1cc521a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -18,11 +18,10 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest; /** - * + * * MessageCodes contains all the valid Dictionary names * */ @@ -37,7 +36,7 @@ public enum DictionaryNames { VSCLAction, ClosedLoopService, ClosedLoopSite, - PEPOptions, + PepOptions, VarbindDictionary, BRMSParamDictionary, BRMSControllerDictionary, @@ -54,4 +53,3 @@ public enum DictionaryNames { TermList, SearchCriteria } - diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java index 2687799cc..920c3dd87 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPStatus; import com.att.research.xacml.util.XACMLProperties; +import com.google.common.annotations.VisibleForTesting; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; @@ -37,12 +38,11 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.restAuth.CheckPDP; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; - /** * Heartbeat thread - periodically check on PDPs' status. * Heartbeat with all known PDPs. @@ -87,9 +87,9 @@ public class Heartbeat implements Runnable { public Heartbeat(PAPPolicyEngine papEngine2) { papEngine = papEngine2; this.heartbeatInterval = - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); this.heartbeatTimeout = - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); } @Override @@ -126,7 +126,8 @@ public class Heartbeat implements Runnable { } } - private void getPdpsFromGroup() { + @VisibleForTesting + protected void getPdpsFromGroup() { try { for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) { for (OnapPDP p : g.getOnapPdps()) { @@ -135,11 +136,12 @@ public class Heartbeat implements Runnable { } } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - "Heartbeat unable to read PDPs from PAPEngine"); + "Heartbeat unable to read PDPs from PAPEngine"); } } - private void notifyEachPdp() { + @VisibleForTesting + protected void notifyEachPdp() { HashMap<String, URL> idToUrlMap = new HashMap<>(); for (OnapPDP pdp : pdps) { // Check for shutdown @@ -162,14 +164,15 @@ public class Heartbeat implements Runnable { } } catch (MalformedURLException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, XACMLPAPSERVLET, - " PDP id '" + fullUrlString + "' is not a valid URL"); + " PDP id '" + fullUrlString + "' is not a valid URL"); } } updatePdpStatus(pdp, openPdpConnection(pdpUrl, pdp)); } } - private String openPdpConnection(URL pdpUrl, OnapPDP pdp) { + @VisibleForTesting + protected String openPdpConnection(URL pdpUrl, OnapPDP pdp) { // Do a GET with type HeartBeat String newStatus = ""; HttpURLConnection connection = null; @@ -188,7 +191,7 @@ public class Heartbeat implements Runnable { // Do the connect connection.connect(); if (connection.getResponseCode() == 204) { - newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); + newStatus = connection.getHeaderField(XacmlRestProperties.PROP_PDP_HTTP_HEADER_HB); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); } @@ -196,25 +199,25 @@ public class Heartbeat implements Runnable { // anything else is an unexpected result newStatus = PDPStatus.Status.UNKNOWN.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " - + connection.getResponseCode() + ": " + pdp.getId()); + + connection.getResponseCode() + ": " + pdp.getId()); } } } catch (UnknownHostException e) { newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' NO_SUCH_HOST"); + HEARTBEATSTRING + pdp.getId() + "' NO_SUCH_HOST"); } catch (SocketTimeoutException e) { newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' connection timeout"); + HEARTBEATSTRING + pdp.getId() + "' connection timeout"); } catch (ConnectException e) { newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' cannot connect"); + HEARTBEATSTRING + pdp.getId() + "' cannot connect"); } catch (Exception e) { newStatus = PDPStatus.Status.UNKNOWN.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' connect exception"); + HEARTBEATSTRING + pdp.getId() + "' connect exception"); } finally { // cleanup the connection if (connection != null) @@ -223,7 +226,8 @@ public class Heartbeat implements Runnable { return newStatus; } - private void updatePdpStatus(OnapPDP pdp, String newStatus) { + @VisibleForTesting + protected void updatePdpStatus(OnapPDP pdp, String newStatus) { if (!pdp.getStatus().getStatus().toString().equals(newStatus)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("previous status='" + pdp.getStatus().getStatus() + "' new Status='" + newStatus + "'"); @@ -232,7 +236,7 @@ public class Heartbeat implements Runnable { getPAPInstance().setPDPSummaryStatus(pdp, newStatus); } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, - "Unable to set state for PDP '" + pdp.getId()); + "Unable to set state for PDP '" + pdp.getId()); } } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java index 9ccccff05..2ca87af28 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java @@ -24,13 +24,15 @@ package org.onap.policy.pap.xacml.rest; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; + import javax.annotation.PostConstruct; import javax.sql.DataSource; + import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.utils.PeCryptoUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -45,9 +47,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc @EnableTransactionManagement -@ComponentScan(basePackages = { "org.onap.*", "com.*" }) +@ComponentScan(basePackages = {"org.onap.*", "com.*"}) public class PAPRestConfig extends WebMvcConfigurerAdapter { - private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class); + private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class); private static String dbDriver = null; private static String dbUrl = null; @@ -55,18 +57,18 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter { private static String dbPassword = null; @PostConstruct - public void init(){ + public void init() { Properties prop = new Properties(); - try(InputStream input = new FileInputStream("xacml.pap.properties")) { + try (InputStream input = new FileInputStream("xacml.pap.properties")) { // load a properties file prop.load(input); setDbDriver(prop.getProperty("javax.persistence.jdbc.driver")); setDbUrl(prop.getProperty("javax.persistence.jdbc.url")); setDbUserName(prop.getProperty("javax.persistence.jdbc.user")); - PeCryptoUtils.initAesKey(prop.getProperty(XACMLRestProperties.PROP_AES_KEY)); + PeCryptoUtils.initAesKey(prop.getProperty(XacmlRestProperties.PROP_AES_KEY)); setDbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password"))); - }catch(Exception e){ - LOGGER.error("Exception Occured while loading properties file"+e); + } catch (Exception e) { + LOGGER.error("Exception Occured while loading properties file" + e); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java index 22f919e4b..1b25c3b9f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -33,19 +34,21 @@ import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.adapters.UpdateObjectData; import org.onap.policy.pap.xacml.rest.components.Policy; import org.onap.policy.pap.xacml.rest.util.JsonMessage; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; @@ -69,9 +72,10 @@ public class UpdateOthersPAPS { private static CommonClassDao commonClassDao; private static final String contentType = "application/json"; - private static String configType =".Config_"; - private static String actionType =".Action_"; - private static String error ="error"; + private static String configType = ".Config_"; + private static String actionType = ".Action_"; + private static String error = "error"; + public static CommonClassDao getCommonClassDao() { return commonClassDao; } @@ -86,11 +90,11 @@ public class UpdateOthersPAPS { } public UpdateOthersPAPS() { - //Empty Constructor + // Empty Constructor } - @RequestMapping(value="/notifyOtherPAPs", method= RequestMethod.POST) - public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response){ + @RequestMapping(value = "/notifyOtherPAPs", method = RequestMethod.POST) + public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); UpdateObjectData body = new UpdateObjectData(); @@ -98,23 +102,23 @@ public class UpdateOthersPAPS { body.setNewPolicyName(request.getParameter("newPolicyName")); body.setOldPolicyName(request.getParameter("oldPolicyName")); - String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url"); - List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class); - if(getPAPUrls != null && !getPAPUrls.isEmpty()){ - for(int i = 0; i < getPAPUrls.size(); i++){ - PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i); - String papUrl = papId.getPolicyDBDaoUrl(); - if(!papUrl.equals(currentPap)){ + String currentPap = XacmlRestProperties.getProperty("xacml.rest.pap.url"); + List<Object> getPAPUrls = commonClassDao.getData(PolicyDbDaoEntity.class); + if (getPAPUrls != null && !getPAPUrls.isEmpty()) { + for (int i = 0; i < getPAPUrls.size(); i++) { + PolicyDbDaoEntity papId = (PolicyDbDaoEntity) getPAPUrls.get(i); + String papUrl = papId.getPolicyDbDaoUrl(); + if (!papUrl.equals(currentPap)) { String userName = papId.getUsername(); String password = papId.getPassword(); Base64.Encoder encoder = Base64.getEncoder(); String txt; try { - PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY)); + PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY)); txt = PeCryptoUtils.decrypt(password); } catch (Exception e) { policyLogger.debug(e); - //if we can't decrypt, might as well try it anyway + // if we can't decrypt, might as well try it anyway txt = password; } String encoding = encoder.encodeToString((userName + ":" + txt).getBytes(StandardCharsets.UTF_8)); @@ -126,33 +130,39 @@ public class UpdateOthersPAPS { HttpEntity<?> requestEntity = new HttpEntity<>(body, headers); HttpClientErrorException exception = null; - try{ - restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, String.class); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); + try { + restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, + String.class); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - if("409 Conflict".equals(e.getMessage())){ + if ("409 Conflict".equals(e.getMessage())) { policyLogger.error(e.getMessage()); response.addHeader(error, e.getMessage()); } } - if(exception != null && exception.getStatusCode()!=null){ + if (exception != null && exception.getStatusCode() != null) { String message; - if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ - message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; + if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { + message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + + "ERROR_AUTH_GET_PERM"; policyLogger.error(message); - }else if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + } else if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); policyLogger.error(message); - }else if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ - message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; + } else if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) { + message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + + exception; policyLogger.error(message); - }else{ - message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + } else { + message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); policyLogger.error(message); } model.put(papUrl, message); - }else{ + } else { model.put(papUrl, "Success"); } } @@ -163,78 +173,80 @@ public class UpdateOthersPAPS { JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); } catch (Exception e) { - policyLogger.error("Exception Occured"+e); + policyLogger.error("Exception Occured" + e); } } } - @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST) + @RequestMapping(value = "/updateConfiguration", method = RequestMethod.POST) @ResponseBody - public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response){ + public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response) { String action = data.getAction(); String newPolicyName = data.getNewPolicyName(); String oldPolicyName = data.getOldPolicyName(); - try{ - if("rename".equals(action)){ - if(oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)){ + try { + if ("rename".equals(action)) { + if (oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)) { File file; - if(oldPolicyName.contains(configType)){ + if (oldPolicyName.contains(configType)) { file = new File(Policy.getConfigHome() + File.separator + oldPolicyName); - }else{ + } else { file = new File(Policy.getActionHome() + File.separator + oldPolicyName); } - if(file.exists()){ + if (file.exists()) { File renamefile; - if(oldPolicyName.contains(configType)){ + if (oldPolicyName.contains(configType)) { renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName); - }else{ + } else { renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName); } - if(file.renameTo(renamefile)){ - policyLogger.info("Policy has been renamed Successfully"+newPolicyName); + if (file.renameTo(renamefile)) { + policyLogger.info("Policy has been renamed Successfully" + newPolicyName); response.addHeader("rename", "Success"); - }else{ + } else { response.addHeader("rename", "Failure"); } } } - }else if("delete".equals(action)){ - if(oldPolicyName.contains(configType)){ + } else if ("delete".equals(action)) { + if (oldPolicyName.contains(configType)) { Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName)); - }else if(oldPolicyName.contains("Action_")){ + } else if (oldPolicyName.contains("Action_")) { Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName)); } - }else if("clonePolicy".equals(action) || "exportPolicy".equals(action)){ - if(newPolicyName.contains(configType)){ - ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName); + } else if ("clonePolicy".equals(action) || "exportPolicy".equals(action)) { + if (newPolicyName.contains(configType)) { + ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao + .getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName); saveConfigurationData(configEntiy, newPolicyName); - }else if(newPolicyName.contains(actionType)){ - ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName); + } else if (newPolicyName.contains(actionType)) { + ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao + .getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName); saveActionBodyData(actionEntiy, newPolicyName); } } } catch (IOException e) { - policyLogger.error("Exception Occured While updating Configuration"+e); + policyLogger.error("Exception Occured While updating Configuration" + e); } } - private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName){ - try(FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)){ + private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName) { + try (FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)) { BufferedWriter bw = new BufferedWriter(fw); bw.write(configEntiy.getConfigBody()); bw.close(); - }catch (IOException e) { - policyLogger.error("Exception Occured While closing the File input stream"+e); + } catch (IOException e) { + policyLogger.error("Exception Occured While closing the File input stream" + e); } } - private void saveActionBodyData(ActionBodyEntity actionEntiy , String newPolicyName){ - try(FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)){ + private void saveActionBodyData(ActionBodyEntity actionEntiy, String newPolicyName) { + try (FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)) { BufferedWriter bw = new BufferedWriter(fw); bw.write(actionEntiy.getActionBody()); bw.close(); - }catch (IOException e) { - policyLogger.error("Exception Occured While closing the File input stream"+e); + } catch (IOException e) { + policyLogger.error("Exception Occured While closing the File input stream" + e); } } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java index c912a8047..e32ae63b1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java @@ -22,12 +22,14 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPStatus; + import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Properties; import java.util.UUID; + import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -49,7 +51,6 @@ public class UpdatePdpThread implements Runnable { private OnapLoggingContext loggingContext; private List<Properties> properties; - public UpdatePdpThread(OnapPDP pdp, List<Properties> properties) { this.pdp = pdp; this.properties = properties; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index 8dc52b861..60450efd7 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +21,14 @@ package org.onap.policy.pap.xacml.rest; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Splitter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -59,15 +68,15 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.components.HandleIncomingNotifications; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler; import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler; import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler; import org.onap.policy.pap.xacml.restAuth.CheckPDP; -import org.onap.policy.rest.XACMLRest; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.XacmlRest; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -80,21 +89,18 @@ import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener; import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.onap.policy.xacml.std.pap.StdPDPStatus; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; /** * Servlet implementation class XacmlPapServlet. */ -@WebServlet(description = "Implements the XACML PAP RESTful API.", urlPatterns = {"/"}, - loadOnStartup = 1, - initParams = {@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", - description = "The location of the properties file holding configuration information.")}) +@WebServlet( + description = "Implements the XACML PAP RESTful API.", + urlPatterns = {"/"}, + loadOnStartup = 1, + initParams = {@WebInitParam( + name = "XACML_PROPERTIES_NAME", + value = "xacml.pap.properties", + description = "The location of the properties file holding configuration information.")}) public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class); @@ -116,8 +122,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom * changed but often read, so the costs of this approach make sense. */ - private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = - new CopyOnWriteArrayList<>(); + private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>(); private static String configHome; private static String actionHome; @@ -129,7 +134,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // The heartbeat thread. private static Heartbeat heartbeat = null; private static Thread heartbeatThread = null; - private static PolicyDBDao policyDbDao; + private static PolicyDbDao policyDbDao; /* * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. */ @@ -181,91 +186,83 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String hostname = InetAddress.getLocalHost().getCanonicalHostName(); baseLoggingContext.setServer(hostname); } catch (UnknownHostException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Unable to get hostname for logging", e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e); } // Initialize - XACMLRest.xacmlInit(config); + XacmlRest.xacmlInit(config); // Load the properties - XACMLRest.loadXacmlProperties(null, null); + XacmlRest.loadXacmlProperties(null, null); /* * Retrieve the property values */ setCommonProperties(); - String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); + String papSiteName = XACMLProperties.getProperty(XacmlRestProperties.PAP_SITE_NAME); if (papSiteName == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papSiteName property entry"); + " ERROR: Bad papSiteName property entry"); throw new PAPException("papSiteName is null"); } - String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE); + String papNodeType = XACMLProperties.getProperty(XacmlRestProperties.PAP_NODE_TYPE); if (papNodeType == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papNodeType property entry"); + " ERROR: Bad papNodeType property entry"); throw new PAPException("papNodeType is null"); } // Integer will throw an exception of anything is missing or // unrecognized - int papTransWait = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - int papTransTimeout = Integer.parseInt( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); - int papAuditTimeout = Integer.parseInt( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)); + int papTransTimeout = + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT)); + int papAuditTimeout = + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT)); // Boolean will default to false if anything is missing or // unrecognized - boolean papAuditFlag = Boolean.parseBoolean( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); - boolean papFileSystemAudit = Boolean.parseBoolean( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); - String papDependencyGroups = - XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); + boolean papAuditFlag = + Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); + boolean papFileSystemAudit = + Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_FLAG)); + String papDependencyGroups = XACMLProperties.getProperty(XacmlRestProperties.PAP_DEPENDENCY_GROUPS); if (papDependencyGroups == null) { throw new PAPException("papDependencyGroups is null"); } setPAPDependencyGroups(papDependencyGroups); // Integer will throw an exception of anything is missing or // unrecognized - int fpMonitorInterval = Integer.parseInt( - XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); - int failedCounterThreshold = Integer.parseInt(XACMLProperties - .getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); - int testTransInterval = Integer.parseInt( - XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); - int writeFpcInterval = Integer.parseInt( - XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); - LOGGER.debug("\n\n\n**************************************" - + "\n*************************************" + "\n" + "\n papDbDriver = " - + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " + papDbUser - + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " - + papTransTimeout + "\n papAuditTimeout = " + papAuditTimeout - + "\n papAuditFlag = " + papAuditFlag + "\n papFileSystemAudit = " - + papFileSystemAudit + "\n papResourceName = " + papResourceName - + "\n fpMonitorInterval = " + fpMonitorInterval - + "\n failedCounterThreshold = " + failedCounterThreshold - + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = " - + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " - + papNodeType + "\n papDependencyGroupsList = " + papDependencyGroups - + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds - + "\n\n*************************************" - + "\n**************************************"); + int fpMonitorInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); + int failedCounterThreshold = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); + int testTransInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); + int writeFpcInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); + LOGGER.debug("\n\n\n**************************************" + "\n*************************************" + + "\n" + "\n papDbDriver = " + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " + + papDbUser + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " + papTransTimeout + + "\n papAuditTimeout = " + papAuditTimeout + "\n papAuditFlag = " + papAuditFlag + + "\n papFileSystemAudit = " + papFileSystemAudit + "\n papResourceName = " + papResourceName + + "\n fpMonitorInterval = " + fpMonitorInterval + "\n failedCounterThreshold = " + + failedCounterThreshold + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = " + + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " + papNodeType + + "\n papDependencyGroupsList = " + papDependencyGroups + "\n papIntegrityAuditPeriodSeconds = " + + papIntegrityAuditPeriodSeconds + "\n\n*************************************" + + "\n**************************************"); // Pull custom persistence settings Properties properties; try { properties = XACMLProperties.getProperties(); - LOGGER.debug("\n\n\n**************************************" - + "\n**************************************" + "\n\n" + "properties = " - + properties + "\n\n**************************************"); + LOGGER.debug("\n\n\n**************************************" + "\n**************************************" + + "\n\n" + "properties = " + properties + "\n\n**************************************"); } catch (IOException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", - " Error loading properties with: " + "XACMLProperties.getProperties()"); + " Error loading properties with: " + "XACMLProperties.getProperties()"); throw new ServletException(e.getMessage(), e.getCause()); } // Create an IntegrityMonitor if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) { properties.setProperty(PERSISTENCE_JDBC_PWD, - PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, ""))); + PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, ""))); } im = IntegrityMonitor.getInstance(papResourceName, properties); // Create an IntegrityAudit @@ -274,26 +271,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // we are about to call the PDPs and give them their configuration. // To do that we need to have the URL of this PAP so we can // construct the Policy file URLs - setPapUrl(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); + setPapUrl(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL)); // Create the policyDBDao setPolicyDbDao(); // Load our PAP engine, first create a factory - ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance( - XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); + ONAPPapEngineFactory factory = ONAPPapEngineFactory + .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); // The factory knows how to go about creating a PAP Engine setPAPEngine(factory.newEngine()); if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) { createDefaultGroupOnInit(); } policyDbDao.setPapEngine(XACMLPapServlet.papEngine); - if (Boolean.parseBoolean( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { + if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { /* * Auditing the local File System groups to be in sync with the Database */ // get an AuditTransaction to lock out all other transactions - PolicyDBDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction(); + PolicyDbDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction(); LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit"); LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString()); @@ -304,8 +300,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (updatedGroup != null) { papEngine.updateGroup(updatedGroup); } - LOGGER.info( - "PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); + LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); // sync up the config data from DB to file system LOGGER.info("PapServlet: Sync config data from DB to file system"); @@ -318,41 +313,37 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Configurable - have the PAP servlet initiate sending the latest // PDP policy/pip configuration // to all its known PDP nodes. - if (Boolean.parseBoolean(XACMLProperties - .getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { + if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { startInitiateThreadService(new Thread(this)); } // After startup, the PAP does Heartbeat's to each of the PDPs // periodically startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine)); } catch (FactoryException | PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Failed to create engine"); - throw new ServletException( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); + throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Failed to create engine - unexpected error"); - throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "PAP not initialized; unexpected error: " + e); + " Failed to create engine - unexpected error"); + throw new ServletException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e); } } private void createDefaultGroupOnInit() { - PolicyDBDaoTransaction addNewGroup = null; + PolicyDbDaoTransaction addNewGroup = null; try { addNewGroup = policyDbDao.getNewTransaction(); OnapPDPGroup group = papEngine.getDefaultGroup(); - addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), - "automaticallyAdded"); + addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded"); addNewGroup.commitTransaction(); addNewGroup = policyDbDao.getNewTransaction(); addNewGroup.changeDefaultGroup(group, "automaticallyAdded"); addNewGroup.commitTransaction(); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", - " Error creating new default group in the database"); + " Error creating new default group in the database"); if (addNewGroup != null) { addNewGroup.rollbackTransaction(); } @@ -364,8 +355,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.start(); } - private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, - Object value) { + @VisibleForTesting + protected static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) { try { mapper.writeValue(response.getOutputStream(), value); } catch (Exception e) { @@ -381,13 +372,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static void setPolicyDbDao() throws ServletException { try { - policyDbDao = PolicyDBDao.getPolicyDBDaoInstance(); + policyDbDao = PolicyDbDao.getPolicyDbDaoInstance(); } catch (Exception e) { throw new ServletException("Unable to Create Policy DBDao Instance", e); } } - public static PolicyDBDao getPolicyDbDao() { + public static PolicyDbDao getPolicyDbDao() { return policyDbDao; } @@ -399,7 +390,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return papUrl; } - private static void setPAPEngine(PAPPolicyEngine newEngine) { + @VisibleForTesting + protected static void setPAPEngine(PAPPolicyEngine newEngine) { XACMLPapServlet.papEngine = newEngine; } @@ -412,22 +404,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); } try { - if (XACMLProperties.getProperty( - XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { - papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties - .getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) - .trim()); + if (XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { + papIntegrityAuditPeriodSeconds = Integer.parseInt( + XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); } } catch (Exception e) { String msg = "integrity_audit_period_seconds "; LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n"); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", - " ERROR: " + msg + "Bad property entry"); + " ERROR: " + msg + "Bad property entry"); throw e; } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", - " ERROR: Bad property entry"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); throw new PAPException(e); } } @@ -435,39 +424,38 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static void setCommonProperties() throws PAPException { setConfigHome(); setActionHome(); - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); + papDbDriver = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_DRIVER); if (papDbDriver == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papDbDriver property entry"); + " ERROR: Bad papDbDriver property entry"); throw new PAPException("papDbDriver is null"); } setPapDbDriver(papDbDriver); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); + papDbUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_URL); if (papDbUrl == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papDbUrl property entry"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); throw new PAPException("papDbUrl is null"); } setPapDbUrl(papDbUrl); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); + papDbUser = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_USER); if (papDbUser == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papDbUser property entry"); + " ERROR: Bad papDbUser property entry"); throw new PAPException("papDbUser is null"); } setPapDbUser(papDbUser); - PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY)); - papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD)); + PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY)); + papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_PASSWORD)); if (papDbPd == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papDbPassword property entry"); + " ERROR: Bad papDbPassword property entry"); throw new PAPException("papDbPassword is null"); } setPapDbPassword(papDbPd); - papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); + papResourceName = XACMLProperties.getProperty(XacmlRestProperties.PAP_RESOURCE_NAME); if (papResourceName == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papResourceName property entry"); + " ERROR: Bad papResourceName property entry"); throw new PAPException("papResourceName is null"); } environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); @@ -477,13 +465,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName"); setMsPolicyName(msPolicyName); // PDPId File location - XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE); if (XACMLPapServlet.pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE - + " The PDP Id Authentication File Property is not valid: " - + XACMLRestProperties.PROP_PDP_IDFILE); - throw new PAPException("The PDP Id Authentication File Property :" - + XACMLRestProperties.PROP_PDP_IDFILE + " is not Valid. "); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " + + XacmlRestProperties.PROP_PDP_IDFILE); + throw new PAPException( + "The PDP Id Authentication File Property :" + XacmlRestProperties.PROP_PDP_IDFILE + " is not Valid. "); } } @@ -517,8 +504,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList XACMLPapServlet.heartbeatThread.join(); } catch (InterruptedException e) { XACMLPapServlet.heartbeatThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Error stopping heartbeat"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); } } if (initiateThread != null) { @@ -527,10 +513,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.join(); } catch (InterruptedException e) { initiateThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Error stopping thread"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); } } + // reset pap url + setPapUrl(null); } private ConsoleAndApiService getAcServiceInstance() { @@ -545,21 +532,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + throws ServletException, IOException { + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPost", "PAP.post"); - PolicyDBDaoTransaction pdpTransaction = null; + PolicyDbDaoTransaction pdpTransaction = null; try { loggingContext.metricStarted(); im.startTransaction(); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); } catch (AdministrativeStateException ae) { - String message = "POST interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() + "\n Exception Message: " - + PolicyUtils.CATCH_EXCEPTION; + String message = + "POST interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION; LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); @@ -568,13 +553,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (IntegrityMonitorException ime) { - String message = "POST interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + ime.getMessage(); + String message = + "POST interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage(); LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); @@ -585,7 +567,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } try { loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); + XacmlRest.dumpRequest(request); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest"); // since getParameter reads the content string, explicitly get the @@ -611,8 +593,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } loggingContext.metricStarted(); - getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost doACPost"); loggingContext.transactionEnded(); @@ -635,23 +616,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (CheckPDP.validateID(id)) { pdpTransaction = policyDbDao.getNewTransaction(); try { - pdpTransaction.addPdpToGroup(id, - XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, - "Registered on first startup", Integer.parseInt(jmxport), - "PDP autoregister"); - XACMLPapServlet.papEngine.newPDP(id, - XACMLPapServlet.papEngine.getDefaultGroup(), id, - "Registered on first startup", Integer.parseInt(jmxport)); - } catch (NullPointerException | PAPException | IllegalArgumentException - | IllegalStateException | PersistenceException | PolicyDBException e) { + pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, + "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); + XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, + "Registered on first startup", Integer.parseInt(jmxport)); + } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException + | PersistenceException | PolicyDbException e) { pdpTransaction.rollbackTransaction(); String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - " " + message); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); im.endTransaction(); return; } @@ -669,8 +645,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); im.endTransaction(); return; } @@ -679,7 +654,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, - "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration."); + "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration."); PolicyLogger.audit("Transaction Failed - See Error.log"); im.endTransaction(); return; @@ -691,7 +666,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction"); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - "Could not commit transaction to put pdp in the database"); + "Could not commit transaction to put pdp in the database"); } } if (jmxport != null && !"".equals(jmxport)) { @@ -709,12 +684,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.error(e); } if (group == null) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW - + " PDP not associated with any group, even the default"); + PolicyLogger + .error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, - "PDP not associated with any group, even the default"); + "PDP not associated with any group, even the default"); im.endTransaction(); return; } @@ -783,8 +758,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); im.endTransaction(); return; } @@ -809,12 +783,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + throws ServletException, IOException { + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doGet", "PAP.get"); loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); + XacmlRest.dumpRequest(request); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest"); String pathInfo = request.getRequestURI(); @@ -835,13 +808,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction"); } catch (IntegrityMonitorException ime) { - String message = "GET interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + ime.getMessage(); + String message = + "GET interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage(); LOGGER.info(message, ime); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -868,7 +838,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } else { String message = - "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -883,8 +853,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricStarted(); - getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); } catch (IOException e) { @@ -908,8 +877,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Is it known? if (pdp == null) { // Check if request came from localhost - if ("localhost".equals(request.getRemoteHost()) - || request.getRemoteHost().equals(request.getLocalAddr())) { + if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) { // Return status information - basically all the groups loggingContext.setServiceName("PAP.getGroups"); Set<OnapPDPGroup> groups = null; @@ -917,12 +885,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { LOGGER.debug(e); - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", - " GET exception"); + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); im.endTransaction(); return; } @@ -935,8 +901,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.endTransaction(); return; } - String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " - + request.getLocalAddr(); + String message = + "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -983,15 +949,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } try { - LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " - + "Policy Name : " + policy.getName() + "\n Policy URI: " - + policy.getLocation().toString()); + LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : " + + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); } catch (PAPException | IOException e) { LOGGER.error(e); } - try (InputStream is = new FileInputStream( - ((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); - OutputStream os = response.getOutputStream()) { + try ( + InputStream is = + new FileInputStream(((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); + OutputStream os = response.getOutputStream()) { // Send the policy back IOUtils.copy(is, os); response.setStatus(HttpServletResponse.SC_OK); @@ -1016,9 +982,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + throws ServletException, IOException { + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPut", "PAP.put"); try { loggingContext.metricStarted(); @@ -1026,13 +991,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction"); } catch (IntegrityMonitorException e) { - String message = "PUT interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + e.getMessage(); + String message = + "PUT interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + e.getMessage(); LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1046,7 +1008,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String apiflag = request.getParameter("apiflag"); // For Debug purposes if (!"api".equals(apiflag) && PolicyLogger.isDebugEnabled()) { - XACMLRest.dumpRequest(request); + XacmlRest.dumpRequest(request); PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest"); } loggingContext.metricEnded(); @@ -1067,11 +1029,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } loggingContext.metricStarted(); LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); - HandleIncomingNotifications handleIncomingNotifications = - new HandleIncomingNotifications(); + HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications(); handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl, - policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, - policyDBDaoRequestExtraData, this); + policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); response.setStatus(200); @@ -1099,7 +1059,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } else { String message = - "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -1137,7 +1097,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (apiflag != null) { if (!authorizeRequest(request)) { String message = - "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -1159,8 +1119,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricEnded(); - getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet goPut doACPut"); } catch (IOException e) { @@ -1217,12 +1176,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // We do not expect anything from anywhere else. // This method is here in case we ever need to support other operations. - LOGGER.error( - XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, - "Request does not have groupId or apiflag"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See error.log"); im.endTransaction(); @@ -1233,9 +1190,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + throws ServletException, IOException { + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doDelete", "PAP.delete"); try { loggingContext.metricStarted(); @@ -1243,13 +1199,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction"); } catch (IntegrityMonitorException ime) { - String message = "DELETE interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + ime.getMessage(); + String message = + "DELETE interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage(); LOGGER.info(message, ime); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1258,7 +1211,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } loggingContext.metricStarted(); - XACMLRest.dumpRequest(request); + XacmlRest.dumpRequest(request); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest"); String groupId = request.getParameter(GROUPID); @@ -1268,7 +1221,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (apiflag != null) { if (!authorizeRequest(request)) { String message = - "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -1292,8 +1245,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricStarted(); - getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete"); } catch (IOException e) { @@ -1308,20 +1260,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, - "Request does not have groupId"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); im.endTransaction(); } - private boolean isPDPCurrent(Properties policies, Properties pipconfig, - Properties pdpProperties) { + private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - String localReferencedPolicies = - policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); if (localRootPolicies == null || localReferencedPolicies == null) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE - + "Missing property on PAP server: RootPolicies=" + localRootPolicies - + " ReferencedPolicies=" + localReferencedPolicies); + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies=" + + localRootPolicies + " ReferencedPolicies=" + localReferencedPolicies); return false; } // Compare the policies and pipconfig properties to the pdpProperties @@ -1331,9 +1279,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) - && localReferencedPolicies.equals( - pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) - && pdpPipConfig.equals(pipconfig)) { + && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) + && pdpPipConfig.equals(pipconfig)) { // The PDP is current return true; } @@ -1344,13 +1291,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // property. // Either of these cases means that the PDP is not up-to-date, so // just drop-through to return false. - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", - " PDP Error"); + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); } return false; } - private void populatePolicyURL(StringBuffer urlPath, Properties policies) { + @VisibleForTesting + protected void populatePolicyURL(StringBuffer urlPath, Properties policies) { String lists[] = new String[2]; lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); @@ -1366,7 +1313,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } protected String getPDPID(HttpServletRequest request) { - String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID); + String pdpURL = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID); if (pdpURL == null || pdpURL.isEmpty()) { // Should send back its port for identification LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header"); @@ -1376,11 +1323,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } protected String getPDPJMX(HttpServletRequest request) { - String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT); + String pdpJMMX = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT); if (pdpJMMX == null || pdpJMMX.isEmpty()) { // Should send back its port for identification LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE - + "PDP did not send custom header for JMX Port so the value of 0 is assigned"); + + "PDP did not send custom header for JMX Port so the value of 0 is assigned"); return null; } return pdpJMMX; @@ -1396,9 +1343,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, - String groupId, OnapLoggingContext loggingContext) throws IOException { - PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction(); + public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, + OnapLoggingContext loggingContext) throws IOException { + PolicyDbDaoTransaction acPutTransaction = policyDbDao.getNewTransaction(); PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI"); try { String userId = request.getParameter("userId"); @@ -1424,7 +1371,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.info("Removing old version of the policy"); for (PDPPolicy existingPolicy : group.getPolicies()) { if (existingPolicy.getName().equals(policy.getName()) - && !existingPolicy.getId().equals(policy.getId())) { + && !existingPolicy.getId().equals(policy.getId())) { group.removePolicy(existingPolicy); LOGGER.info("Removing policy: " + existingPolicy); break; @@ -1437,7 +1384,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut", userId); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - " Error while updating group in the database: " + "group=" + group.getId()); + " Error while updating group in the database: " + "group=" + group.getId()); throw new PAPException(e.getMessage()); } @@ -1470,8 +1417,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); LOGGER.info("Success"); - if (policy != null && ((policy.getId().contains("Config_MS_")) - || (policy.getId().contains("BRMS_Param")))) { + if (policy != null + && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); if (pushPolicyHandler.preSafetyCheck(policy, configHome)) { LOGGER.debug("Precheck Successful."); @@ -1482,14 +1429,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } catch (PAPException e) { acPutTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - " API PUT exception"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); String message = XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Exception in request to update group from API - See Error.log on on the PAP."; - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + + "Exception in request to update group from API - See Error.log on on the PAP."; + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", message); @@ -1531,10 +1476,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " getPDPGroups failed"); - throw new IllegalAccessError( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); } for (OnapPDPGroup group : groups) { groupChanged(group); @@ -1547,10 +1490,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " getPDPGroups failed"); - throw new IllegalAccessError( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); } for (OnapPDPGroup group : groups) { groupChanged(group, loggingContext); @@ -1604,8 +1545,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, - List<Properties> pdpDataByGroup) { + private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> pdpDataByGroup) { Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup)); if (CheckPDP.validateID(pdp.getId())) { t.start(); @@ -1622,8 +1562,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return dataToNotify.setPolicyConfigProperties(pdp, papEngine); } - private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) - throws IOException { + private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) throws IOException { LOGGER.info("Test request received"); try { im.evaluateSanity(); @@ -1634,8 +1573,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.audit("Transaction Failed - See Error.log"); response.setStatus(HttpServletResponse.SC_OK); return; - } catch (ForwardProgressException | AdministrativeStateException - | StandbyStatusException e) { + } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) { String submsg; if (e instanceof ForwardProgressException) { submsg = " is not making forward progress."; @@ -1645,8 +1583,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList submsg = " Standby Status is NOT PROVIDING SERVICE."; } - String message = "GET:/pap/test called and PAP " + papResourceName + submsg - + " Exception Message: " + e.getMessage(); + String message = + "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: " + e.getMessage(); LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1660,8 +1598,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (eMsg == null) { eMsg = "No Exception Message"; } - String message = "GET:/pap/test called and PAP " + papResourceName - + " has had a subsystem failure." + " Exception Message: " + eMsg; + String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." + + " Exception Message: " + eMsg; LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1686,18 +1624,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, - String serviceName) { + private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, String serviceName) { loggingContext.transactionStarted(); loggingContext.setServiceName(serviceName); if (loggingContext.getRequestId() == null || "".equals(loggingContext.getRequestId())) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestId(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapServlet ('" + methodType - + "') so we generated one"); + PolicyLogger + .info("requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one"); } else { - PolicyLogger.info( - "requestID was provided in call to XACMLPapServlet ('" + methodType + "')"); + PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')"); } } @@ -1712,14 +1648,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static void loadWebapps() throws PAPException { if (actionHome == null || configHome == null) { - Path webappsPath = - Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS)); // Sanity Check if (webappsPath == null) { - PolicyLogger.error("Invalid Webapps Path Location property : " - + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new PAPException("Invalid Webapps Path Location property : " - + XACMLRestProperties.PROP_PAP_WEBAPPS); + PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException( + "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config"); Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action"); @@ -1728,17 +1662,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Files.createDirectories(webappsPathConfig); } catch (IOException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - "Failed to create config directory: " - + webappsPathConfig.toAbsolutePath().toString()); + "Failed to create config directory: " + webappsPathConfig.toAbsolutePath().toString()); } } if (Files.notExists(webappsPathAction)) { try { Files.createDirectories(webappsPathAction); } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Failed to create action directory: " - + webappsPathAction.toAbsolutePath().toString(), e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: " + + webappsPathAction.toAbsolutePath().toString(), e); } } actionHome = webappsPathAction.toString(); @@ -1790,7 +1722,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return papEngine; } - public static PolicyDBDaoTransaction getDbDaoTransaction() { + public static PolicyDbDaoTransaction getDbDaoTransaction() { return policyDbDao.getNewTransaction(); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java index 45c46cb5b..be13c542a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; public class SearchData { @@ -31,70 +32,92 @@ public class SearchData { private String vproAction; private String serviceType; private String bindTextSearch; + public String getQuery() { return query; } + public void setQuery(String query) { this.query = query; } + public String getPolicyType() { return policyType; } + public void setPolicyType(String policyType) { this.policyType = policyType; } + public String getDescriptiveScope() { return descriptiveScope; } + public void setDescriptiveScope(String descriptiveScope) { this.descriptiveScope = descriptiveScope; } + public String getClosedLooppolicyType() { return closedLooppolicyType; } + public void setClosedLooppolicyType(String closedLooppolicyType) { this.closedLooppolicyType = closedLooppolicyType; } + public String getOnapName() { return onapName; } + public void setOnapName(String onapName) { this.onapName = onapName; } + public String getD2Service() { return d2Service; } + public void setD2Service(String d2Service) { this.d2Service = d2Service; } + public String getVnfType() { return vnfType; } + public void setVnfType(String vnfType) { this.vnfType = vnfType; } + public String getPolicyStatus() { return policyStatus; } + public void setPolicyStatus(String policyStatus) { this.policyStatus = policyStatus; } + public String getVproAction() { return vproAction; } + public void setVproAction(String vproAction) { this.vproAction = vproAction; } + public String getServiceType() { return serviceType; } + public void setServiceType(String serviceType) { this.serviceType = serviceType; } + public String getBindTextSearch() { return bindTextSearch; } + public void setBindTextSearch(String bindTextSearch) { this.bindTextSearch = bindTextSearch; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java index aa59868fe..ead403a02 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; public class UpdateObjectData { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java index 780ed86c7..c4076b2ad 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -32,6 +33,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; @@ -47,6 +49,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -82,7 +85,6 @@ public class ActionPolicy extends Policy { List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); - private CommonClassDao commonClassDao; private static boolean isAttribute = false; @@ -360,7 +362,6 @@ public class ActionPolicy extends Policy { return obligations; } - // if compound setting the inner apply here protected ApplyType getInnerActionApply(String value1Label) { ApplyType actionApply = new ApplyType(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java index 8ca4dfa01..233add1ad 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,16 +35,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -56,6 +49,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class ClosedLoopPolicy extends Policy { private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class); @@ -68,7 +68,7 @@ public class ClosedLoopPolicy extends Policy { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { if (policyName.endsWith(".xml")) { @@ -76,7 +76,7 @@ public class ClosedLoopPolicy extends Policy { } try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) { String body = jsonBody; - //Remove the trapMaxAge in Verification Signature + // Remove the trapMaxAge in Verification Signature body = body.replace(",\"trapMaxAge\":null", ""); this.policyAdapter.setJsonBody(body); out.println(body); @@ -85,7 +85,7 @@ public class ClosedLoopPolicy extends Policy { } } - //Utility to read json data from the existing file to a string + // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); @@ -93,7 +93,7 @@ public class ClosedLoopPolicy extends Policy { } - //create the configuration file based on the policy name on adding the extension as .json + // create the configuration file based on the policy name on adding the extension as .json private String getConfigFile(String filename) { filename = FilenameUtils.removeExtension(filename); if (filename.endsWith(".xml")) { @@ -124,13 +124,13 @@ public class ClosedLoopPolicy extends Policy { return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override public boolean prepareToSave() throws PAPException { if (isPreparedToSave()) { - //we have already done this + // we have already done this return true; } @@ -176,17 +176,13 @@ public class ClosedLoopPolicy extends Policy { // Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -340,7 +336,7 @@ public class ClosedLoopPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment5); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("RiskType"); assignment6.setCategory(CATEGORY_RESOURCE); @@ -389,7 +385,6 @@ public class ClosedLoopPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment9); - advices.getAdviceExpression().add(advice); return advices; } @@ -399,5 +394,4 @@ public class ClosedLoopPolicy extends Policy { return policyAdapter.getPolicyData(); } - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java index d6b09086a..1cab7166a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modified Copyright (C) 2019 Bell Canada. * ================================================================================ @@ -22,6 +22,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -33,17 +36,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.utils.PolicyUtils; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -58,6 +50,14 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.utils.PolicyUtils; + public class ConfigPolicy extends Policy { /** @@ -93,7 +93,6 @@ public class ConfigPolicy extends Policy { } } - // Here we are adding the extension for the configurations file based on the // config type selection for saving. private String getConfigFile(String filename) { @@ -103,8 +102,7 @@ public class ConfigPolicy extends Policy { if (id == null) { return filename; } - switch (id.toUpperCase()) - { + switch (id.toUpperCase()) { case JSON_CONFIG: return filename + ".json"; case XML_CONFIG: @@ -127,7 +125,6 @@ public class ConfigPolicy extends Policy { return filename; } - // Validations for Config form /* * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object... @@ -181,7 +178,7 @@ public class ConfigPolicy extends Policy { } if (!isPreparedToSave()) { - //Prep and configure the policy for saving + // Prep and configure the policy for saving prepareToSave(); } @@ -192,8 +189,8 @@ public class ConfigPolicy extends Policy { return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override public boolean prepareToSave() throws PAPException { @@ -441,7 +438,7 @@ public class ConfigPolicy extends Policy { } } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java index 9809ad498..2151a1988 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import java.util.HashMap; @@ -26,7 +27,7 @@ import java.util.Map; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PolicyUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -34,26 +35,28 @@ import org.springframework.stereotype.Service; @Service public class CreateBRMSRuleTemplate { - private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); private static CommonClassDao commonClassDao; @Autowired - public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){ + public CreateBRMSRuleTemplate(CommonClassDao commonClassDao) { CreateBRMSRuleTemplate.commonClassDao = commonClassDao; } - public CreateBRMSRuleTemplate() {} + public CreateBRMSRuleTemplate() { + } public Map<String, String> addRule(String rule, String ruleName, String description, String userID) { - Map<String,String> responseMap = new HashMap<>(); - if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class); - if(duplicateData!=null && !duplicateData.isEmpty()){ + Map<String, String> responseMap = new HashMap<>(); + if (rule != null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")) { + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BrmsParamTemplate.class); + if (duplicateData != null && !duplicateData.isEmpty()) { LOGGER.error("Import new service failed. Service already exists"); responseMap.put("DBError", "EXISTS"); return responseMap; - }else{ - BRMSParamTemplate brmsParamTemplate = new BRMSParamTemplate(); + } else { + BrmsParamTemplate brmsParamTemplate = new BrmsParamTemplate(); brmsParamTemplate.setDescription(description); brmsParamTemplate.setRuleName(ruleName); brmsParamTemplate.setRule(rule); @@ -63,7 +66,7 @@ public class CreateBRMSRuleTemplate { LOGGER.info("Template created with " + ruleName + " by " + userID); } responseMap.put("success", "success"); - }else{ + } else { LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template"); responseMap.put("error", "VALIDATION"); } @@ -73,8 +76,8 @@ public class CreateBRMSRuleTemplate { public static boolean validateRuleParams(String rule) { CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(); Map<String, String> paramValues = policy.findType(rule); - for(String key : paramValues.keySet()) { - if(!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))){ + for (String key : paramValues.keySet()) { + if (!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))) { return false; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java index 6a0c92650..ffb902bc4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,6 +20,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -38,22 +41,7 @@ import java.util.Map.Entry; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.script.SimpleBindings; - -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.BRMSParamTemplate; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -67,6 +55,15 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.BrmsParamTemplate; public class CreateBrmsParamPolicy extends Policy { @@ -91,19 +88,18 @@ public class CreateBrmsParamPolicy extends Policy { copyMap.put("policyVersion", policyAdapter.getHighestVersion().toString()); copyMap.put("unique", ("p" + policyName + UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", "")); - //Finding all the keys in the Map data-structure. + // Finding all the keys in the Map data-structure. Iterator<String> iterator = copyMap.keySet().iterator(); Pattern p; Matcher m; while (iterator.hasNext()) { - //Converting the first character of the key into a lower case. + // Converting the first character of the key into a lower case. String input = iterator.next(); - String output = Character.toLowerCase(input.charAt(0)) + - (input.length() > 1 ? input.substring(1) : ""); - //Searching for a pattern in the String using the key. + String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : ""); + // Searching for a pattern in the String using the key. p = Pattern.compile("\\$\\{" + output + "\\}"); m = p.matcher(ruleContents); - //Replacing the value with the inputs provided by the user in the editor. + // Replacing the value with the inputs provided by the user in the editor. String finalInput = copyMap.get(input); if (finalInput.contains("$")) { finalInput = finalInput.replace("$", "\\$"); @@ -113,7 +109,6 @@ public class CreateBrmsParamPolicy extends Policy { return ruleContents; } - // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); @@ -133,11 +128,10 @@ public class CreateBrmsParamPolicy extends Policy { out.close(); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", - "Exception saving configuration file"); + "Exception saving configuration file"); } } - // Here we are adding the extension for the configurations file based on the // config type selection for saving. private String getConfigFile(String filename) { @@ -151,6 +145,7 @@ public class CreateBrmsParamPolicy extends Policy { } // Validations for Config form + @Override public boolean validateConfigForm() { // Validating mandatory Fields. @@ -187,12 +182,12 @@ public class CreateBrmsParamPolicy extends Policy { private String getValueFromDictionary(String templateName) { String ruleTemplate = null; CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - String queryString = "from BRMSParamTemplate where param_template_name= :templateName"; + String queryString = "from BrmsParamTemplate where param_template_name= :templateName"; SimpleBindings params = new SimpleBindings(); params.put("templateName", templateName); List<Object> result = dbConnection.getDataByQuery(queryString, params); if (!result.isEmpty()) { - BRMSParamTemplate template = (BRMSParamTemplate) result.get(0); + BrmsParamTemplate template = (BrmsParamTemplate) result.get(0); ruleTemplate = template.getRule(); } return ruleTemplate; @@ -222,8 +217,7 @@ public class CreateBrmsParamPolicy extends Policy { if (line.contains("*/")) { try { comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace("*/", ""); + line = line.split("\\/\\*")[0] + line.split("\\*\\/")[1].replace("*/", ""); } catch (Exception e) { LOGGER.debug(e); line = line.split("\\/\\*")[0]; @@ -255,8 +249,8 @@ public class CreateBrmsParamPolicy extends Policy { break; } } - String param = params.toString().replace("declare Params", "").replace("end", "") - .replaceAll("\\s+", ""); + String param = + params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""); String[] components = param.split(":"); String caption = ""; for (int i = 0; i < components.length; i++) { @@ -274,7 +268,7 @@ public class CreateBrmsParamPolicy extends Policy { LOGGER.debug(e); nextComponent = components[i]; } - //If the type is of type String then we add the UI Item and type to the map. + // If the type is of type String then we add the UI Item and type to the map. if (nextComponent.startsWith("String")) { type = "String"; mapFieldType.put(caption, type); @@ -287,7 +281,7 @@ public class CreateBrmsParamPolicy extends Policy { } } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", - "Exception parsing file in findType"); + "Exception parsing file in findType"); } } return mapFieldType; @@ -330,10 +324,8 @@ public class CreateBrmsParamPolicy extends Policy { StringBuilder body = new StringBuilder(); try { - body.append( - "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " + - "purpose. \n\t " + - "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); + body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " + + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); body.append("<%$Values="); for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) { String uiKey = entry.getKey(); @@ -344,8 +336,8 @@ public class CreateBrmsParamPolicy extends Policy { body.append("$%> \n*/ \n"); body.append(valueFromDictionary + "\n"); } catch (Exception e) { - PolicyLogger - .error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", + "Exception saving policy"); } saveConfigurations(policyName, body.toString()); @@ -366,12 +358,10 @@ public class CreateBrmsParamPolicy extends Policy { String fileName = policyAdapter.getNewFileName(); String name = fileName.substring(fileName.lastIndexOf("\\") + 1); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1 - ); + name = fileName.substring(fileName.lastIndexOf("/") + 1); } allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); // Match for ONAPName @@ -415,12 +405,11 @@ public class CreateBrmsParamPolicy extends Policy { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", - "Exception creating ACCESS URI"); + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -438,7 +427,7 @@ public class CreateBrmsParamPolicy extends Policy { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", - "Exception creating Config URI"); + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -459,24 +448,21 @@ public class CreateBrmsParamPolicy extends Policy { rule.setTarget(targetInRule); rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(configPolicy); } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); } setPreparedToSave(true); return true; } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { + @VisibleForTesting + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - //Policy Config ID Assignment + // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("BRMSPARAMID"); @@ -489,8 +475,7 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue = new AttributeValueType(); configNameAttributeValue.setDataType(STRING_DATATYPE); configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. @@ -505,8 +490,7 @@ public class CreateBrmsParamPolicy extends Policy { String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); attributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue)); + assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); // Policy Name Assignment @@ -518,15 +502,12 @@ public class CreateBrmsParamPolicy extends Policy { attributeValue3.setDataType(STRING_DATATYPE); fileName = FilenameUtils.removeExtension(fileName); fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1 - ); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1 - ); + name = fileName.substring(fileName.lastIndexOf("/") + 1); } attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); // Version Number Assignment @@ -537,8 +518,7 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue4 = new AttributeValueType(); configNameAttributeValue4.setDataType(STRING_DATATYPE); configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); // Onap Name Assignment @@ -549,12 +529,10 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue5 = new AttributeValueType(); configNameAttributeValue5.setDataType(STRING_DATATYPE); configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -564,16 +542,15 @@ public class CreateBrmsParamPolicy extends Policy { configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. + // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:" + policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()) - .getController())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("controller:" + policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } - // Adding Dependencies. + // Adding Dependencies. if (policyAdapter.getBrmsDependency() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); ArrayList<String> dependencies = new ArrayList<>(); @@ -582,18 +559,18 @@ public class CreateBrmsParamPolicy extends Policy { dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); key.append(dependencyName + ","); } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } - // Dynamic Field Config Attributes. + // Dynamic Field Config Attributes. Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Entry<String, String> map : dynamicFieldConfigAttributes.entrySet()) { advice.getAttributeAssignmentExpression() - .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); + .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java index efa28b2bb..bb46fd6a9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; import java.io.File; import java.io.IOException; @@ -34,15 +36,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -57,6 +50,11 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; public class CreateBrmsRawPolicy extends Policy { @@ -76,8 +74,7 @@ public class CreateBrmsRawPolicy extends Policy { protected void saveConfigurations(String policyName, String jsonBody) { if (policyName.endsWith(".xml")) { - policyName = policyName.substring(0, - policyName.lastIndexOf(".xml")); + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); } try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) { out.println(jsonBody); @@ -195,7 +192,6 @@ public class CreateBrmsRawPolicy extends Policy { } allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); // Match for ONAPName @@ -243,8 +239,7 @@ public class CreateBrmsRawPolicy extends Policy { } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -267,8 +262,7 @@ public class CreateBrmsRawPolicy extends Policy { configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl( - configURI).stringValue()); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); configMatch.setAttributeDesignator(configAttributeDesignator); configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -284,22 +278,18 @@ public class CreateBrmsRawPolicy extends Policy { rule.setTarget(targetInRule); rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(configPolicy); } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); } setPreparedToSave(true); return true; } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); @@ -314,8 +304,7 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue = new AttributeValueType(); configNameAttributeValue.setDataType(STRING_DATATYPE); configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. @@ -330,8 +319,7 @@ public class CreateBrmsRawPolicy extends Policy { String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(AttributeValue)); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); // Policy Name Assignment @@ -350,8 +338,7 @@ public class CreateBrmsRawPolicy extends Policy { } System.out.println(name); attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); // Version Number Assignment @@ -362,8 +349,7 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue4 = new AttributeValueType(); configNameAttributeValue4.setDataType(STRING_DATATYPE); configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); // Onap Name Assignment @@ -374,12 +360,10 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue5 = new AttributeValueType(); configNameAttributeValue5.setDataType(STRING_DATATYPE); configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -390,16 +374,15 @@ public class CreateBrmsRawPolicy extends Policy { assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. + // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:" + policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()) - .getController())); + advice.getAttributeAssignmentExpression().add(createResponseAttributes( + "controller:" + policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } - // Adding Dependencies. + // Adding Dependencies. if (policyAdapter.getBrmsDependency() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); ArrayList<String> dependencies = new ArrayList<>(); @@ -408,11 +391,11 @@ public class CreateBrmsRawPolicy extends Policy { dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); key.append(dependencyName).append(","); } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } - // Dynamic Field Config Attributes. + // Dynamic Field Config Attributes. Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) { String keyField = entry.getKey(); @@ -420,7 +403,7 @@ public class CreateBrmsRawPolicy extends Policy { .add(createResponseAttributes("key:" + keyField, entry.getValue())); } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java index e74cc3359..a980e70d8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; import java.io.File; import java.io.PrintWriter; @@ -30,16 +32,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -54,40 +46,47 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class CreateClosedLoopPerformanceMetrics extends Policy { - private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); public CreateClosedLoopPerformanceMetrics() { super(); } - public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){ + public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, final String jsonBody) { - if(policyName.endsWith(".xml")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); - } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json")){ + if (policyName.endsWith(".xml")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); + } + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "." + policyName + ".json")) { out.println(jsonBody); policyAdapter.setJsonBody(jsonBody); policyAdapter.setConfigBodyData(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } } - //getting the policy name and setting to configuration on adding .json + // getting the policy name and setting to configuration on adding .json private String getConfigFile(String filename) { filename = FilenameUtils.removeExtension(filename); if (filename.endsWith(".xml")) { filename = filename.substring(0, filename.length() - 4); } - filename = filename +".json"; + filename = filename + ".json"; return filename; } @@ -95,13 +94,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -109,18 +108,18 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -148,7 +147,6 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -167,17 +165,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); // Match for ServiceType allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType())); @@ -210,7 +204,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -229,7 +224,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -286,7 +282,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { AttributeValueType AttributeValue = new AttributeValueType(); AttributeValue.setDataType(URI_DATATYPE); - String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName); + String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); @@ -344,7 +340,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { advice.getAttributeAssignmentExpression().add(assignment6); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("RiskType"); assignment7.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index 103928cbc..e18628dff 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -36,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -46,17 +49,16 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; +import org.onap.policy.rest.util.MsModelUtils.ModelType; public class CreateNewMicroServiceModel { private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class); private MicroServiceModels newModel = null; - private HashMap<String, MSAttributeObject> classMap = new HashMap<>(); - + private HashMap<String, MsAttributeObject> classMap = new HashMap<>(); - private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + private MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { super(); @@ -82,7 +84,7 @@ public class CreateNewMicroServiceModel { this.newModel.setUserCreatedBy(userInfo); String cleanUpFile = null; - Map<String, MSAttributeObject> tempMap = new HashMap<>(); + Map<String, MsAttributeObject> tempMap = new HashMap<>(); // Need to delete the file if (importFile.contains(".zip")) { extractFolder(randomID + ".zip"); @@ -98,7 +100,7 @@ public class CreateNewMicroServiceModel { cleanUpFile = "ExtractDir" + File.separator + randomID + ".yml"; } else { - tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", MODEL_TYPE.XMI); + tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", ModelType.XMI); classMap.putAll(tempMap); cleanUpFile = "ExtractDir" + File.separator + randomID + ".xmi"; } @@ -109,7 +111,7 @@ public class CreateNewMicroServiceModel { } private void processFiles(String modelName, List<File> fileList) { - Map<String, MSAttributeObject> tempMap; + Map<String, MsAttributeObject> tempMap; for (File file : fileList) { if (file.isFile()) { int indx = file.getName().lastIndexOf('.'); @@ -121,7 +123,7 @@ public class CreateNewMicroServiceModel { } else { - tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); + tempMap = utils.processEpackage(file.getAbsolutePath(), ModelType.XMI); classMap.putAll(tempMap); } } @@ -145,10 +147,9 @@ public class CreateNewMicroServiceModel { try { - utils.parseTosca(fileName); - MSAttributeObject msAttributes = new MSAttributeObject(); + MsAttributeObject msAttributes = new MsAttributeObject(); msAttributes.setClassName(modelName); LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); @@ -164,7 +165,7 @@ public class CreateNewMicroServiceModel { returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if (!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())) { + if (!PolicyDbDao.isNullOrEmpty(utils.getListConstraints())) { LinkedHashMap<String, String> enumList = new LinkedHashMap<>(); String[] listArray = utils.getListConstraints().split("#"); for (String str : listArray) { @@ -255,7 +256,7 @@ public class CreateNewMicroServiceModel { public Map<String, String> addValuesToNewModel(String type) { Map<String, String> successMap = new HashMap<>(); - MSAttributeObject mainClass = null; + MsAttributeObject mainClass = null; List<String> dependency = null; String subAttribute = null; @@ -269,13 +270,12 @@ public class CreateNewMicroServiceModel { } mainClass = classMap.get(this.newModel.getModelName()); - if (".yml".equalsIgnoreCase(type)) { newModel.setDependency("[]"); if (mainClass.getSubClass() != null) { String value = new Gson().toJson(mainClass.getSubClass()); - newModel.setSub_attributes(value); + newModel.setSubAttributes(value); } if (mainClass.getAttribute() != null) { @@ -289,7 +289,7 @@ public class CreateNewMicroServiceModel { String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); int equalsIndex = refAttributes.indexOf("="); String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1); - this.newModel.setRef_attributes(refAttributesAfterFirstEquals); + this.newModel.setRefAttributes(refAttributesAfterFirstEquals); } if (mainClass.getEnumType() != null) { @@ -317,7 +317,7 @@ public class CreateNewMicroServiceModel { dependency = utils.getFullDependencyList(dependency, classMap); if (!dependency.isEmpty()) { for (String element : dependency) { - MSAttributeObject temp = new MSAttributeObject(); + MsAttributeObject temp = new MsAttributeObject(); if (classMap.containsKey(element)) { temp = classMap.get(element); mainClass.addAllRefAttribute(temp.getRefAttribute()); @@ -328,14 +328,14 @@ public class CreateNewMicroServiceModel { } subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - this.newModel.setSub_attributes(subAttribute); + this.newModel.setSubAttributes(subAttribute); if (mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()) { this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); } if (mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()) { this.newModel - .setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + .setRefAttributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); } if (mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()) { @@ -368,8 +368,8 @@ public class CreateNewMicroServiceModel { model.setDependency(this.newModel.getDependency()); model.setDescription(this.newModel.getDescription()); model.setEnumValues(this.newModel.getEnumValues()); - model.setRef_attributes(this.newModel.getRef_attributes()); - model.setSub_attributes(this.newModel.getSub_attributes()); + model.setRefAttributes(this.newModel.getRefAttributes()); + model.setSubAttributes(this.newModel.getSubAttributes()); model.setDataOrderInfo(this.newModel.getDataOrderInfo()); model.setDecisionModel(this.newModel.isDecisionModel()); model.setRuleFormation(this.newModel.getRuleFormation()); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java index 87c9f9108..8c63a2766 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -43,28 +45,26 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; - -import com.google.gson.Gson; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; +import org.onap.policy.rest.util.MsModelUtils.ModelType; public class CreateNewOptimizationModel { private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class); private OptimizationModels newModel = null; - private HashMap<String,MSAttributeObject > classMap = new HashMap<>(); + private HashMap<String, MsAttributeObject> classMap = new HashMap<>(); private static final String EXTRACTDIR = "ExtractDir"; private static final String SUCCESS = "success"; - - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewOptimizationModel() { super(); } - public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) { + public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, + String randomID) { this.newModel = new OptimizationModels(); this.newModel.setVersion(version); @@ -75,15 +75,15 @@ public class CreateNewOptimizationModel { this.newModel.setUserCreatedBy(userInfo); String cleanUpFile = null; - Map<String, MSAttributeObject> tempMap = new HashMap<>(); - //Need to delete the file - if (importFile.contains(".zip")){ + Map<String, MsAttributeObject> tempMap = new HashMap<>(); + // Need to delete the file + if (importFile.contains(".zip")) { extractFolder(randomID + ".zip"); File directory = new File(EXTRACTDIR + File.separator + randomID); List<File> fileList = listModelFiles(directory.toString()); - //get all the files from a director - for (File file : fileList){ - if (file.isFile()){ + // get all the files from a director + for (File file : fileList) { + if (file.isFile()) { processYmlModel(file.toString(), modelName); } } @@ -96,32 +96,32 @@ public class CreateNewOptimizationModel { } catch (IOException e) { logger.error("Failed to unzip model file " + randomID, e); } - }else { - if(importFile.contains(".yml")){ + } else { + if (importFile.contains(".yml")) { - processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName); - cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml"; + processYmlModel(EXTRACTDIR + File.separator + randomID + ".yml", modelName); + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".yml"; - }else{ - tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI); + } else { + tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID + ".xmi", ModelType.XMI); classMap.putAll(tempMap); - cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi"; + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".xmi"; } File deleteFile = new File(cleanUpFile); deleteFile.delete(); } } - private void processYmlModel(String fileName, String modelName){ + private void processYmlModel(String fileName, String modelName) { try { utils.parseTosca(fileName); - MSAttributeObject msAttributes= new MSAttributeObject(); + MsAttributeObject msAttributes = new MsAttributeObject(); msAttributes.setClassName(modelName); - LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>(); + LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); returnAttributeList.put(modelName, utils.getAttributeString()); msAttributes.setAttribute(returnAttributeList); @@ -129,24 +129,24 @@ public class CreateNewOptimizationModel { msAttributes.setMatchingSet(utils.getMatchableValues()); - LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>(); + LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>(); returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if(!"".equals(utils.getListConstraints())){ - LinkedHashMap<String, String> enumList =new LinkedHashMap<>(); - String[] listArray=utils.getListConstraints().split("#"); - for(String str:listArray){ - String[] strArr= str.split("="); - if(strArr.length>1){ + if (!"".equals(utils.getListConstraints())) { + LinkedHashMap<String, String> enumList = new LinkedHashMap<>(); + String[] listArray = utils.getListConstraints().split("#"); + for (String str : listArray) { + String[] strArr = str.split("="); + if (strArr.length > 1) { enumList.put(strArr[0], strArr[1]); } } msAttributes.setEnumType(enumList); } - classMap=new LinkedHashMap<>(); + classMap = new LinkedHashMap<>(); classMap.put(modelName, msAttributes); } catch (Exception e) { @@ -174,13 +174,13 @@ public class CreateNewOptimizationModel { int buffer = 2048; File file = new File(zipFile); - try(ZipFile zip = new ZipFile(EXTRACTDIR + File.separator +file);){ - String newPath = zipFile.substring(0, zipFile.length() - 4); + try (ZipFile zip = new ZipFile(EXTRACTDIR + File.separator + file);) { + String newPath = zipFile.substring(0, zipFile.length() - 4); new File(newPath).mkdir(); Enumeration zipFileEntries = zip.entries(); // Process each entry - while (zipFileEntries.hasMoreElements()){ + while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); @@ -189,13 +189,13 @@ public class CreateNewOptimizationModel { destinationParent.mkdirs(); - if (!entry.isDirectory()){ + if (!entry.isDirectory()) { int currentByte; byte[] data = new byte[buffer]; - try(FileOutputStream fos = new FileOutputStream(destFile); + try (FileOutputStream fos = new FileOutputStream(destFile); BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); - BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { + BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { while ((currentByte = is.read(data, 0, buffer)) != -1) { dest.write(data, 0, currentByte); @@ -204,7 +204,7 @@ public class CreateNewOptimizationModel { } } - if (currentEntry.endsWith(".zip")){ + if (currentEntry.endsWith(".zip")) { extractFolder(destFile.getAbsolutePath()); } } @@ -216,40 +216,42 @@ public class CreateNewOptimizationModel { public Map<String, String> addValuesToNewModel() { Map<String, String> successMap = new HashMap<>(); - MSAttributeObject mainClass; + MsAttributeObject mainClass; - if (!classMap.containsKey(this.newModel.getModelName())){ - logger.error("Model Provided does not contain the service name provided in request. Unable to import new model"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request"); + if (!classMap.containsKey(this.newModel.getModelName())) { + logger.error( + "Model Provided does not contain the service name provided in request. Unable to import new model"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", + "Unable to pull out required values, file missing service name provided in request"); successMap.put("error", "MISSING"); return successMap; } mainClass = classMap.get(this.newModel.getModelName()); newModel.setDependency("[]"); - if(mainClass.getSubClass() != null){ - String value = new Gson().toJson(mainClass.getSubClass()); - newModel.setSubattributes(value); + if (mainClass.getSubClass() != null) { + String value = new Gson().toJson(mainClass.getSubClass()); + newModel.setSubattributes(value); } - if(mainClass.getAttribute() != null){ - String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf('='); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + if (mainClass.getAttribute() != null) { + String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes = attributes.indexOf('='); + String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1); this.newModel.setAttributes(atttributesAfterFirstEquals); } - if(mainClass.getRefAttribute() != null){ - String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf('='); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + if (mainClass.getRefAttribute() != null) { + String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex = refAttributes.indexOf('='); + String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1); this.newModel.setRefattributes(refAttributesAfterFirstEquals); } - if(mainClass.getEnumType() != null){ + if (mainClass.getEnumType() != null) { this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); } - if(mainClass.getMatchingSet() != null){ + if (mainClass.getMatchingSet() != null) { this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); } @@ -258,14 +260,15 @@ public class CreateNewOptimizationModel { } - public Map<String, String> saveImportService(){ + public Map<String, String> saveImportService() { String modelName = this.newModel.getModelName(); String importedBy = "API"; String version = this.newModel.getVersion(); Map<String, String> successMap = new HashMap<>(); CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version); - if(result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + version); + if (result.isEmpty()) { OptimizationModels model = new OptimizationModels(); model.setModelName(modelName); model.setVersion(version); @@ -283,7 +286,7 @@ public class CreateNewOptimizationModel { model.setUserCreatedBy(userInfo); dbConnection.save(model); successMap.put(SUCCESS, SUCCESS); - }else{ + } else { successMap.put("DBError", "EXISTS"); logger.error("Import new service failed. Service already exists"); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java index da5c6aea1..ed1d551b4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.XACML3; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.std.IdentifierImpl; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -40,6 +41,25 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + import org.apache.commons.lang3.StringEscapeUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -63,25 +83,6 @@ import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine; import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; - @Component public class DecisionPolicy extends Policy { @@ -103,7 +104,6 @@ public class DecisionPolicy extends Policy { private static final String POLICY_NAME = "PolicyName"; private static final String DESCRIPTION = "description"; - List<String> dynamicLabelRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>(); @@ -154,16 +154,15 @@ public class DecisionPolicy extends Policy { private void readRawPolicyData() { Object policy; if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) { - policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils - .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); + policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream( + StringEscapeUtils.unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); } else { policy = XACMLPolicyScanner.readPolicy( new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8))); } String policyRawDesc; if (policy instanceof PolicySetType) { - policyRawDesc = - ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; + policyRawDesc = ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; ((PolicySetType) policy).setDescription(policyRawDesc); } else { policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; @@ -204,13 +203,13 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || - policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) || - policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){ + if (policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) + || policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)) { Map<String, String> yamlParams = new HashMap<>(); - String blackListEntryType = policyAdapter.getBlackListEntryType() != null - ? policyAdapter.getBlackListEntryType() : "Use Manual Entry"; + String blackListEntryType = + policyAdapter.getBlackListEntryType() != null ? policyAdapter.getBlackListEntryType() + : "Use Manual Entry"; String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription() : "YAML Guard Policy"; yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@"); @@ -428,8 +427,7 @@ public class DecisionPolicy extends Policy { yamlSpecs.put("guardActiveStart", constraints.getActive_time_range().get("start")); yamlSpecs.put("guardActiveEnd", constraints.getActive_time_range().get("end")); String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs, - constraints.getBlacklist(), - guard.getMatch_parameters().getTargets()); + constraints.getBlacklist(), guard.getMatch_parameters().getTargets()); // Convert the Policy into Stream input to Policy Adapter. Object policy = XACMLPolicyScanner @@ -713,7 +711,8 @@ public class DecisionPolicy extends Policy { if (!attributeId.startsWith("S_")) { ApplyType innerDecisionApply = generateApplyTypeDataType(functionKey); AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey); - AttributeValueType decisionConditionAttributeValue = generateAttributeValueTypeDataType(functionKey); + AttributeValueType decisionConditionAttributeValue = + generateAttributeValueTypeDataType(functionKey); if (attributeId != null) { attributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -793,7 +792,6 @@ public class DecisionPolicy extends Policy { dataTypeList.add(dataType); } - private String getDataType(String key) { DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key); @@ -826,8 +824,7 @@ public class DecisionPolicy extends Policy { private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) { AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": attributeDesignator.setDataType(INTEGER_DATATYPE); break; @@ -839,8 +836,7 @@ public class DecisionPolicy extends Policy { private ApplyType generateApplyTypeDataType(String functionKey) { ApplyType applyType = new ApplyType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); break; @@ -852,8 +848,7 @@ public class DecisionPolicy extends Policy { private AttributeValueType generateAttributeValueTypeDataType(String functionKey) { AttributeValueType applyType = new AttributeValueType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": applyType.setDataType(INTEGER_DATATYPE); break; @@ -864,8 +859,10 @@ public class DecisionPolicy extends Policy { } private void applyTwoTextFieldRuleAttribute(ApplyType decisionApply, String value1, String functionKey) { - decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); - decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); + decisionApply.getExpression() + .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); + decisionApply.getExpression() + .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); } private ApplyType generateApplyTypeDataType(String value1, String functionKey) { @@ -874,10 +871,8 @@ public class DecisionPolicy extends Policy { attributeDesignator.setCategory(CATEGORY_RESOURCE); // Here set actual field values - attributeDesignator - .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); - innerApply.getExpression() - .add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); + attributeDesignator.setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); + innerApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); return innerApply; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java index eca473f41..e153ea834 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java @@ -26,6 +26,7 @@ import com.att.research.xacml.std.IdentifierImpl; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonpatch.diff.JsonDiff; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -41,11 +42,27 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.script.SimpleBindings; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -66,19 +83,6 @@ import org.onap.policy.rest.jpa.TermList; import org.onap.policy.rest.jpa.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Component public class FirewallConfigPolicy extends Policy { @@ -114,11 +118,11 @@ public class FirewallConfigPolicy extends Policy { LOGGER.debug("Configuration is succesfully saved"); } } catch (IOException e) { - LOGGER.error("Save of configuration to file" +fileName+ "failed",e); + LOGGER.error("Save of configuration to file" + fileName + "failed", e); } } - //Utility to read json data from the existing file to a string + // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); @@ -127,11 +131,11 @@ public class FirewallConfigPolicy extends Policy { @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ + if (!isPreparedToSave()) { prepareToSave(); } @@ -139,9 +143,10 @@ public class FirewallConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); Boolean dbIsUpdated = false; - if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){ + if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())) { if (policyAdapter.isEditPolicy()) { - dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); + dbIsUpdated = + updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); } else { try { dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody()); @@ -153,14 +158,14 @@ public class FirewallConfigPolicy extends Policy { dbIsUpdated = true; } - if(dbIsUpdated) { - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + if (dbIsUpdated) { + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); } else { PolicyLogger.error("Failed to Update the Database Dictionary Tables."); - //remove the new json file + // remove the new json file String jsonBody = policyAdapter.getPrevJsonBody(); - if (jsonBody!=null){ + if (jsonBody != null) { saveConfigurations(policyName, jsonBody); } else { saveConfigurations(policyName, ""); @@ -171,13 +176,13 @@ public class FirewallConfigPolicy extends Policy { return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -196,13 +201,13 @@ public class FirewallConfigPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - //String oldPolicyName = policyName.replace(".xml", ""); + // String oldPolicyName = policyName.replace(".xml", ""); String scope = policyName.substring(0, policyName.indexOf('.')); - String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", ""); + String dbPolicyName = policyName.substring(policyName.indexOf('.') + 1).replace(".xml", ""); - int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1)); - dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1); - if(oldversion > 1){ + int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.') + 1)); + dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.') + 1); + if (oldversion > 1) { oldversion = oldversion - 1; dbPolicyName = dbPolicyName + oldversion + ".xml"; } @@ -277,7 +282,8 @@ public class FirewallConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -298,7 +304,8 @@ public class FirewallConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -332,7 +339,7 @@ public class FirewallConfigPolicy extends Policy { // Data required for Advice part is setting here. private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - //Firewall Config ID Assignment + // Firewall Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("firewallConfigID"); @@ -349,7 +356,7 @@ public class FirewallConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. - //URL ID Assignment + // URL ID Assignment AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); assignment2.setAttributeId("URLID"); assignment2.setCategory(CATEGORY_RESOURCE); @@ -365,7 +372,7 @@ public class FirewallConfigPolicy extends Policy { assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - //Policy Name Assignment + // Policy Name Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); assignment3.setCategory(CATEGORY_RESOURCE); @@ -382,7 +389,7 @@ public class FirewallConfigPolicy extends Policy { assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - //Version Number Assignment + // Version Number Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); assignment4.setCategory(CATEGORY_RESOURCE); @@ -393,7 +400,7 @@ public class FirewallConfigPolicy extends Policy { assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); - //Onap Name Assignment + // Onap Name Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ONAPID); assignment5.setCategory(CATEGORY_RESOURCE); @@ -403,7 +410,7 @@ public class FirewallConfigPolicy extends Policy { assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -414,7 +421,7 @@ public class FirewallConfigPolicy extends Policy { assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("RiskType"); assignment7.setCategory(CATEGORY_RESOURCE); @@ -466,19 +473,18 @@ public class FirewallConfigPolicy extends Policy { return advices; } - - private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { + private Boolean insertFirewallDicionaryData(String jsonBody) throws SQLException { CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject json = null; if (jsonBody != null) { - //Read jsonBody to JsonObject + // Read jsonBody to JsonObject json = stringToJson(jsonBody); JsonArray firewallRules = null; JsonArray serviceGroup = null; JsonArray addressGroup = null; - //insert data into tables + // insert data into tables try { firewallRules = json.getJsonArray("firewallRuleList"); serviceGroup = json.getJsonArray("serviceGroups"); @@ -487,28 +493,28 @@ public class FirewallConfigPolicy extends Policy { * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ if (firewallRules != null) { - for(int i = 0;i<firewallRules.size();i++) { + for (int i = 0; i < firewallRules.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(i); - //get values from JSON fields of firewallRulesList Array + // get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString(); String action = ruleListobj.get("action").toString(); String description = ruleListobj.get("description").toString(); List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { TermList termEntry = (TermList) result.get(0); dbConnection.delete(termEntry); } - //getting fromZone Array field from the firewallRulesList + // getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) { + for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); if (fromZoneString != null) { @@ -517,12 +523,12 @@ public class FirewallConfigPolicy extends Policy { fromZoneString = value; } } - String fromZoneInsert = "'"+fromZoneString+"'"; + String fromZoneInsert = "'" + fromZoneString + "'"; - //getting toZone Array field from the firewallRulesList + // getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) { + for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); if (toZoneString != null) { @@ -531,19 +537,19 @@ public class FirewallConfigPolicy extends Policy { toZoneString = value; } } - String toZoneInsert = "'"+toZoneString+"'"; + String toZoneInsert = "'" + toZoneString + "'"; - //getting sourceList Array fields from the firewallRulesList + // getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; - for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) { + for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = srcListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = srcListObj.get("value").toString(); @@ -552,19 +558,19 @@ public class FirewallConfigPolicy extends Policy { srcListString = getLeftOrRight(srcListString, value); } - String srcListInsert = "'"+srcListString+"'"; + String srcListInsert = "'" + srcListString + "'"; - //getting destinationList Array fields from the firewallRulesList + // getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; - for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) { + for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destListObj.get("value").toString(); @@ -572,19 +578,20 @@ public class FirewallConfigPolicy extends Policy { destListString = getLeftOrRight(destListString, value); } - String destListInsert = "'"+destListString+"'"; + String destListInsert = "'" + destListString + "'"; - //getting destServices Array fields from the firewallRulesList + // getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; - for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { + for (int destPortListIndex = 0; destPortListIndex < destServicesArray + .size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destServicesObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destServicesObj.get("value").toString(); @@ -592,7 +599,7 @@ public class FirewallConfigPolicy extends Policy { destPortListString = getLeftOrRight(destPortListString, value); } - String destPortListInsert = "'"+destPortListString+"'"; + String destPortListInsert = "'" + destPortListString + "'"; /* * Create Queries to INSERT data into database tables and execute @@ -603,16 +610,16 @@ public class FirewallConfigPolicy extends Policy { TermList termEntry = new TermList(); termEntry.setTermName(ruleName); - termEntry.setSrcIPList(srcListInsert); - termEntry.setDestIPList(destListInsert); + termEntry.setSrcIpList(srcListInsert); + termEntry.setDestIpList(destListInsert); termEntry.setProtocolList("null"); termEntry.setPortList("null"); termEntry.setSrcPortList("null"); termEntry.setDestPortList(destPortListInsert); termEntry.setAction(action); termEntry.setDescription(description); - termEntry.setFromZones(fromZoneInsert); - termEntry.setToZones(toZoneInsert); + termEntry.setFromZone(fromZoneInsert); + termEntry.setToZone(toZoneInsert); termEntry.setUserCreatedBy(userInfo); dbConnection.save(termEntry); @@ -624,35 +631,35 @@ public class FirewallConfigPolicy extends Policy { * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables */ if (serviceGroup != null) { - for(int i = 0; i < serviceGroup.size() ; i++) { + for (int i = 0; i < serviceGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(i); String serviceListName = svcGroupListobj.get("name").toString(); String description = null; - if (svcGroupListobj.containsKey("description")){ + if (svcGroupListobj.containsKey("description")) { description = svcGroupListobj.get("description").toString(); } - //getting members Array from the serviceGroup + // getting members Array from the serviceGroup JsonArray membersArray = svcGroupListobj.getJsonArray("members"); - //String type = svcGroupListobj.get("type").toString(); + // String type = svcGroupListobj.get("type").toString(); Boolean isServiceGroup = false; - if (membersArray!=null){ + if (membersArray != null) { String membersType = membersArray.getJsonObject(0).get("type").toString(); if (membersType.contains("REFERENCE")) { isServiceGroup = true; } } - //Insert values into GROUPSERVICELIST table if name begins with Group + // Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray); - } else { //Insert JSON data serviceList table, protollist table, and portlist table + } else { // Insert JSON data serviceList table, protollist table, and portlist table String type = svcGroupListobj.get("type").toString(); String transportProtocol = svcGroupListobj.get("transportProtocol").toString(); String ports = svcGroupListobj.get("ports").toString(); @@ -660,7 +667,8 @@ public class FirewallConfigPolicy extends Policy { /* * Create Queries to INSERT data into database table and execute */ - saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports); + saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, + ports); saveProtocolListToDb(dbConnection, transportProtocol); @@ -673,19 +681,19 @@ public class FirewallConfigPolicy extends Policy { * Inserting addressGroup data into the ADDRESSGROUP table */ if (addressGroup != null) { - for(int i = 0; i < addressGroup.size(); i++) { + for (int i = 0; i < addressGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(i); - //create JSON array for members + // create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString(); String description = null; - if (addressGroupObj.containsKey("description")){ + if (addressGroupObj.containsKey("description")) { description = addressGroupObj.get("description").toString(); } @@ -693,13 +701,11 @@ public class FirewallConfigPolicy extends Policy { String type = null; for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); - //String value = membersObj.get("value").toString(); type = membersObj.get("type").toString().replace("\"", ""); - String value = null; prefixIP = getName(prefixIP, membersObj, type); } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'" + prefixIP + "'"; Boolean isAddressGroup = type.contains("REFERENCE"); @@ -711,8 +717,9 @@ public class FirewallConfigPolicy extends Policy { } } removeDuplicateValuesFromLookup(dbConnection); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", + "Exception getting Json values"); return false; } return true; @@ -731,33 +738,34 @@ public class FirewallConfigPolicy extends Policy { + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; dbConnection.updateQuery(protoDelete); - //PortList Table + // PortList Table String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; dbConnection.updateQuery(portListDelete); - //PrefixList Table + // PrefixList Table String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; dbConnection.updateQuery(prefixListDelete); - //GroupServiceList + // GroupServiceList String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + "groupservicelist.serviceList = g1.serviceList; "; dbConnection.updateQuery(groupServiceDelete); } - private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) { + private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, + JsonArray membersArray) { String name = null; - for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) { + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); String type = membersObj.get("type").toString().replace("\"", ""); name = getName(name, membersObj, type); } - String nameInsert = "'"+name+"'"; + String nameInsert = "'" + name + "'"; GroupServiceList groupServiceEntry = new GroupServiceList(); groupServiceEntry.setGroupName(serviceListName); groupServiceEntry.setServiceList(nameInsert); @@ -766,9 +774,9 @@ public class FirewallConfigPolicy extends Policy { private String getName(String name, JsonObject membersObj, String type) { String value; - if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ + if (type.equals("REFERENCE") || type.equals("GROUP") || type.equals("SERVICE")) { value = membersObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = membersObj.get("value").toString(); @@ -791,7 +799,6 @@ public class FirewallConfigPolicy extends Policy { return name; } - private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) { CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject oldJson = null; @@ -802,7 +809,7 @@ public class FirewallConfigPolicy extends Policy { oldJson = stringToJson(prevJsonBody); newJson = stringToJson(jsonBody); - //if no changes to the json then return true + // if no changes to the json then return true if (oldJson != null && oldJson.equals(newJson)) { return true; } @@ -815,12 +822,12 @@ public class FirewallConfigPolicy extends Policy { serviceGroup = newJson.getJsonArray("serviceGroups"); addressGroup = newJson.getJsonArray("addressGroups"); - //insert data into tables + // insert data into tables try { JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody); - for (int i = 0; i<jsonDiff.size(); i++) { - //String path = jsonDiff.get(i).asText(); + for (int i = 0; i < jsonDiff.size(); i++) { + // String path = jsonDiff.get(i).asText(); String jsonpatch = jsonDiff.get(i).toString(); JsonObject patchObj = stringToJson(jsonpatch); @@ -831,29 +838,29 @@ public class FirewallConfigPolicy extends Policy { /* * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ - for(int ri = 0; ri < firewallRules.size(); ri++) { + for (int ri = 0; ri < firewallRules.size(); ri++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(ri); - //get values from JSON fields of firewallRulesList Array + // get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\''); String action = ruleListobj.get("action").toString().replace('"', '\''); String description = ruleListobj.get("description").toString().replace('"', '\''); List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { TermList termEntry = (TermList) result.get(0); dbConnection.delete(termEntry); } - //getting fromZone Array field from the firewallRulesList + // getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) { + for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); @@ -865,13 +872,12 @@ public class FirewallConfigPolicy extends Policy { } } - String fromZoneInsert = "'"+fromZoneString+"'"; + String fromZoneInsert = "'" + fromZoneString + "'"; - //getting toZone Array field from the firewallRulesList + // getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); @@ -884,18 +890,18 @@ public class FirewallConfigPolicy extends Policy { } } - String toZoneInsert = "'"+toZoneString+"'"; - //getting sourceList Array fields from the firewallRulesList + String toZoneInsert = "'" + toZoneString + "'"; + // getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; - for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) { + for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = srcListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = srcListObj.get("value").toString(); @@ -904,19 +910,19 @@ public class FirewallConfigPolicy extends Policy { srcListString = getLeftOrRight(srcListString, value); } - String srcListInsert = "'"+srcListString+"'"; + String srcListInsert = "'" + srcListString + "'"; - //getting destinationList Array fields from the firewallRulesList + // getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; - for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) { + for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destListObj.get("value").toString(); @@ -924,19 +930,20 @@ public class FirewallConfigPolicy extends Policy { destListString = getLeftOrRight(destListString, value); } - String destListInsert = "'"+destListString+"'"; + String destListInsert = "'" + destListString + "'"; - //getting destServices Array fields from the firewallRulesList + // getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; - for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { + for (int destPortListIndex = 0; destPortListIndex < destServicesArray + .size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destServicesObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destServicesObj.get("value").toString(); @@ -944,7 +951,7 @@ public class FirewallConfigPolicy extends Policy { destPortListString = getLeftOrRight(destPortListString, value); } - String destPortListInsert = "'"+destPortListString+"'"; + String destPortListInsert = "'" + destPortListString + "'"; /* * Create Queries to INSERT data into database tables and execute @@ -955,21 +962,22 @@ public class FirewallConfigPolicy extends Policy { TermList termEntry = new TermList(); termEntry.setTermName(ruleName); - termEntry.setSrcIPList(srcListInsert); - termEntry.setDestIPList(destListInsert); + termEntry.setSrcIpList(srcListInsert); + termEntry.setDestIpList(destListInsert); termEntry.setProtocolList("null"); termEntry.setPortList("null"); termEntry.setSrcPortList("null"); termEntry.setDestPortList(destPortListInsert); termEntry.setAction(action); termEntry.setDescription(description); - termEntry.setFromZones(fromZoneInsert); - termEntry.setToZones(toZoneInsert); + termEntry.setFromZone(fromZoneInsert); + termEntry.setToZone(toZoneInsert); termEntry.setUserCreatedBy(userInfo); dbConnection.save(termEntry); - List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action); - if(actionResult == null || actionResult.isEmpty()){ + List<Object> actionResult = + dbConnection.getDataById(ActionList.class, "actionName", action); + if (actionResult == null || actionResult.isEmpty()) { saveActionListToDb(dbConnection, action); } } @@ -977,61 +985,66 @@ public class FirewallConfigPolicy extends Policy { if (path.contains("serviceGroups")) { /* - * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables + * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList + * tables */ - for(int si = 0; si < serviceGroup.size(); si++) { + for (int si = 0; si < serviceGroup.size(); si++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(si); String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); String description = null; - if (svcGroupListobj.containsKey("description")){ + if (svcGroupListobj.containsKey("description")) { description = svcGroupListobj.get("description").toString().replace('"', '\''); } JsonArray membersArray = svcGroupListobj.getJsonArray("members"); Boolean isServiceGroup = false; - if (membersArray!=null){ + if (membersArray != null) { String membersType = membersArray.getJsonObject(0).get("type").toString(); if (membersType.contains("REFERENCE")) { isServiceGroup = true; } } - //Insert values into GROUPSERVICELIST table if name begins with Group + // Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { - List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(GroupServiceList.class, "name", groupName); + if (result != null && !result.isEmpty()) { GroupServiceList groupEntry = (GroupServiceList) result.get(0); dbConnection.delete(groupEntry); } saveGroupServiceListTableToDb(dbConnection, groupName, membersArray); - } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table + } else { // Insert JSON data serviceGroup table, protocollist table, and portlist table String type = svcGroupListobj.get("type").toString().replace('"', '\''); - String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); + String transportProtocol = + svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); String ports = svcGroupListobj.get("ports").toString().replace('"', '\''); List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { ServiceList serviceEntry = (ServiceList) result.get(0); dbConnection.delete(serviceEntry); } - saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports); + saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, + ports); - List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); - if(protocolResult == null || protocolResult.isEmpty()){ + List<Object> protocolResult = + dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); + if (protocolResult == null || protocolResult.isEmpty()) { saveProtocolListToDb(dbConnection, transportProtocol); } List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports); - if(portResult == null || portResult.isEmpty()){ + if (portResult == null || portResult.isEmpty()) { savePortListToDb(dbConnection, ports); } } @@ -1042,46 +1055,47 @@ public class FirewallConfigPolicy extends Policy { /* * Inserting addressGroup data into the ADDRESSGROUP table */ - for(int ai=0; ai < addressGroup.size() ; ai++) { + for (int ai = 0; ai < addressGroup.size(); ai++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(ai); - //create JSON array for members + // create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\''); String description = null; - if (addressGroupObj.containsKey("description")){ + if (addressGroupObj.containsKey("description")) { description = addressGroupObj.get("description").toString().replace('"', '\''); } String prefixIP = null; String type = null; - for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) { + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); type = membersObj.get("type").toString().replace("\"", ""); - String value = null; prefixIP = getName(prefixIP, membersObj, type); } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'" + prefixIP + "'"; Boolean isAddressGroup = type.contains("REFERENCE"); if (isAddressGroup) { - List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); + if (result != null && !result.isEmpty()) { AddressGroup addressGroupEntry = (AddressGroup) result.get(0); dbConnection.delete(addressGroupEntry); } saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList); } else { - List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); + if (result != null && !result.isEmpty()) { PrefixList prefixListEntry = (PrefixList) result.get(0); dbConnection.delete(prefixListEntry); } @@ -1091,8 +1105,9 @@ public class FirewallConfigPolicy extends Policy { } } removeDuplicateValuesFromLookup(dbConnection); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", + "Exception executing Firewall queries"); return false; } return true; @@ -1123,18 +1138,20 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(protocolEntry); } - private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) { + private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, + String transportProtocol, String ports) { ServiceList serviceListEntry = new ServiceList(); serviceListEntry.setServiceName(groupName); serviceListEntry.setServiceDescription(description); serviceListEntry.setServiceType(type); - serviceListEntry.setServiceTransProtocol(transportProtocol); + serviceListEntry.setServiceTransportProtocol(transportProtocol); serviceListEntry.setServiceAppProtocol("null"); serviceListEntry.setServicePorts(ports); dbConnection.save(serviceListEntry); } - private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) { + private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, + String prefixList) { PrefixList newPrefixList = new PrefixList(); newPrefixList.setPrefixListName(addressGroupName); newPrefixList.setDescription(description); @@ -1142,7 +1159,8 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(newPrefixList); } - private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) { + private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, + String prefixList) { AddressGroup newAddressGroup = new AddressGroup(); newAddressGroup.setGroupName(addressGroupName); newAddressGroup.setDescription(description); @@ -1151,7 +1169,7 @@ public class FirewallConfigPolicy extends Policy { } private JsonObject stringToJson(String jsonString) { - //Read jsonBody to JsonObject + // Read jsonBody to JsonObject StringReader in = new StringReader(jsonString); JsonReader jsonReader = Json.createReader(in); JsonObject json = jsonReader.readObject(); @@ -1167,7 +1185,7 @@ public class FirewallConfigPolicy extends Policy { oldJason = JsonLoader.fromString(oldJson); updatedJason = JsonLoader.fromString(json); } catch (IOException e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } return JsonDiff.asJson(oldJason, updatedJason); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java index fc08b643e..72e6f488a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; @@ -34,7 +36,9 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.List; + import javax.persistence.PersistenceException; + import org.apache.commons.io.FilenameUtils; import org.hibernate.Query; import org.hibernate.Session; @@ -44,8 +48,8 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.rest.jpa.PolicyEntity; @@ -70,7 +74,6 @@ public class HandleIncomingNotifications { public static final String OTHER_CONFIG = "OTHER"; public static final String AUDIT_USER = "audit"; - private static SessionFactory sessionfactory; @Autowired @@ -82,15 +85,24 @@ public class HandleIncomingNotifications { // Default Constructor } + /** + * Handle the incoming HTTP notification. + * + * @param url the URL + * @param entityId the entity id + * @param entityType the entity type + * @param extraData extra data + * @param xacmlPapServlet the servlet to use + */ public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, XACMLPapServlet xacmlPapServlet) { logger.info("DBDao url: " + url + " has reported an update on " + entityType + " entity " + entityId); - PolicyDBDaoTransaction transaction = PolicyDBDao.getPolicyDBDaoInstance().getNewTransaction(); + PolicyDbDaoTransaction transaction = PolicyDbDao.getPolicyDbDaoInstance().getNewTransaction(); // although its named retries, this is the total number of tries int retries; try { retries = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); + .parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); } catch (Exception e) { logger.error("xacml.rest.pap.incomingnotification.tries property not set, using a default of 3." + e); retries = 3; @@ -101,6 +113,7 @@ public class HandleIncomingNotifications { retries = 1; } int pauseBetweenRetries = 1000; + switch (entityType) { case POLICY_NOTIFICATION: @@ -110,7 +123,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", " + extraData + ")"); } @@ -129,7 +142,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", " + transaction + ")"); } @@ -148,7 +161,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", " + extraData + ", " + transaction + ", " + xacmlPapServlet + ")"); } @@ -160,14 +173,25 @@ public class HandleIncomingNotifications { } } break; + + default: } // no changes should be being made in this function, we still need to // close transaction.rollbackTransaction(); } - private void handleIncomingGroupChange(String groupId, String extraData, PolicyDBDaoTransaction transaction) - throws PAPException, PolicyDBException { + /** + * Handle an incoming group change. + * + * @param groupId the group ID + * @param extraData extra data + * @param transaction the transaction + * @throws PAPException on PAP exceptions + * @throws PolicyDbException on Policy DB exceptions + */ + private void handleIncomingGroupChange(String groupId, String extraData, PolicyDbDaoTransaction transaction) + throws PAPException, PolicyDbException { GroupEntity groupRecord = null; long groupIdLong = -1; try { @@ -178,7 +202,7 @@ public class HandleIncomingNotifications { try { groupRecord = transaction.getGroup(groupIdLong); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp group record with transaction.getGroup(" + groupIdLong + ");"); throw new PAPException("Could not get local group " + groupIdLong); } @@ -189,7 +213,7 @@ public class HandleIncomingNotifications { // does group folder exist OnapPDPGroup localGroup = null; try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); } catch (Exception e) { logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup(" + groupId + ");", e); @@ -197,7 +221,7 @@ public class HandleIncomingNotifications { if (localGroup == null && extraData != null) { // here we can try to load an old group id from the extraData try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData); } catch (Exception e) { logger.warn( "Caught PAPException trying to get local pdp group with papEngine.getGroup(" + extraData + ");", @@ -208,17 +232,17 @@ public class HandleIncomingNotifications { OnapPDPGroup newLocalGroup = null; if (extraData != null) { try { - newLocalGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData); + newLocalGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData + ");"); } } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup + ", " + newLocalGroup + ");"); throw new PAPException("Could not remove group " + groupId); @@ -226,18 +250,21 @@ public class HandleIncomingNotifications { } else if (localGroup == null) { // creating a new group try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newGroup(groupRecord.getgroupName(), + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newGroup(groupRecord.getGroupName(), groupRecord.getDescription()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to create pdp group with " + + "papEngine.newGroup(groupRecord.getGroupName(), groupRecord.getDescription());"); throw new PAPException("Could not create group " + groupRecord); } try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get pdp group we just created with papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs or policies in the new group may not have been added"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get pdp group we just created with " + + "papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs " + + "or policies in the new group may not have been added"); return; } // add possible pdps to group @@ -245,11 +272,12 @@ public class HandleIncomingNotifications { for (Object pdpO : pdpsInGroup) { PdpEntity pdp = (PdpEntity) pdpO; try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup, + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), " + + "localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); throw new PAPException("Could not create pdp " + pdp); } } @@ -269,36 +297,36 @@ public class HandleIncomingNotifications { // set default if it should be if (!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().setDefaultGroup(localGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().setDefaultGroup(localGroup); return; } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to set default group with papEngine.SetDefaultGroup(" + localGroupClone + ");"); throw new PAPException("Could not set default group to " + localGroupClone); } } boolean needToUpdate = false; - if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord, transaction)) { + if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord)) { needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) - || !PolicyDBDao.stringEquals(localGroupClone.getName(), groupRecord.getgroupName())) { + if (!PolicyDbDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) + || !PolicyDbDao.stringEquals(localGroupClone.getName(), groupRecord.getGroupName())) { // changing ids // we do not want to change the id, the papEngine will do this // for us, it needs to know the old id - localGroupClone.setName(groupRecord.getgroupName()); + localGroupClone.setName(groupRecord.getGroupName()); needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) { + if (!PolicyDbDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) { localGroupClone.setDescription(groupRecord.getDescription()); needToUpdate = true; } if (needToUpdate) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updateGroup(localGroupClone); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updateGroup(localGroupClone); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone + ");"); throw new PAPException("Could not update group " + localGroupClone); @@ -310,7 +338,7 @@ public class HandleIncomingNotifications { // this will also handle removes, since incoming pdpGroup has no policies // internally, we are just going to add them all in from the db private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup, OnapPDPGroup oldPdpGroup, - GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException { + GroupEntity groupRecord) throws PAPException, PolicyDbException { if (!(pdpGroup instanceof StdPDPGroup)) { throw new PAPException("group is not a StdPDPGroup"); } @@ -325,7 +353,7 @@ public class HandleIncomingNotifications { } for (PolicyEntity policy : groupRecord.getPolicies()) { String pdpPolicyName = - PolicyDBDao.getPolicyDBDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope()); + PolicyDbDao.getPolicyDbDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope()); if (group.getPolicy(pdpPolicyName) == null) { didUpdate = true; if (currentPolicySet.containsKey(pdpPolicyName)) { @@ -335,7 +363,7 @@ public class HandleIncomingNotifications { "PolicyDBDao: Adding the new policy to the PDP group after notification: " + pdpPolicyName); InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); group.copyPolicyToFile(pdpPolicyName, policyStream); - ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDBDao.getPolicyDBDaoInstance() + ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDbDao.getPolicyDbDaoInstance() .removeExtensionAndVersionFromPolicyName(pdpPolicyName)); try { policyStream.close(); @@ -354,7 +382,7 @@ public class HandleIncomingNotifications { return didUpdate; } - private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException { + private void handleIncomingPdpChange(String pdpId, PolicyDbDaoTransaction transaction) throws PAPException { // get pdp long pdpIdLong = -1; try { @@ -366,7 +394,7 @@ public class HandleIncomingNotifications { try { pdpRecord = transaction.getPdp(pdpIdLong); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp record with transaction.getPdp(" + pdpIdLong + ");"); throw new PAPException("Could not get local pdp " + pdpIdLong); } @@ -375,15 +403,15 @@ public class HandleIncomingNotifications { } OnapPDP localPdp = null; try { - localPdp = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId()); + localPdp = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId()); } catch (PAPException e) { logger.warn("Caught PAPException trying to get local pdp with papEngine.getPDP(" + pdpId + ");", e); } if (localPdp != null && pdpRecord.isDeleted()) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removePDP(localPdp); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removePDP(localPdp); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get remove pdp with papEngine.removePDP(" + localPdp + ");"); throw new PAPException("Could not remove pdp " + pdpId); } @@ -393,17 +421,18 @@ public class HandleIncomingNotifications { OnapPDPGroup localGroup = null; try { localGroup = - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId()); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get local group to add pdp to with " + + "papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); throw new PAPException("Could not get local group"); } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup, + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup, pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + ", " + localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + ", " + pdpRecord.getJmxPort() + ");"); @@ -411,41 +440,41 @@ public class HandleIncomingNotifications { } } else { boolean needToUpdate = false; - if (!PolicyDBDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId()) - || !PolicyDBDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { + if (!PolicyDbDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId()) + || !PolicyDbDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { // again, we don't want to change the id, the papEngine will do // this localPdp.setName(pdpRecord.getPdpName()); needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) { + if (!PolicyDbDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) { localPdp.setDescription(pdpRecord.getDescription()); needToUpdate = true; } String localPdpGroupId = null; try { - localPdpGroupId = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDPGroup(localPdp).getId(); + localPdpGroupId = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDPGroup(localPdp).getId(); } catch (PAPException e) { // could be null or something, just warn at this point - logger.warn( - "Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", - e); + logger.warn("Caught PAPException trying to get id of local group that pdp is in with " + + "localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", e); } - if (!PolicyDBDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { + if (!PolicyDbDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { OnapPDPGroup newPdpGroup = null; try { - newPdpGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine() + newPdpGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine() .getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e) { // ok, now we have an issue. Time to stop things - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get id of local group to move pdp to with " + + "papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); throw new PAPException("Could not get local group"); } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);"); throw new PAPException("Could not move pdp " + localPdp); } @@ -456,9 +485,9 @@ public class HandleIncomingNotifications { } if (needToUpdate) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updatePDP(localPdp); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updatePDP(localPdp); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to update pdp with papEngine.updatePdp(" + localPdp + ");"); throw new PAPException("Could not update pdp " + localPdp); } @@ -490,22 +519,22 @@ public class HandleIncomingNotifications { if (policy.getConfigurationData() != null) { subFile = - getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDBDao.CONFIG); + getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDbDao.CONFIG); } else if (policy.getActionBodyEntity() != null) { - subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDBDao.ACTION); + subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDbDao.ACTION); } if (subFile != null) { Files.deleteIfExists(subFile); } if (policy.getConfigurationData() != null) { - writePolicySubFile(policy, PolicyDBDao.CONFIG); + writePolicySubFile(policy, PolicyDbDao.CONFIG); } else if (policy.getActionBodyEntity() != null) { writePolicySubFile(policy, action); } } } catch (IOException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, "Error occurred while performing [" + action + "] of Policy File: " + policyName); } finally { session.close(); @@ -518,8 +547,8 @@ public class HandleIncomingNotifications { String type = null; String subTypeName = null; String subTypeBody = null; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policyType)) { - type = PolicyDBDao.CONFIG; + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policyType)) { + type = PolicyDbDao.CONFIG; subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName()); subTypeBody = policy.getConfigurationData().getConfigBody(); @@ -539,12 +568,12 @@ public class HandleIncomingNotifications { subTypeName = subTypeName + ".txt"; } } - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policyType)) { - type = PolicyDBDao.ACTION; + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policyType)) { + type = PolicyDbDao.ACTION; subTypeName = policy.getActionBodyEntity().getActionBodyName(); subTypeBody = policy.getActionBodyEntity().getActionBody(); } - Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type); + Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); if (subTypeBody == null) { subTypeBody = ""; @@ -558,11 +587,10 @@ public class HandleIncomingNotifications { try (FileWriter fileWriter = new FileWriter(file, false)) { // false to overwrite fileWriter.write(subTypeBody); - fileWriter.close(); success = true; } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName()); } return success; @@ -571,7 +599,7 @@ public class HandleIncomingNotifications { Path getPolicySubFile(String inputFileName, String subFileType) { String filename = inputFileName; logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")"); - Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), subFileType); + Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), subFileType); File file = null; filename = FilenameUtils.removeExtension(filename); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java index 26c7ed834..5a7a2088f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,11 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,23 +37,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.MicroServiceModels; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -61,7 +49,16 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.MicroServiceModels; public class MicroServiceConfigPolicy extends Policy { @@ -70,7 +67,7 @@ public class MicroServiceConfigPolicy extends Policy { private static Map<String, String> mapAttribute = new HashMap<>(); private static Map<String, String> mapMatch = new HashMap<>(); - private static synchronized Map<String, String> getMatchMap () { + private static synchronized Map<String, String> getMatchMap() { return mapMatch; } @@ -82,34 +79,33 @@ public class MicroServiceConfigPolicy extends Policy { super(); } - public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){ + public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); - } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json")){ + if (policyName.endsWith(".xml")) { + policyName = policyName.replace(".xml", ""); + } + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) { out.println(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); + LOGGER.error("Exception Occured While writing Configuration data" + e); } } - @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -117,18 +113,18 @@ public class MicroServiceConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -156,7 +152,6 @@ public class MicroServiceConfigPolicy extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -170,32 +165,33 @@ public class MicroServiceConfigPolicy extends Policy { name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); } - //setup values for pulling out matching attributes + // setup values for pulling out matching attributes ObjectMapper mapper = new ObjectMapper(); String matching = null; Map<String, String> matchMap = null; try { JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - if (policyAdapter.getTtlDate()==null){ + if (policyAdapter.getTtlDate() == null) { policyAdapter.setTtlDate("NA"); } - if (policyAdapter.getServiceType().contains("-v")){ + if (policyAdapter.getServiceType().contains("-v")) { matching = getValueFromDictionary(policyAdapter.getServiceType()); } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), + new String[] {"\""}, new String[] {""}); matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); } - if (matching != null && !matching.isEmpty()){ + if (matching != null && !matching.isEmpty()) { matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); - setMatchMap(matchMap); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); + setMatchMap(matchMap); + if (policyAdapter.getJsonBody() != null) { + pullMatchValue(rootNode); } } } catch (IOException e1) { throw new PAPException(e1); } - + // Match for policyName allOfOne.getMatch().add(createMatch("PolicyName", name)); @@ -203,7 +199,7 @@ public class MicroServiceConfigPolicy extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); - if (matchMap==null || matchMap.isEmpty()){ + if (matchMap == null || matchMap.isEmpty()) { // Match for ConfigName allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); // Match for Service @@ -212,29 +208,25 @@ public class MicroServiceConfigPolicy extends Policy { allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid())); // Match for location allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation())); - }else { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + } else { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ + if (value.contains("matching-true")) { + if (mapAttribute.containsKey(key)) { allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); } } } } // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -265,7 +257,8 @@ public class MicroServiceConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -284,7 +277,8 @@ public class MicroServiceConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -317,36 +311,38 @@ public class MicroServiceConfigPolicy extends Policy { private void pullMatchValue(JsonNode rootNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry<String, JsonNode> field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - MicroServiceModels model = (MicroServiceModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = + StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, new String[] {"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service) { + String ruleTemplate = null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = + dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + modelVersion); + if (result != null && !result.isEmpty()) { + MicroServiceModels model = (MicroServiceModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("MSID"); @@ -372,12 +368,12 @@ public class MicroServiceConfigPolicy extends Policy { AttributeValueType AttributeValue = new AttributeValueType(); AttributeValue.setDataType(URI_DATATYPE); String configName; - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { configName = policyName.replace(".xml", ""); - }else{ + } else { configName = policyName; } - String content = CONFIG_URL +"/Config/" + configName + ".json"; + String content = CONFIG_URL + "/Config/" + configName + ".json"; AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); @@ -427,16 +423,16 @@ public class MicroServiceConfigPolicy extends Policy { assignment7.setAttributeId("matching:service"); assignment7.setCategory(CATEGORY_RESOURCE); assignment7.setIssuer(""); - + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); configNameAttributeValue7.setDataType(STRING_DATATYPE); configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - + advice.getAttributeAssignmentExpression().add(assignment7); Map<String, String> matchMap = getMatchMap(); - if (matchMap==null || matchMap.isEmpty()){ + if (matchMap == null || matchMap.isEmpty()) { AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -449,7 +445,6 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment6); - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("matching:uuid"); assignment8.setCategory(CATEGORY_RESOURCE); @@ -474,28 +469,28 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment9); } else { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ + if (value.contains("matching-true")) { + if (mapAttribute.containsKey(key)) { AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); assignment9.setAttributeId("matching:" + key); assignment9.setCategory(CATEGORY_RESOURCE); assignment9.setIssuer(""); - + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); configNameAttributeValue9.setDataType(STRING_DATATYPE); configNameAttributeValue9.getContent().add(mapAttribute.get(key)); assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - + advice.getAttributeAssignmentExpression().add(assignment9); - + } } } } - + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("Priority"); assignment10.setCategory(CATEGORY_RESOURCE); @@ -508,7 +503,7 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment10); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); assignment11.setAttributeId("RiskType"); assignment11.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java index 2e2a74015..e9db043bf 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,14 +34,14 @@ import java.util.List; import java.util.UUID; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; import org.onap.policy.utils.PeCryptoUtils; public class NotifyOtherPaps { private static final Logger LOGGER = FlexLogger.getLogger(NotifyOtherPaps.class); - private List<PolicyDBDaoEntity> failedPaps = null; + private List<PolicyDbDaoEntity> failedPaps = null; public void notifyOthers(long entityId, String entityType) { notifyOthers(entityId, entityType, null); @@ -55,10 +56,10 @@ public class NotifyOtherPaps { */ public void notifyOthers(long entityId, String entityType, String newGroupId) { LOGGER.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers(" + entityId + "," - + entityType + "," + newGroupId + ") called"); + + entityType + "," + newGroupId + ") called"); failedPaps = new ArrayList<>(); - List<?> otherServers = PolicyDBDao.getPolicyDBDaoInstance().getOtherServers(); + List<?> otherServers = PolicyDbDao.getPolicyDbDaoInstance().getOtherServers(); // Notify other paps startNotifyThreads(otherServers, entityId, entityType, newGroupId); // Retry for failed paps @@ -67,7 +68,7 @@ public class NotifyOtherPaps { } } - private void startNotifyThreads(List<?> otherServers, long entityId, String entityType, String newGroupId) { + protected void startNotifyThreads(List<?> otherServers, long entityId, String entityType, String newGroupId) { LinkedList<Thread> notifyThreads = new LinkedList<>(); // we're going to run notifications in parallel threads to speed things // up @@ -102,10 +103,9 @@ public class NotifyOtherPaps { @Override public void run() { - PolicyDBDao dao = new PolicyDBDao(); - PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity) obj; - String otherPap = dbdEntity.getPolicyDBDaoUrl(); - String username = dbdEntity.getUsername(); + PolicyDbDao dao = new PolicyDbDao(); + PolicyDbDaoEntity dbdEntity = (PolicyDbDaoEntity) obj; + String otherPap = dbdEntity.getPolicyDbDaoUrl(); String txt; try { txt = PeCryptoUtils.decrypt(dbdEntity.getPassword()); @@ -116,7 +116,6 @@ public class NotifyOtherPaps { } HttpURLConnection connection = null; - UUID requestId = UUID.randomUUID(); URL url; String papUrl; try { @@ -143,11 +142,11 @@ public class NotifyOtherPaps { return; } if (newGroupId == null) { - url = new URL(otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" - + entityType); + url = new URL( + otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + entityType); } else { url = new URL(otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" - + entityType + "&extradata=" + newGroupId); + + entityType + "&extradata=" + newGroupId); } } catch (MalformedURLException e) { LOGGER.warn("Caught MalformedURLException on: new URL()", e); @@ -174,6 +173,10 @@ public class NotifyOtherPaps { LOGGER.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");", e); return; } + + String username = dbdEntity.getUsername(); + UUID requestId = UUID.randomUUID(); + Base64.Encoder encoder = Base64.getEncoder(); String encoding = encoder.encodeToString((username + ":" + txt).getBytes(StandardCharsets.UTF_8)); connection.setRequestProperty("Authorization", "Basic " + encoding); @@ -183,7 +186,7 @@ public class NotifyOtherPaps { int readTimeout; try { readTimeout = - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_NOTIFY_TIMEOUT)); + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_NOTIFY_TIMEOUT)); } catch (Exception e) { LOGGER.error("xacml.rest.pap.notify.timeoutms property not set, using a default.", e); readTimeout = 10000; @@ -212,7 +215,7 @@ public class NotifyOtherPaps { LOGGER.info("PolicyDBDao: NotifyOtherThread received response 200 from pap server on notify"); } else { LOGGER.warn("PolicyDBDao: NotifyOtherThread connection response code not 200, received: " - + connection.getResponseCode()); + + connection.getResponseCode()); failedPaps.add(dbdEntity); } } catch (Exception e) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java index 2719a155b..097a33f8e 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -20,6 +20,11 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,23 +37,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.OptimizationModels; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -61,7 +49,16 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.OptimizationModels; public class OptimizationConfigPolicy extends Policy { @@ -70,7 +67,7 @@ public class OptimizationConfigPolicy extends Policy { private static Map<String, String> mapAttribute = new HashMap<>(); private static Map<String, String> mapMatch = new HashMap<>(); - private static synchronized Map<String, String> getMatchMap () { + private static synchronized Map<String, String> getMatchMap() { return mapMatch; } @@ -82,36 +79,35 @@ public class OptimizationConfigPolicy extends Policy { super(); } - public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){ + public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { policyName = policyName.replace(".xml", ""); } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){ + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json");) { out.println(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); + LOGGER.error("Exception Occured While writing Configuration data" + e); } } - @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -119,18 +115,18 @@ public class OptimizationConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -158,7 +154,6 @@ public class OptimizationConfigPolicy extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -172,32 +167,33 @@ public class OptimizationConfigPolicy extends Policy { name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); } - //setup values for pulling out matching attributes + // setup values for pulling out matching attributes ObjectMapper mapper = new ObjectMapper(); String matching = null; Map<String, String> matchMap = null; try { JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - if (policyAdapter.getTtlDate()==null){ + if (policyAdapter.getTtlDate() == null) { policyAdapter.setTtlDate("NA"); } - if (policyAdapter.getServiceType().contains("-v")){ + if (policyAdapter.getServiceType().contains("-v")) { matching = getValueFromDictionary(policyAdapter.getServiceType()); } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), + new String[] {"\""}, new String[] {""}); matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); } - if (matching != null && !matching.isEmpty()){ + if (matching != null && !matching.isEmpty()) { matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); setMatchMap(matchMap); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); + if (policyAdapter.getJsonBody() != null) { + pullMatchValue(rootNode); } } } catch (IOException e1) { throw new PAPException(e1); } - + // Match for policyName allOfOne.getMatch().add(createMatch("PolicyName", name)); @@ -205,28 +201,24 @@ public class OptimizationConfigPolicy extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); - if (matchMap!=null && !matchMap.isEmpty()) { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + if (matchMap != null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + if (value.contains("matching-true") && mapAttribute.containsKey(key)) { allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); } } } // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -257,7 +249,8 @@ public class OptimizationConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -276,7 +269,8 @@ public class OptimizationConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -309,36 +303,38 @@ public class OptimizationConfigPolicy extends Policy { private void pullMatchValue(JsonNode rootNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry<String, JsonNode> field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - OptimizationModels model = (OptimizationModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = + StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, new String[] {"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service) { + String ruleTemplate = null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = + dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion); + if (result != null && !result.isEmpty()) { + OptimizationModels model = (OptimizationModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("OptimizationID"); @@ -366,18 +362,18 @@ public class OptimizationConfigPolicy extends Policy { AttributeValueType attributeValue = new AttributeValueType(); attributeValue.setDataType(URI_DATATYPE); String configName; - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { configName = policyName.replace(".xml", ""); - }else{ + } else { configName = policyName; } - String content = CONFIG_URL +"/Config/" + configName + ".json"; + String content = CONFIG_URL + "/Config/" + configName + ".json"; attributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - //PolicyName Attribute Assignment + // PolicyName Attribute Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); assignment3.setCategory(CATEGORY_RESOURCE); @@ -395,7 +391,7 @@ public class OptimizationConfigPolicy extends Policy { assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - //VersionNumber Attribute Assignment + // VersionNumber Attribute Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); assignment4.setCategory(CATEGORY_RESOURCE); @@ -408,7 +404,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment4); - //OnapName Attribute Assignment + // OnapName Attribute Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ONAPID); assignment5.setCategory(CATEGORY_RESOURCE); @@ -421,41 +417,41 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment5); - //ServiceType Attribute Assignment + // ServiceType Attribute Assignment AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("matching:service"); assignment7.setCategory(CATEGORY_RESOURCE); assignment7.setIssuer(""); - + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); configNameAttributeValue7.setDataType(STRING_DATATYPE); configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - + advice.getAttributeAssignmentExpression().add(assignment7); // Add matching attribute assignments if exist Map<String, String> matchMap = getMatchMap(); - if (matchMap!=null && !matchMap.isEmpty()) { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + if (matchMap != null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + if (value.contains("matching-true") && mapAttribute.containsKey(key)) { AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); assignment9.setAttributeId("matching:" + key); assignment9.setCategory(CATEGORY_RESOURCE); assignment9.setIssuer(""); - + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); configNameAttributeValue9.setDataType(STRING_DATATYPE); configNameAttributeValue9.getContent().add(mapAttribute.get(key)); assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - + advice.getAttributeAssignmentExpression().add(assignment9); } } } - + // Priority Attribute Assignment AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("Priority"); @@ -469,7 +465,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment10); - //RiskType Attribute Assignment + // RiskType Attribute Assignment AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); assignment11.setAttributeId("RiskType"); assignment11.setCategory(CATEGORY_RESOURCE); @@ -482,7 +478,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment11); - //RiskLevel Attribute Assignment + // RiskLevel Attribute Assignment AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType(); assignment12.setAttributeId("RiskLevel"); assignment12.setCategory(CATEGORY_RESOURCE); @@ -495,7 +491,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment12); - //Guard Attribute Assignment + // Guard Attribute Assignment AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType(); assignment13.setAttributeId("guard"); assignment13.setCategory(CATEGORY_RESOURCE); @@ -508,7 +504,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment13); - //TTLDate Attribute Assignment + // TTLDate Attribute Assignment AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType(); assignment14.setAttributeId("TTLDate"); assignment14.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java index 549d26b28..4873fc5ce 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java @@ -2,15 +2,15 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * 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. @@ -21,6 +21,12 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; + import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -30,24 +36,21 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.xacml.util.XACMLPolicyWriter; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -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 abstract class Policy { @@ -141,7 +144,7 @@ public abstract class Policy { /** * Return the data field of the PolicyAdapter that will be used when saving this policy with the savePolicies * method. - * + * * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData() */ public abstract Object getCorrectPolicyDataObject(); @@ -324,12 +327,12 @@ public abstract class Policy { private static void loadWebapps() throws PAPException { if (actionHome == null || configHome == null) { - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS)); // Sanity Check if (webappsPath == null) { - PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS); throw new PAPException( - "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig; Path webappsPathAction; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java index 9a39b6ed1..9af380b05 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java @@ -24,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; @@ -36,7 +37,9 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; + import javax.persistence.PersistenceException; + import org.apache.commons.io.FilenameUtils; import org.hibernate.Criteria; import org.hibernate.LockMode; @@ -48,15 +51,15 @@ import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; import org.onap.policy.rest.jpa.DatabaseLockEntity; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -68,9 +71,12 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +/** + * The Class PolicyDbDao. + */ @Component -public class PolicyDBDao { - private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); +public class PolicyDbDao { + private static final Logger logger = FlexLogger.getLogger(PolicyDbDao.class); public static final String JSON_CONFIG = "JSON"; public static final String XML_CONFIG = "XML"; public static final String PROPERTIES_CONFIG = "PROPERTIES"; @@ -86,65 +92,82 @@ public class PolicyDBDao { public static final String PDPENTITY_SELECT = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; public static final String GROUP_NOT_FOUND = "The group could not be found with id "; - public static final String FOUND_IN_DB_NOT_DEL = - " were found in the database that are not deleted"; + public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted"; public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id "; - public static final String DELETED_STATUS_FOUND = - " and deleted status were found in the database"; + public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database"; public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id "; public static final String PDP_ID = "pdpId"; - public static final String QUERY_FAILED_FOR_GROUP = - "Query failed trying to check for existing group"; + public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group"; public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group "; public static final String SCOPE = "scope"; public static final String POLICYDBDAO_VAR = "PolicyDBDao"; public static final String DUP_POLICYID = "Somehow, more than one policy with the id "; public static final String FOUND_IN_DB = " were found in the database"; - private static PolicyDBDao currentInstance = null; + + private static final String AUDIT_STR = "Audit"; + + private static PolicyDbDao currentInstance = null; private static boolean isJunit = false; private static SessionFactory sessionfactory; private List<?> otherServers; private PAPPolicyEngine papEngine; - /** * Gets the current instance of PolicyDBDao. * * @return The instance of PolicyDBDao or throws exception if the given instance is null. - * @throws IllegalStateException if a PolicyDBDao instance is null. Call - * createPolicyDBDaoInstance (EntityManagerFactory emf) to get this. + * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance + * (EntityManagerFactory emf) to get this. */ - public static PolicyDBDao getPolicyDBDaoInstance() { + public static PolicyDbDao getPolicyDbDaoInstance() { logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); if (currentInstance != null) { return currentInstance; } else { - currentInstance = new PolicyDBDao("init"); + currentInstance = new PolicyDbDao("init"); } return currentInstance; } + /** + * Sets the pap engine. + * + * @param papEngine2 the new pap engine + */ public void setPapEngine(PAPPolicyEngine papEngine2) { this.papEngine = papEngine2; } + /** + * Instantiates a new policy db dao. + * + * @param sessionFactory the session factory + */ @Autowired - public PolicyDBDao(SessionFactory sessionFactory) { - PolicyDBDao.sessionfactory = sessionFactory; + public PolicyDbDao(SessionFactory sessionFactory) { + PolicyDbDao.sessionfactory = sessionFactory; } - public PolicyDBDao() { + /** + * Instantiates a new policy db dao. + */ + public PolicyDbDao() { // Default Constructor } - public PolicyDBDao(String init) { + /** + * Initialize the DAO. + * + * @param init initiation parameters + */ + public PolicyDbDao(String init) { // not needed in this release if (!register()) { - PolicyLogger.error( - "This server's PolicyDBDao instance could not be registered and may not reveive updates"); + PolicyLogger + .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); } - otherServers = getRemotePolicyDBDaoList(); + otherServers = getRemotePolicyDbDaoList(); if (logger.isDebugEnabled()) { logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size()); } @@ -153,21 +176,26 @@ public class PolicyDBDao { } } - // not static because we are going to be using the instance's emf - // waitTime in ms to wait for lock, or -1 to wait forever (no) + /** + * Start a synchronized transaction. + * + * <p>Not static because we are going to be using the instance's emf waitTime in ms to wait for lock, or -1 to wait + * forever (no) + * + * @param session the session + * @param waitTime the wait time + */ @SuppressWarnings("deprecation") public void startTransactionSynced(Session session, int waitTime) { - logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " - + "\n startTransactionSynced(" + session + "," + waitTime + ") called\n\n"); + logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" + + session + "," + waitTime + ") called\n\n"); DatabaseLockEntity lock = null; session.beginTransaction(); try { if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" - + "\n\n"); + logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n"); } - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, - LockMode.PESSIMISTIC_WRITE); + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); if (logger.isDebugEnabled()) { logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); } @@ -182,17 +210,17 @@ public class PolicyDBDao { } /** - * Gets the list of other registered PolicyDBDaos from the database + * Gets the list of other registered PolicyDBDaos from the database. * - * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos + * @return List (type PolicyDbDaoEntity) of other PolicyDBDaos */ - private List<?> getRemotePolicyDBDaoList() { + private List<?> getRemotePolicyDbDaoList() { logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called"); - List<?> policyDBDaoEntityList = new LinkedList<>(); + List<?> policyDbDaoEntityList = new LinkedList<>(); Session session = sessionfactory.openSession(); try { - Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); - policyDBDaoEntityList = cr.list(); + Criteria cr = session.createCriteria(PolicyDbDaoEntity.class); + policyDbDaoEntityList = cr.list(); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception querying for other registered PolicyDBDaos"); @@ -201,32 +229,37 @@ public class PolicyDBDao { try { session.close(); } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } - return policyDBDaoEntityList; + return policyDbDaoEntityList; } - public PolicyDBDaoTransaction getNewTransaction() { + /** + * Gets the new transaction. + * + * @return the new transaction + */ + public PolicyDbDaoTransaction getNewTransaction() { logger.debug("getNewTransaction() as getNewTransaction() called"); return new PolicyDbDaoTransactionInstance("init"); } - /* - * Because the normal transactions are not used in audits, we can use the same transaction - * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to provide - * different transaction timeout values in ms because the audit will run longer than normal - * transactions. + /** + * Get a new audit transaction. + * + * <p>Because the normal transactions are not used in audits, we can use the same transaction mechanism to get a + * transaction and obtain the emlock and the DB lock. We just need to provide different transaction timeout values + * in ms because the audit will run longer than normal transactions. + * + * @return the new audit transaction */ - public PolicyDBDaoTransaction getNewAuditTransaction() { + public PolicyDbDaoTransaction getNewAuditTransaction() { logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); // Use the standard transaction wait time in ms - int auditWaitMs = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)); // Use the (extended) audit timeout time in ms - int auditTimeoutMs = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT)); return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); } @@ -235,10 +268,10 @@ public class PolicyDBDao { * * @param one A String or null to compare * @param two A String or null to compare + * @return true, if successful */ public static boolean stringEquals(String one, String two) { - logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two - + ") called"); + logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called"); if (one == null && two == null) { return true; } @@ -249,20 +282,25 @@ public class PolicyDBDao { } /** - * Returns the url of this local pap server, removing the username and password, if they are - * present + * Returns the url of this local pap server, removing the username and password, if they are present. * * @return The url of this local pap server */ public String[] getPapUrlUserPass() { logger.debug("getPapUrl() as getPapUrl() called"); - String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL); if (url == null) { return null; } return splitPapUrlUserPass(url); } + /** + * Split the user and password of a PAP URL. + * + * @param url the URL + * @return the user and password + */ public String[] splitPapUrlUserPass(String url) { String[] urlUserPass = new String[3]; String[] commaSplit = url.split(","); @@ -272,15 +310,14 @@ public class PolicyDBDao { urlUserPass[2] = commaSplit[2]; } if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { - String usernamePropertyValue = - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID); if (usernamePropertyValue != null) { urlUserPass[1] = usernamePropertyValue; } } if (urlUserPass[2] == null || "".equals(urlUserPass[2])) { String passwordPropertyValue = - PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)); if (passwordPropertyValue != null) { urlUserPass[2] = passwordPropertyValue; } @@ -291,7 +328,7 @@ public class PolicyDBDao { } /** - * Register the PolicyDBDao instance in the PolicyDBDaoEntity table + * Register the PolicyDBDao instance in the PolicyDbDaoEntity table. * * @return Boolean, were we able to register? */ @@ -332,26 +369,25 @@ public class PolicyDBDao { } } } - logger.debug( - "\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); - PolicyDBDaoEntity foundPolicyDBDaoEntity = null; - Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); - cr.add(Restrictions.eq("policyDBDaoUrl", url[0])); + logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + PolicyDbDaoEntity foundPolicyDbDaoEntity = null; + Criteria cr = session.createCriteria(PolicyDbDaoEntity.class); + cr.add(Restrictions.eq("policyDbDaoUrl", url[0])); List<?> data = cr.list(); if (!data.isEmpty()) { - foundPolicyDBDaoEntity = (PolicyDBDaoEntity) data.get(0); + foundPolicyDbDaoEntity = (PolicyDbDaoEntity) data.get(0); } // encrypt the password String txt = PeCryptoUtils.encrypt(url[2]); - if (foundPolicyDBDaoEntity == null) { - PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); - newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]); - newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]); - newPolicyDBDaoEntity.setUsername(url[1]); - newPolicyDBDaoEntity.setPassword(txt); + if (foundPolicyDbDaoEntity == null) { + PolicyDbDaoEntity newPolicyDbDaoEntity = new PolicyDbDaoEntity(); + newPolicyDbDaoEntity.setPolicyDbDaoUrl(url[0]); + newPolicyDbDaoEntity.setDescription("PAP server at " + url[0]); + newPolicyDbDaoEntity.setUsername(url[1]); + newPolicyDbDaoEntity.setPassword(txt); try { - session.persist(newPolicyDBDaoEntity); + session.persist(newPolicyDbDaoEntity); session.getTransaction().commit(); } catch (Exception e) { logger.debug(e); @@ -365,13 +401,13 @@ public class PolicyDBDao { } } else { // just want to update in order to change modified date - if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) { - foundPolicyDBDaoEntity.setUsername(url[1]); + if (url[1] != null && !stringEquals(url[1], foundPolicyDbDaoEntity.getUsername())) { + foundPolicyDbDaoEntity.setUsername(url[1]); } - if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) { - foundPolicyDBDaoEntity.setPassword(txt); + if (txt != null && !stringEquals(txt, foundPolicyDbDaoEntity.getPassword())) { + foundPolicyDbDaoEntity.setPassword(txt); } - foundPolicyDBDaoEntity.preUpdate(); + foundPolicyDbDaoEntity.preUpdate(); try { session.getTransaction().commit(); } catch (Exception e) { @@ -390,12 +426,20 @@ public class PolicyDBDao { return true; } - /* - * This method is called during all pushPolicy transactions and makes sure the file system group - * is in sync with the database groupentity + /** + * Synchronize group policies in the fuile system. + * + * <p>This method is called during all pushPolicy transactions and makes sure the file system group is in sync with + * the database group entity + * + * @param pdpGroup the pdp group + * @param groupentity the groupentity + * @return the std PDP group + * @throws PAPException the PAP exception + * @throws PolicyDbException the policy db exception */ - public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, - GroupEntity groupentity) throws PAPException, PolicyDBException { + public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) + throws PAPException, PolicyDbException { HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>(); HashSet<String> newPolicyIdSet = new HashSet<>(); @@ -415,23 +459,19 @@ public class PolicyDBDao { // convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); name = name.substring(0, name.lastIndexOf('.')); - InputStream policyStream = - new ByteArrayInputStream(policy.getPolicyData().getBytes()); + InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); - URI location = - Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId) - .toUri(); + URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); StdPDPPolicy newPolicy = null; try { newPolicy = new StdPDPPolicy(pdpPolicyId, true, removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); newPolicySet.add(newPolicy); - logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() - + ", Location - " + location); + logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location); } catch (Exception e) { logger.debug(e); - PolicyLogger.error( - "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + PolicyLogger + .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + e.getMessage()); } } @@ -444,39 +484,44 @@ public class PolicyDBDao { } catch (Exception e) { logger.debug(e); PolicyLogger.error( - "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. " - + e.getMessage()); + "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy" + + " file from the group. " + e.getMessage()); } } } - logger.info( - "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); + logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); pdpGroup.setPolicies(newPolicySet); return pdpGroup; } - public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) - throws PolicyDBException { + /** + * Removes the extension and version from policy name. + * + * @param originalPolicyName the original policy name + * @return the string + * @throws PolicyDbException the policy db exception + */ + public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDbException { return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; } /** - * Splits apart the policy name and version from a policy file path + * Splits apart the policy name and version from a policy file path. * - * @param originalPolicyName: a policy file name ex: Config_policy.2.xml + * @param originalPolicyName the original policy name * @return An array [0]: The policy name, [1]: the policy version, as a string + * @throws PolicyDbException the policy db exception */ - public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) - throws PolicyDBException { + public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException { String policyName = originalPolicyName; String[] nameAndVersion = new String[2]; try { policyName = removeFileExtension(policyName); nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.')); if (isNullOrEmpty(nameAndVersion[0])) { - throw new PolicyDBException(); + throw new PolicyDbException(); } } catch (Exception e) { nameAndVersion[0] = originalPolicyName; @@ -485,7 +530,7 @@ public class PolicyDBDao { try { nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1); if (isNullOrEmpty(nameAndVersion[1])) { - throw new PolicyDBException(); + throw new PolicyDbException(); } } catch (Exception e) { nameAndVersion[1] = "1"; @@ -494,6 +539,13 @@ public class PolicyDBDao { return nameAndVersion; } + /** + * Get the PDP policy by name. + * + * @param name The name to get + * @param scope The scope to use + * @return the policy. + */ public String getPdpPolicyName(String name, String scope) { String finalName = ""; finalName += scope; @@ -507,18 +559,28 @@ public class PolicyDBDao { return fileName.substring(0, fileName.lastIndexOf('.')); } + /** + * Audit local database. + * + * @param papEngine2 the pap engine 2 + */ public void auditLocalDatabase(PAPPolicyEngine papEngine2) { logger.debug("PolicyDBDao.auditLocalDatabase() is called"); try { deleteAllGroupTables(); auditGroups(papEngine2); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "auditLocalDatabase() error"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); logger.error("Exception Occured" + e); } } + /** + * Audit local file system. + * + * @param group the group + * @return the std PDP group + */ public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) { logger.info("Starting Local File System group audit"); @@ -534,17 +596,15 @@ public class PolicyDBDao { if (groupQueryList != null && !groupQueryList.isEmpty()) { GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0); updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup); - logger.info( - "Group was updated during file system audit: " + updatedGroup.toString()); + logger.info("Group was updated during file system audit: " + updatedGroup.toString()); } - } catch (PAPException | PolicyDBException e) { + } catch (PAPException | PolicyDbException e) { logger.error(e); } catch (Exception e) { logger.error(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException( - "Query failed trying to check if group " + group.getId() + " exists"); + throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists"); } session.getTransaction().commit(); @@ -553,9 +613,8 @@ public class PolicyDBDao { return updatedGroup; } - /* - * This method is called at startup to recreate config data from DB to the file system. - * + /** + * Synchronize config data in file system. */ public void synchronizeConfigDataInFileSystem() { @@ -571,8 +630,7 @@ public class PolicyDBDao { final Criteria configDataQuery = session.createCriteria(cl.getName()); @SuppressWarnings("unchecked") final List<T> configDataResult = configDataQuery.list(); - Path webappsPath = Paths - .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); for (final T configData : configDataResult) { String configName = null; @@ -588,8 +646,7 @@ public class PolicyDBDao { } else { configName = ((ActionBodyEntity) configData).getActionBodyName(); configBody = (((ActionBodyEntity) configData).getActionBody() != null) - ? ((ActionBodyEntity) configData).getActionBody() - .getBytes(StandardCharsets.UTF_8) + ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8) : "".getBytes(); } Path filePath = Paths.get(webappsPath.toString(), configName); @@ -609,6 +666,9 @@ public class PolicyDBDao { session.close(); } + /** + * Delete all group tables. + */ public void deleteAllGroupTables() { logger.debug("PolicyDBDao.deleteAllGroupTables() called"); Session session = sessionfactory.openSession(); @@ -624,13 +684,17 @@ public class PolicyDBDao { session.close(); } + /** + * Audit groups. + * + * @param papEngine2 the pap engine 2 + */ @SuppressWarnings("unchecked") public void auditGroups(PAPPolicyEngine papEngine2) { logger.debug("PolicyDBDao.auditGroups() called"); Session session = sessionfactory.openSession(); session.getTransaction().begin(); - final String AUDIT_STR = "Audit"; try { Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups(); @@ -642,7 +706,7 @@ public class PolicyDBDao { groupEntity.setDescription(grp.getDescription()); groupEntity.setDefaultGroup(grp.isDefaultGroup()); groupEntity.setCreatedBy(AUDIT_STR); - groupEntity.setGroupId(createNewPDPGroupId(grp.getId())); + groupEntity.setGroupId(createNewPdpGroupId(grp.getId())); groupEntity.setModifiedBy(AUDIT_STR); session.persist(groupEntity); Set<OnapPDP> pdps = grp.getOnapPdps(); @@ -662,15 +726,13 @@ public class PolicyDBDao { for (PDPPolicy policy : policies) { try { - String[] stringArray = - getNameScopeAndVersionFromPdpPolicy(policy.getId()); + String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); if (stringArray == null) { throw new IllegalArgumentException( "Invalid input - policyID must contain name, scope and version"); } List<PolicyEntity> policyEntityList; - Query getPolicyEntitiesQuery = - session.getNamedQuery("PolicyEntity.findByNameAndScope"); + Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope"); getPolicyEntitiesQuery.setParameter("name", stringArray[0]); getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); @@ -694,8 +756,7 @@ public class PolicyDBDao { } } catch (Exception e) { session.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "Exception auditGroups outer catch"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); session.close(); return; } @@ -705,6 +766,13 @@ public class PolicyDBDao { } + /** + * Gets the config file. + * + * @param filename the filename + * @param policy the policy + * @return the config file + */ public String getConfigFile(String filename, PolicyRestAdapter policy) { if (policy == null) { return getConfigFile(filename, (String) null); @@ -714,12 +782,18 @@ public class PolicyDBDao { // copied from ConfigPolicy.java and modified // Here we are adding the extension for the configurations file based on the + /** + * Gets the config file. + * + * @param inputFilename the input filename + * @param configType the config type + * @return the config file + */ // config type selection for saving. public String getConfigFile(String inputFilename, String configType) { String filename = inputFilename; - logger.debug( - "getConfigFile(String filename, String scope, String configType) as getConfigFile(" - + filename + ", " + configType + ") called"); + logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename + + ", " + configType + ") called"); filename = FilenameUtils.removeExtension(filename); String id = configType; @@ -740,6 +814,12 @@ public class PolicyDBDao { return filename; } + /** + * Gets the name scope and version from pdp policy. + * + * @param fileName the file name + * @return the name scope and version from pdp policy + */ public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { String[] splitByDots = fileName.split("\\."); if (splitByDots.length < 3) { @@ -763,7 +843,13 @@ public class PolicyDBDao { return returnArray; } - public static String createNewPDPGroupId(String name) { + /** + * Creates the new PDP group id. + * + * @param name the name + * @return the string + */ + public static String createNewPdpGroupId(String name) { String id = name; // replace "bad" characters with sequences that will be ok for file // names and properties keys. @@ -786,7 +872,7 @@ public class PolicyDBDao { } /** - * Checks if any of the given strings are empty or null + * Checks if any of the given strings are empty or null. * * @param strings One or more Strings (or nulls) to check if they are null or empty * @return true if one or more of the given strings are empty or null @@ -800,47 +886,107 @@ public class PolicyDBDao { return false; } + /** + * Gets the other servers. + * + * @return the other servers + */ public List<?> getOtherServers() { return otherServers; } + /** + * Sets the other servers. + * + * @param otherServers the new other servers + */ public void setOtherServers(List<?> otherServers) { this.otherServers = otherServers; } + /** + * Gets the pap engine. + * + * @return the pap engine + */ public PAPPolicyEngine getPapEngine() { return papEngine; } - + /** + * Checks if is junit. + * + * @return true, if is junit + */ public static boolean isJunit() { return isJunit; } + /** + * Sets the junit. + * + * @param isJunit the new junit + */ public static void setJunit(boolean isJunit) { - PolicyDBDao.isJunit = isJunit; + PolicyDbDao.isJunit = isJunit; } - public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() { - return new PolicyDBDao().new PolicyDBDaoTestClass(); + /** + * Gets the policy DB dao test class. + * + * @return the policy DB dao test class + */ + public static PolicyDbDaoTestClass getPolicyDbDaoTestClass() { + return new PolicyDbDao().new PolicyDbDaoTestClass(); } - final class PolicyDBDaoTestClass { + /** + * The Class PolicyDBDaoTestClass. + */ + final class PolicyDbDaoTestClass { + + /** + * Gets the config file. + * + * @param filename the filename + * @param scope the scope + * @param policy the policy + * @return the config file + */ String getConfigFile(String filename, String scope, PolicyRestAdapter policy) { - return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); - } - - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) - throws PolicyDBException { - return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); - } - + return scope + "." + PolicyDbDao.this.getConfigFile(filename, policy); + } + + /** + * Gets the policy name and version from policy file name. + * + * @param originalPolicyName the original policy name + * @return the policy name and version from policy file name + * @throws PolicyDbException the policy db exception + */ + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException { + return PolicyDbDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); + } + + /** + * Gets the name scope and version from pdp policy. + * + * @param fileName the file name + * @return the name scope and version from pdp policy + */ String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { - return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName); + return PolicyDbDao.this.getNameScopeAndVersionFromPdpPolicy(fileName); } + /** + * Gets the pdp policy name. + * + * @param name the name + * @param scope the scope + * @return the pdp policy name + */ String getPdpPolicyName(String name, String scope) { - return PolicyDBDao.this.getPdpPolicyName(name, scope); + return PolicyDbDao.this.getPdpPolicyName(name, scope); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java index dbb2fa830..70ca36ac7 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,16 +22,19 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; + import java.util.List; + import javax.persistence.PersistenceException; -import org.onap.policy.rest.dao.PolicyDBException; + +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; -public interface PolicyDBDaoTransaction { +public interface PolicyDbDaoTransaction { /** * Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP @@ -42,7 +46,7 @@ public interface PolicyDBDaoTransaction { public void commitTransaction(); /** - * Create or update a policy + * Create or update a policy. * * @param policy A Policy object representing the policy to store or update * @param username A string of the username you want to be stored for doing this operation @@ -50,10 +54,10 @@ public interface PolicyDBDaoTransaction { * @throws PersistenceException If a database error occurs * @throws IllegalArgumentException If the Policy's PolicyRestAdapter contains incorrect data. */ - public void createPolicy(Policy policy, String username) throws PolicyDBException; + public void createPolicy(Policy policy, String username) throws PolicyDbException; /** - * Check if the PolicyDBDaoTransaction is currently open + * Check if the PolicyDBDaoTransaction is currently open. * * @return False if the PolicyDBDao transaction has not been used or has been committed already, true if it is open. */ @@ -70,9 +74,8 @@ public interface PolicyDBDaoTransaction { */ public void close(); - /** - * Create a new PDP group in the database + * Create a new PDP group in the database. * * @param groupID The ID to name the new group (use PolicyDBDao.createNewPDPGroupId) * @param groupName The name to use for the new group @@ -83,23 +86,22 @@ public interface PolicyDBDaoTransaction { * @throws PersistenceException If a database error occurs */ public void createGroup(String groupID, String groupName, String groupDescription, String username) - throws PolicyDBException; + throws PolicyDbException; /** - * Updates a group in the database with a new name of description + * Updates a group in the database with a new name of description. * * @param group The group with updated information. The id must match an existing group, but the name and * description can be changed. - * @param username Username of the user performing the operation * @param userId needed to store user information in policyAuditlog table during transaction. * @throws IllegalArgumentException If non-optional parameters are null or empty strings * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs or if the group can not be found */ - public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDBException; + public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDbException; /** - * Updates a PDP in the database with new information + * Updates a PDP in the database with new information. * * @param pdp The PDP to update * @param username Username of the user performing the operation @@ -107,7 +109,7 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs or if the pdp can not be found */ - public void updatePdp(OnapPDP pdp, String username) throws PolicyDBException; + public void updatePdp(OnapPDP pdp, String username) throws PolicyDbException; /** * Change the default group in the database to the group provided. @@ -118,7 +120,7 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ - public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDBException; + public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDbException; /** * Moves a PDP to a new group. @@ -130,41 +132,37 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ - public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDBException; + public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDbException; /** - * Add a new PDP to an existing group + * Add a new PDP to an existing group. * * @param pdpID The ID to name the new PDP * @param groupID The ID of the existing group to add the PDP to * @param pdpName The name to use for the new PDP * @param pdpDescription Description of the new PDP (optional) - * @param pdpJmxPort + * @param pdpJmxPort PDP JMX port * @param username Username of the user performing the operation * @throws IllegalArgumentException If non-optional parameters are null or empty strings * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, - String username) throws PolicyDBException; + String username) throws PolicyDbException; /** - * Add an existing policy to an existing group + * Add an existing policy to an existing group. * * @param group The ID of the existing group to add the policy to * @param policyID The ID of an existing policy - * @return - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - * @throws PolicyDBException + * @return the PDP groups + * @throws PolicyDbException on DB exceptions */ public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username) - throws PolicyDBException; - + throws PolicyDbException; /** - * Delete an existing PDP groupPolicyDBException + * Delete an existing PDP groupPolicyDBException. * * @param group A PDPGroup object representing the group to delete * @param moveToGroup A PDPGroup object representing another existing group which PDPs in the group being deleted @@ -174,7 +172,7 @@ public interface PolicyDBDaoTransaction { * @throws PersistenceException If a database error occurs * @throws PAPException If an error relating to how groups are handled occurs */ - public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException; + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException; /** * Removes an existing PDP from its group and deletes it. @@ -184,7 +182,7 @@ public interface PolicyDBDaoTransaction { * @throws IllegalStateException If a transaction is already open * @throws PersistenceException If a database error occurs */ - public void removePdpFromGroup(String pdpID, String username) throws PolicyDBException; + public void removePdpFromGroup(String pdpID, String username) throws PolicyDbException; public GroupEntity getGroup(long groupKey); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java index f63649ddc..e694f7e0b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -36,14 +38,17 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; + import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.hibernate.Query; @@ -53,9 +58,9 @@ import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; import org.onap.policy.rest.jpa.GroupEntity; @@ -71,12 +76,16 @@ import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.xml.sax.InputSource; - @Component -public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { - +public class PolicyDbDaoTransactionInstance implements PolicyDbDaoTransaction { private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class); + // Recurring constants + private static final String BRACKET_CALLED = ") called"; + private static final String EXISTS = " exists"; + private static final String GROUP = "group"; + private static final String CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS = "Caught Exception on notifyOthers("; + private final Object emLock = new Object(); long policyId; long groupId; @@ -86,8 +95,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private Thread transactionTimer; private static final String POLICY_NOTIFICATION = "policy"; private static final String PDP_NOTIFICATION = "pdp"; - private static final String GROUP_NOTIFICATION = "group"; - + private static final String GROUP_NOTIFICATION = GROUP; private static final String DECISIONMS_MODEL = "MicroService_Model"; private static boolean isJunit = false; @@ -100,8 +108,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { */ public PolicyDbDaoTransactionInstance(String test) { // call the constructor with arguments - this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); + this(Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT)), + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT))); } public PolicyDbDaoTransactionInstance() { @@ -115,7 +123,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private static SessionFactory sessionfactory; - /** * Instantiates a new policy DB dao transaction instance. * @@ -134,7 +141,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { session = sessionfactory.openSession(); try { - PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime); + PolicyDbDao.getPolicyDbDaoInstance().startTransactionSynced(session, transactionWaitTime); } catch (Exception e) { logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e); throw new PersistenceException( @@ -221,7 +228,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { session.getTransaction().commit(); } catch (RollbackException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught RollbackException on em.getTransaction().commit()"); throw new PersistenceException("The commit failed. Message:\n" + e.getMessage()); } @@ -232,16 +239,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + "," + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + "," + newGroupId + ")"); } } else { try { otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ")"); } } } @@ -251,16 +258,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + "," + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + "," + newGroupId + ")"); } } else { try { otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ")"); } } } @@ -269,8 +276,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + pdpId + "," + PDP_NOTIFICATION + ")"); } } } @@ -287,13 +294,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { session.getTransaction().rollback(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not rollback transaction"); } try { session.close(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not close Hibernate Session."); } @@ -317,7 +324,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", " + policyScope + ", " + policyName + ", " + policyDataString + ") called"); synchronized (emLock) { - PolicyDBDao policyDbDao = new PolicyDBDao(); + PolicyDbDao policyDbDao = new PolicyDbDao(); checkBeforeOperationRun(); String configName = policyName; if (policyName.contains("Config_")) { @@ -332,7 +339,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyName = policyName.split(":")[1]; Query createPolicyQuery = session .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); - createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope); + createPolicyQuery.setParameter(PolicyDbDao.SCOPE, policyScope); createPolicyQuery.setParameter("policyName", policyName); List<?> createPolicyQueryList = createPolicyQuery.list(); PolicyEntity newPolicyEntity; @@ -351,7 +358,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } ActionBodyEntity newActionBodyEntity = null; - if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) { + if (policy.getPolicyType().equals(PolicyDbDao.ACTION)) { boolean abupdate = false; if (newPolicyEntity.getActionBodyEntity() == null) { newActionBodyEntity = new ActionBodyEntity(); @@ -410,7 +417,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } ConfigurationDataEntity newConfigurationDataEntity; - if (PolicyDBDao.CONFIG.equals(policy.getPolicyType()) + if (PolicyDbDao.CONFIG.equals(policy.getPolicyType()) || DECISIONMS_MODEL.equals(policy.getRuleProvider())) { boolean configUpdate; if (newPolicyEntity.getConfigurationData() == null) { @@ -423,7 +430,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (newConfigurationDataEntity != null) { - if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), + if (!PolicyDbDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), policyDbDao.getConfigFile(configName, policy))) { newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy)); } @@ -478,22 +485,22 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } policyId = newPolicyEntity.getPolicyId(); - if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) { newPolicyEntity.setPolicyName(policyName); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) { newPolicyEntity.setCreatedBy(username); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) { newPolicyEntity.setDescription(policy.getPolicyDescription()); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) { newPolicyEntity.setModifiedBy(username); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) { newPolicyEntity.setPolicyData(policyDataString); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getScope(), policyScope)) { newPolicyEntity.setScope(policyScope); } if (newPolicyEntity.isDeleted()) { @@ -518,7 +525,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { InputStream policyXmlStream = null; try { logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + "," - + username + ") called"); + + username + BRACKET_CALLED); String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); // Does not need to be XACMLPolicyWriterWithPapNotify since it is // already in the PAP @@ -535,22 +542,26 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyDataString = IOUtils.toString(policyXmlStream); } catch (IOException e) { policyDataString = "could not read"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught IOException on IOUtils.toString(" + policyXmlStream + ")"); throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); } IOUtils.closeQuietly(policyXmlStream); - if (PolicyDBDao.isJunit()) { + if (PolicyDbDao.isJunit()) { + if (policyDataString != null) { + logger.warn("isJUnit will overwrite policyDataString"); + } // Using parentPath object to set policy data. policyDataString = policy.policyAdapter.getParentPath(); } String configPath = ""; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { configPath = evaluateXPath( - "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", + "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/" + + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { configPath = evaluateXPath( "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " + policy.policyAdapter.getActionAttribute() @@ -558,16 +569,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyDataString); } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { configPath = evaluateXPath( - "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", + "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/" + + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); } String prefix = null; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); - if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { + if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { String configData = ""; try { String newConfigPath = configPath; @@ -582,7 +594,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } policy.policyAdapter.setConfigBodyData(configData); } - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Action_"; } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Decision_"; @@ -599,20 +611,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // get the config file extension String ext = ""; if (configPath != null && !"".equalsIgnoreCase(configPath)) { - ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());; + ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length()); } if (ext.contains("txt")) { - policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG); } else if (ext.contains("json")) { - policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG); } else if (ext.contains("xml")) { - policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG); } else if (ext.contains("properties")) { - policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG); } else { - if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) { - policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG); + if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) { + policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG); } } } @@ -629,7 +641,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } - public PolicyEntity getPolicy(int policyId) { return getPolicy(policyId, null, null); } @@ -640,42 +651,42 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) { logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName - + ") called"); - if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) { + + BRACKET_CALLED); + if (policyIdVar < 0 && PolicyDbDao.isNullOrEmpty(policyName, scope)) { throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank"); } synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists - String policyId; + String locPolicyId; Query policyQuery; - if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) { - policyId = policyName; + if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) { + locPolicyId = policyName; policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); - policyQuery.setParameter("name", policyId); + policyQuery.setParameter("name", locPolicyId); policyQuery.setParameter("scope", scope); } else { - policyId = String.valueOf(policyIdVar); + locPolicyId = String.valueOf(policyIdVar); policyQuery = session.getNamedQuery("PolicyEntity.FindById"); - policyQuery.setParameter("id", policyId); + policyQuery.setParameter("id", locPolicyId); } List<?> policyQueryList; try { policyQueryList = policyQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get policy with policyQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get policy " + policyId); + throw new PersistenceException("Query failed trying to get policy " + locPolicyId); } if (policyQueryList.isEmpty()) { - PolicyLogger.error("Policy does not exist with id " + policyId); - throw new PersistenceException("Group policy is being added to does not exist with id " + policyId); + PolicyLogger.error("Policy does not exist with id " + locPolicyId); + throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId); } else if (policyQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); - throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB); + throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB); } return (PolicyEntity) policyQueryList.get(0); } @@ -683,7 +694,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public GroupEntity getGroup(long groupKey) { - logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called"); + logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED); if (groupKey < 0) { throw new IllegalArgumentException("groupKey must be at least 0"); } @@ -696,18 +707,18 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group does not exist with groupKey " + groupKey); throw new PersistenceException("Group does not exist with groupKey " + groupKey); } else if (groupQueryList.size() > 1) { PolicyLogger - .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB); throw new PersistenceException( - "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB); } return (GroupEntity) groupQueryList.get(0); } @@ -715,29 +726,29 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public GroupEntity getGroup(String groupId) { - logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupId)) { + logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupId)) { throw new IllegalArgumentException("groupId must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); - groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); + groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId); List<?> groupQueryList; try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group does not exist with id " + groupId); throw new PersistenceException("Group does not exist with id " + groupId); } else if (groupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB); - throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB); + throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB); } return (GroupEntity) groupQueryList.get(0); } @@ -745,21 +756,21 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public List<?> getPdpsInGroup(long groupKey) { - logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called"); + logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED); if (groupKey < 0) { throw new IllegalArgumentException("groupId must not be < 0"); } synchronized (emLock) { checkBeforeOperationRun(true); Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); - pdpsQuery.setParameter("group", getGroup(groupKey)); + pdpsQuery.setParameter(GROUP, getGroup(groupKey)); return pdpsQuery.list(); } } @Override public PdpEntity getPdp(long pdpKey) { - logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called"); + logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED); if (pdpKey < 0) { throw new IllegalArgumentException("pdpKey must be at least 0"); } @@ -772,7 +783,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { pdpQueryList = pdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp with pdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get pdp " + pdpKey); } @@ -780,9 +791,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey); throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey); } else if (pdpQueryList.size() > 1) { - PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB); throw new PersistenceException( - "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB); + "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB); } return (PdpEntity) pdpQueryList.get(0); } @@ -798,7 +809,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private String processConfigPath(String inputConfigPath) { String configPath = inputConfigPath; - String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS); + String webappsPath = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS); if (webappsPath == null) { logger.error("Webapps property does not exist"); throw new IllegalArgumentException("Webapps property does not exist"); @@ -835,7 +846,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { return configDataString; } - @Override public void close() { synchronized (emLock) { @@ -855,8 +865,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) { String groupDescription = inputGroupDescription; logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", " - + groupDescription + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) { + + groupDescription + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) { throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); } if (groupDescription == null) { @@ -865,16 +875,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { checkBeforeOperationRun(); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The group being added already exists with id " + groupId); @@ -898,50 +908,50 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void updateGroup(OnapPDPGroup group, String requestType, String username) { logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + "," - + username + ") called"); + + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) { + if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) { throw new IllegalArgumentException("group.getId() and username must not be null or empty"); } synchronized (emLock) { - PolicyDBDao policyDbDaoVar = new PolicyDBDao(); + PolicyDbDao policyDbDaoVar = new PolicyDbDao(); checkBeforeOperationRun(); - Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - getGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + getGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getGroupQueryList; try { getGroupQueryList = getGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing"); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing"); } if (getGroupQueryList.isEmpty()) { PolicyLogger.error("The group cannot be found to update with id " + group.getId()); throw new PersistenceException("The group cannot be found to update with id " + group.getId()); } else if (getGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0); - if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { + if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { groupToUpdateInDb.setModifiedBy(requestType); } if (group.getDescription() != null - && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { + && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { groupToUpdateInDb.setDescription(group.getDescription()); } // let's find out what policies have been deleted StdPDPGroup oldGroup = null; try { - oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId()); + oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, "We cannot get the group from the papEngine to delete policies"); } if (oldGroup == null) { @@ -992,7 +1002,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not get policy to remove: " + pol.getId()); throw new PersistenceException("Could not get policy to remove: " + pol.getId()); } @@ -1001,19 +1011,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (group.getName() != null - && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) { + && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getGroupName())) { // we need to check if the new id exists in the database - String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName()); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName()); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The new group name already exists, group id " + newGrpId); @@ -1034,35 +1044,35 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, " + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", " + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username - + ") called"); - if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { + + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (checkGroupQueryList.size() != 1) { PolicyLogger.error("The group does not exist"); throw new PersistenceException("The group does not exist"); } - Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId); - checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId); + checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkDuplicateList; try { checkDuplicateList = checkDuplicateQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check for duplicate PDP " + pdpId + " on checkDuplicateQuery.getResultList()"); throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId); @@ -1094,24 +1104,24 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void updatePdp(OnapPDP pdp, String username) { - logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called"); + logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED); if (pdp == null) { throw new IllegalArgumentException("PDP pdp must not be null"); } - if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) { + if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) { throw new IllegalArgumentException("pdp.getId() and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId()); - getPdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId()); + getPdpQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getPdpQueryList; try { getPdpQueryList = getPdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getPdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get PDP " + pdp.getId()); } @@ -1119,19 +1129,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId()); throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId()); } else if (getPdpQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); - if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } if (pdp.getDescription() != null - && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { + && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { pdpToUpdate.setDescription(pdp.getDescription()); } - if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) { + if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) { pdpToUpdate.setPdpName(pdp.getName()); } if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) { @@ -1146,25 +1156,25 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) { logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + "," - + username + ") called"); + + username + BRACKET_CALLED); if (pdp == null || group == null) { throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) { + if (PolicyDbDao.isNullOrEmpty(username, pdp.getId(), group.getId())) { throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); // check if pdp exists - Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId()); - getPdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId()); + getPdpQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getPdpQueryList; try { getPdpQueryList = getPdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getPdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId()); } @@ -1172,20 +1182,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId()); throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId()); } else if (getPdpQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } // check if new group exists - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group on checkGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to get new group " + group.getId()); } @@ -1196,7 +1206,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0); PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); pdpToUpdate.setGroup(groupToMoveInto); - if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } @@ -1208,38 +1218,38 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void changeDefaultGroup(OnapPDPGroup group, String username) { logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + "," - + username + ") called"); + + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) { + if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) { throw new IllegalArgumentException("group.getId() and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - getGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + getGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> getGroupQueryList; try { getGroupQueryList = getGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId()); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId()); } if (getGroupQueryList.isEmpty()) { PolicyLogger.error("The group cannot be found to set default with id " + group.getId()); throw new PersistenceException("The group cannot be found to set default with id " + group.getId()); } else if (getGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0); newDefaultGroup.setDefaultGroup(true); - if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) { newDefaultGroup.setModifiedBy(username); } @@ -1249,12 +1259,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey"); // not going to set modified by for all groups setAllGroupsNotDefault.setParameter("defaultGroup", false); - setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false); + setAllGroupsNotDefault.setParameter(PolicyDbDao.DELETED, false); setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey()); try { logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on setAllGroupsNotDefault.executeUpdate()"); throw new PersistenceException("Could not set all other groups default to false"); } @@ -1263,51 +1273,51 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException { + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException { logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", " - + moveToGroup + "," + username + ") called"); + + moveToGroup + "," + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group cannot be null"); } - if (PolicyDBDao.isNullOrEmpty(username, group.getId())) { + if (PolicyDbDao.isNullOrEmpty(username, group.getId())) { throw new IllegalArgumentException("group.getId() and and username must not be null or empty"); } if (group.isDefaultGroup()) { PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be."); - throw new PolicyDBException("You cannot delete the default group."); + throw new PolicyDbException("You cannot delete the default group."); } synchronized (emLock) { checkBeforeOperationRun(); - Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> deleteGroupQueryList; try { deleteGroupQueryList = deleteGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to check if group exists"); } if (deleteGroupQueryList.isEmpty()) { - logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId()); + logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId()); return; } else if (deleteGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } Query pdpsInGroupQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted"); - pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0))); - pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false); + pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0))); + pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> pdpsInGroupList; try { pdpsInGroupList = pdpsInGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to get PDPs in group"); } @@ -1315,37 +1325,37 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { if (moveToGroup != null) { Query checkMoveToGroupQuery = session .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted"); - checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId()); - checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false); + checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId()); + checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> checkMoveToGroupList; try { checkMoveToGroupList = checkMoveToGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList"); throw new PersistenceException("Query failed trying to check if group exists"); } if (checkMoveToGroupList.isEmpty()) { - PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId()); - throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId()); + PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId()); + throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId()); } else if (checkMoveToGroupList.size() > 1) { PolicyLogger.error( - PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } else { GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0); for (Object pdpObject : pdpsInGroupList) { PdpEntity pdp = (PdpEntity) pdpObject; pdp.setGroup(newGroup); - if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) { pdp.setModifiedBy(username); } try { session.flush(); this.newGroupId = newGroup.getGroupId(); } catch (PersistenceException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PersistenceException trying to set pdp group to null on em.flush()"); throw new PersistenceException("Query failed trying to set pdp group to "); } @@ -1354,14 +1364,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } else { PolicyLogger.error("Group " + group.getId() + " is trying to be delted with PDPs. No group was provided to move them to"); - throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to"); + throw new PolicyDbException("Group has PDPs. Must provide a group for them to move to"); } } // delete group here GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0); groupToDelete.setDeleted(true); - if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) { groupToDelete.setModifiedBy(username); } session.flush(); @@ -1371,40 +1381,40 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username) - throws PolicyDBException { + throws PolicyDbException { logger.info( "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup(" - + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { + + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); // check if group exists - Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar); - groupQuery.setParameter(PolicyDBDao.DELETED, false); + Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar); + groupQuery.setParameter(PolicyDbDao.DELETED, false); List<?> groupQueryList; try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists"); + throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar); throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar); } else if (groupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } // we need to convert the form of the policy id that is used groups // into the form that is used // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml) - PolicyDBDao policyDbDao = new PolicyDBDao(); + PolicyDbDao policyDbDao = new PolicyDbDao(); String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar); if (policyNameScopeAndVersion == null) { throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version"); @@ -1412,17 +1422,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName " + "AND p.scope=:scope AND p.deleted=:deleted"); policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]); - policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]); - policyQuery.setParameter(PolicyDBDao.DELETED, false); + policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]); + policyQuery.setParameter(PolicyDbDao.DELETED, false); List<?> policyQueryList; try { policyQueryList = policyQuery.list(); } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if policy exists policyQuery.getResultList()"); throw new PersistenceException( - "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists"); + "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS); } if (policyQueryList.isEmpty()) { PolicyLogger.error("Policy being added to the group does not exist with policy id " @@ -1431,9 +1441,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + policyNameScopeAndVersion[0]); } else if (policyQueryList.size() > 1) { PolicyLogger.error( - PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } logger.info("PolicyDBDao: Getting group and policy from database"); GroupEntity group = (GroupEntity) groupQueryList.get(0); @@ -1464,7 +1474,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // filesytem group is in sync with the db group try { StdPDPGroup pdpGroup = - (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId()); + (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId()); return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group); } catch (PAPException e) { logger.debug(e); @@ -1479,27 +1489,27 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void removePdpFromGroup(String pdpId, String username) { logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username - + ") called"); - if (PolicyDBDao.isNullOrEmpty(pdpId, username)) { + + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(pdpId, username)) { throw new IllegalArgumentException("pdpID and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId); - pdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId); + pdpQuery.setParameter(PolicyDbDao.DELETED, false); List<?> pdpList; try { pdpList = pdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if pdp exists pdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists"); + throw new PersistenceException("Query failed trying to check if pdp " + pdpId + EXISTS); } if (pdpList.size() > 1) { - PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } else if (pdpList.isEmpty()) { PolicyLogger.error("Pdp being removed does not exist with id " + pdpId); return; @@ -1509,7 +1519,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { pdp.setGroup(null); } - if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) { pdp.setModifiedBy(username); } pdp.setDeleted(true); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java index 7a0f708d8..6ef7a8f18 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import java.util.List; @@ -31,8 +32,8 @@ import org.yaml.snakeyaml.constructor.Constructor; public class SafePolicyBuilder { - private SafePolicyBuilder(){ - //Private Constructor. + private SafePolicyBuilder() { + // Private Constructor. } public static ControlLoopGuard loadYamlGuard(String specification) { @@ -45,40 +46,42 @@ public class SafePolicyBuilder { return (ControlLoopGuard) obj; } - public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap, List<String> blacklist, List<String> targets) { - //Setup default values and Targets. - StringBuilder targetRegex= new StringBuilder(".*|"); - if(targets!=null && !targets.isEmpty()){ + public static String generateXacmlGuard(String xacmlFileContent, Map<String, String> generateMap, + List<String> blacklist, List<String> targets) { + // Setup default values and Targets. + StringBuilder targetRegex = new StringBuilder(".*|"); + if (targets != null && !targets.isEmpty()) { targetRegex = new StringBuilder(); - for(String t : targets){ + for (String t : targets) { targetRegex.append(t + "|"); } } - if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){ - generateMap.put("clname",".*"); + if (generateMap.get("clname") == null || generateMap.get("clname").isEmpty()) { + generateMap.put("clname", ".*"); } - generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1)); + generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length() - 1)); // Replace values. - for(Map.Entry<String,String> map: generateMap.entrySet()){ - Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}"); + for (Map.Entry<String, String> map : generateMap.entrySet()) { + Pattern p = Pattern.compile("\\$\\{" + map.getKey() + "\\}"); Matcher m = p.matcher(xacmlFileContent); String finalInput = map.getValue(); - if(finalInput.contains("$")){ + if (finalInput.contains("$")) { finalInput = finalInput.replace("$", "\\$"); } - xacmlFileContent=m.replaceAll(finalInput); + xacmlFileContent = m.replaceAll(finalInput); } - if(blacklist!=null && !blacklist.isEmpty()){ + if (blacklist != null && !blacklist.isEmpty()) { StringBuilder rule = new StringBuilder(); - for(String blackListName : blacklist){ - if(blackListName.contains("$")){ + for (String blackListName : blacklist) { + if (blackListName.contains("$")) { blackListName = blackListName.replace("$", "\\$"); } - rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"+blackListName+"</AttributeValue>"); + rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + blackListName + + "</AttributeValue>"); } Pattern p = Pattern.compile("\\$\\{blackListElement\\}"); Matcher m = p.matcher(xacmlFileContent); - xacmlFileContent=m.replaceAll(rule.toString()); + xacmlFileContent = m.replaceAll(rule.toString()); } PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); return xacmlFileContent; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java index 8e620408b..f576bffe8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,6 +20,10 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; @@ -38,10 +42,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class ActionPolicyDictionaryController { @@ -51,36 +51,43 @@ public class ActionPolicyDictionaryController { private static String actionDatas = "actionPolicyDictionaryDatas"; @Autowired - public ActionPolicyDictionaryController(CommonClassDao commonClassDao){ + public ActionPolicyDictionaryController(CommonClassDao commonClassDao) { ActionPolicyDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { ActionPolicyDictionaryController.commonClassDao = commonClassDao; } - public ActionPolicyDictionaryController(){ + public ActionPolicyDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionEntitybyName(HttpServletResponse response){ + @RequestMapping( + value = {"/get_ActionPolicyDictDataByName"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionEntitybyName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, actionDatas, attributeName, ActionPolicyDict.class); } - @RequestMapping(value={"/get_ActionPolicyDictData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionPolicyDictionaryEntityData(HttpServletResponse response){ + @RequestMapping( + value = {"/get_ActionPolicyDictData"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionPolicyDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, actionDatas, ActionPolicyDict.class); } - @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={RequestMethod.POST}) - public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/action_dictionary/save_ActionDict"}, method = {RequestMethod.POST}) + public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -90,63 +97,68 @@ public class ActionPolicyDictionaryController { ActionPolicyDict actionPolicyDict = null; ActionAdapter adapter = null; String userId = null; - if(fromAPI){ + if (fromAPI) { actionPolicyDict = mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class); adapter = mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class); userId = "API"; - }else{ - actionPolicyDict = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); + } else { + actionPolicyDict = + mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), + attributeName, ActionPolicyDict.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { actionPolicyDict.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))) { duplicateflag = true; } } actionPolicyDict.setHeader(utils.appendKeyValue(adapter.getHeaders(), ":", "=")); String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { actionPolicyDict.setUserModifiedBy(userInfo); - if(actionPolicyDict.getId() == 0){ + if (actionPolicyDict.getId() == 0) { actionPolicyDict.setUserCreatedBy(userInfo); commonClassDao.save(actionPolicyDict); - }else{ + } else { actionPolicyDict.setModifiedDate(new Date()); commonClassDao.update(actionPolicyDict); } responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class)); - }else{ + } else { responseString = "Duplicate"; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, actionDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={RequestMethod.POST}) - public void removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/action_dictionary/remove_actionPolicyDict"}, method = {RequestMethod.POST}) + public void removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, actionDatas, ActionPolicyDict.class); } } -class ActionAdapter{ + +class ActionAdapter { private List<Object> headers; public List<Object> getHeaders() { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java index d6ebed2b8..d9cde35bb 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java @@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.io.IOUtils; import org.onap.policy.api.PEDependency; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -37,9 +40,9 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.BRMSController; -import org.onap.policy.rest.jpa.BRMSDependency; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsController; +import org.onap.policy.rest.jpa.BrmsDependency; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PolicyUtils; @@ -51,7 +54,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; - @Controller public class BRMSDictionaryController { @@ -91,32 +93,35 @@ public class BRMSDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_BRMSParamDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSParamDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, brmsParamDatas, ruleName, BRMSParamTemplate.class); + utils.getDataByEntity(response, brmsParamDatas, ruleName, BrmsParamTemplate.class); } - @RequestMapping(value = {"/get_BRMSParamData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSParamData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSParamDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, brmsParamDatas, BRMSParamTemplate.class); + utils.getData(response, brmsParamDatas, BrmsParamTemplate.class); } @RequestMapping(value = {"/brms_dictionary/set_BRMSParamData"}, method = {RequestMethod.POST}) public static void setRuleData(HttpServletRequest request) throws IOException { StringWriter writer = new StringWriter(); IOUtils.copy(request.getInputStream(), writer, StandardCharsets.UTF_8); - String cleanStreamBoundary = - writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); + String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end") + 4); } @RequestMapping(value = {"/brms_dictionary/save_BRMSParam"}, method = {RequestMethod.POST}) - public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -124,26 +129,25 @@ public class BRMSDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - BRMSParamTemplate bRMSParamTemplateData; + BrmsParamTemplate bRMSParamTemplateData; String userId = null; if (fromAPI) { - bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), - BRMSParamTemplate.class); + bRMSParamTemplateData = + mapper.readValue(root.get(dictionaryFields).toString(), BrmsParamTemplate.class); userId = "API"; } else { - bRMSParamTemplateData = mapper.readValue( - root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); + bRMSParamTemplateData = + mapper.readValue(root.get("brmsParamDictionaryData").toString(), BrmsParamTemplate.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), + ruleName, BrmsParamTemplate.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + BrmsParamTemplate data = (BrmsParamTemplate) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { bRMSParamTemplateData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) @@ -164,8 +168,7 @@ public class BRMSDictionaryController { } else { commonClassDao.update(bRMSParamTemplateData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(BrmsParamTemplate.class)); } else { responseString = duplicateResponseString; } @@ -192,30 +195,32 @@ public class BRMSDictionaryController { } @RequestMapping(value = {"/brms_dictionary/remove_brmsParam"}, method = {RequestMethod.POST}) - public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, brmsParamDatas, BRMSParamTemplate.class); + utils.removeData(request, response, brmsParamDatas, BrmsParamTemplate.class); } - @RequestMapping(value = {"/get_BRMSDependencyDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSDependencyDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BRMSDependency.class); + utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BrmsDependency.class); } - @RequestMapping(value = {"/get_BRMSDependencyData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSDependencyData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, brmsDependencyDatas, BRMSDependency.class); + utils.getData(response, brmsDependencyDatas, BrmsDependency.class); } - @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, - method = {RequestMethod.POST}) - public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, method = {RequestMethod.POST}) + public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); @@ -224,46 +229,41 @@ public class BRMSDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - BRMSDependency brmsDependency; + BrmsDependency brmsDependency; String userId = null; if (fromAPI) { - brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), - BRMSDependency.class); + brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), BrmsDependency.class); userId = "API"; } else { - brmsDependency = mapper.readValue( - root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); + brmsDependency = + mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BrmsDependency.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), + dependencyName, BrmsDependency.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - BRMSDependency data = (BRMSDependency) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + BrmsDependency data = (BrmsDependency) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { brmsDependency.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != brmsDependency.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != brmsDependency.getId()))) { duplicateflag = true; } } LOGGER.audit("the userId from the onap portal is: " + userId); String responseString = null; - if (brmsDependency.getDependency() != null - && !("").equals(brmsDependency.getDependency().trim())) { + if (brmsDependency.getDependency() != null && !("").equals(brmsDependency.getDependency().trim())) { PEDependency dependency = null; try { - dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), - PEDependency.class); + dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), PEDependency.class); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID - + "wrong data given for BRMS PEDependency Dictionary : " - + brmsDependency.getDependency(), e); + + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency(), + e); } if (dependency == null) { responseString = errorMessage; @@ -277,8 +277,7 @@ public class BRMSDictionaryController { brmsDependency.setModifiedDate(new Date()); commonClassDao.update(brmsDependency); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(BrmsDependency.class)); } else { responseString = duplicateResponseString; } @@ -302,33 +301,34 @@ public class BRMSDictionaryController { return null; } - @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, - method = {RequestMethod.POST}) - public void removeBRMSDependencyDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, method = {RequestMethod.POST}) + public void removeBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, brmsDependencyDatas, BRMSDependency.class); + utils.removeData(request, response, brmsDependencyDatas, BrmsDependency.class); } - - @RequestMapping(value = {"/get_BRMSControllerDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSControllerDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, brmsControllerDatas, controllerName, BRMSController.class); + utils.getDataByEntity(response, brmsControllerDatas, controllerName, BrmsController.class); } - @RequestMapping(value = {"/get_BRMSControllerData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSControllerData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSControllerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, brmsControllerDatas, BRMSController.class); + utils.getData(response, brmsControllerDatas, BrmsController.class); } - @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, - method = {RequestMethod.POST}) - public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, method = {RequestMethod.POST}) + public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); @@ -336,45 +336,39 @@ public class BRMSDictionaryController { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - BRMSController brmsController; + BrmsController brmsController; String userId = null; if (fromAPI) { - brmsController = mapper.readValue(root.get(dictionaryFields).toString(), - BRMSController.class); + brmsController = mapper.readValue(root.get(dictionaryFields).toString(), BrmsController.class); userId = "API"; } else { - brmsController = mapper.readValue( - root.get("brmsControllerDictionaryData").toString(), BRMSController.class); + brmsController = + mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BrmsController.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - brmsController.getControllerName(), controllerName, BRMSController.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), + controllerName, BrmsController.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - BRMSController data = (BRMSController) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + BrmsController data = (BrmsController) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { brmsController.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != brmsController.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != brmsController.getId()))) { duplicateflag = true; } } String responseString = null; - if (brmsController.getController() != null - && !("").equals(brmsController.getController().trim())) { + if (brmsController.getController() != null && !("").equals(brmsController.getController().trim())) { PEDependency dependency = null; try { - dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), - PEDependency.class); + dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), PEDependency.class); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID - + "wrong data given for BRMS Controller Dictionary : " - + brmsController.getController(), e); + + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController(), e); } if (dependency == null) { responseString = errorMessage; @@ -388,8 +382,7 @@ public class BRMSDictionaryController { brmsController.setModifiedDate(new Date()); commonClassDao.update(brmsController); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); } else { responseString = duplicateResponseString; } @@ -412,21 +405,20 @@ public class BRMSDictionaryController { return null; } - @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, - method = {RequestMethod.POST}) - public void removeBRMSControllerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, method = {RequestMethod.POST}) + public void removeBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, brmsControllerDatas, BRMSController.class); + utils.removeData(request, response, brmsControllerDatas, BrmsController.class); } - public BRMSDependency getDependencyDataByID(String dependencyName) { - return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, + public BrmsDependency getDependencyDataByID(String dependencyName) { + return (BrmsDependency) commonClassDao.getEntityItem(BrmsDependency.class, BRMSDictionaryController.dependencyName, dependencyName); } - public BRMSController getControllerDataByID(String controllerName) { - return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, + public BrmsController getControllerDataByID(String controllerName) { + return (BrmsController) commonClassDao.getEntityItem(BrmsController.class, BRMSDictionaryController.controllerName, controllerName); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java index 2aec0cc0d..9ea956aa7 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -35,10 +38,10 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ClosedLoopD2Services; import org.onap.policy.rest.jpa.ClosedLoopSite; import org.onap.policy.rest.jpa.OnapName; -import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.PepOptions; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.jpa.VNFType; -import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VnfType; +import org.onap.policy.rest.jpa.VsclAction; import org.onap.policy.rest.jpa.VarbindDictionary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -51,9 +54,9 @@ import org.springframework.web.servlet.ModelAndView; public class ClosedLoopDictionaryController { private static CommonClassDao commonClassDao; - private static String vsclaction = "vsclaction"; + private static String vsclaction = "action"; private static String operation = "operation"; - private static String vnftype = "vnftype"; + private static String vnftype = "type"; private static String pepName = "pepName"; private static String varbindName = "varbindName"; private static String serviceName = "serviceName"; @@ -89,85 +92,108 @@ public class ClosedLoopDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_VSCLActionDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VSCLActionDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, vsclActionDatas, vsclaction, VSCLAction.class); + utils.getDataByEntity(response, vsclActionDatas, vsclaction, VsclAction.class); } - - @RequestMapping(value = {"/get_VSCLActionData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VSCLActionData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVSCLActionDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, vsclActionDatas, VSCLAction.class); + utils.getData(response, vsclActionDatas, VsclAction.class); } - @RequestMapping(value = {"/get_VNFTypeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VNFTypeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, vnfTypeDatas, vnftype, VNFType.class); + utils.getDataByEntity(response, vnfTypeDatas, vnftype, VnfType.class); } - @RequestMapping(value = {"/get_VNFTypeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VNFTypeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVNFTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, vnfTypeDatas, VNFType.class); + utils.getData(response, vnfTypeDatas, VnfType.class); } - @RequestMapping(value = {"/get_PEPOptionsDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PEPOptionsDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, pepOptionDatas, pepName, PEPOptions.class); + utils.getDataByEntity(response, pepOptionDatas, pepName, PepOptions.class); } - @RequestMapping(value = {"/get_PEPOptionsData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PEPOptionsData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPEPOptionsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, pepOptionDatas, PEPOptions.class); + utils.getData(response, pepOptionDatas, PepOptions.class); } - @RequestMapping(value = {"/get_VarbindDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VarbindDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVarbindDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, varbindDatas, varbindName, VarbindDictionary.class); } - @RequestMapping(value = {"/get_VarbindDictionaryData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VarbindDictionaryData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVarbindDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, varbindDatas, VarbindDictionary.class); } - @RequestMapping(value = {"/get_ClosedLoopServicesDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopServicesDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopDatas, serviceName, ClosedLoopD2Services.class); } - @RequestMapping(value = {"/get_ClosedLoopServicesData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopServicesData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, closedLoopDatas, ClosedLoopD2Services.class); } - @RequestMapping(value = {"/get_ClosedLoopSiteDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopSiteDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopSiteDatas, siteName, ClosedLoopSite.class); } - @RequestMapping(value = {"/get_ClosedLoopSiteData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopSiteData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -175,39 +201,34 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/save_vsclAction"}, method = {RequestMethod.POST}) - public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - VSCLAction vSCLAction; + VsclAction vSCLAction; String userId = null; if (fromAPI) { - vSCLAction = - mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); + vSCLAction = mapper.readValue(root.get(dictionaryFields).toString(), VsclAction.class); userId = "API"; } else { - vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), - VSCLAction.class); + vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), VsclAction.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(vSCLAction.getAction(), vsclaction, VsclAction.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - VSCLAction data = (VSCLAction) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + VsclAction data = (VsclAction) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { vSCLAction.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != vSCLAction.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != vSCLAction.getId()))) { duplicateflag = true; } } @@ -221,8 +242,7 @@ public class ClosedLoopDictionaryController { vSCLAction.setModifiedDate(new Date()); commonClassDao.update(vSCLAction); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(VsclAction.class)); } else { responseString = duplicateResponseString; } @@ -239,45 +259,40 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_VsclAction"}, method = {RequestMethod.POST}) - public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vsclActionDatas, OnapName.class); } @RequestMapping(value = {"/cl_dictionary/save_vnfType"}, method = {RequestMethod.POST}) - public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - VNFType vNFType; + VnfType vNFType; String userId = null; if (fromAPI) { - vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class); + vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VnfType.class); userId = "API"; } else { - vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), - VNFType.class); + vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VnfType.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), - vnftype, VNFType.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(vNFType.getType(), vnftype, VnfType.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - VNFType data = (VNFType) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + VnfType data = (VnfType) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { vNFType.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != vNFType.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != vNFType.getId()))) { duplicateflag = true; } } @@ -291,7 +306,7 @@ public class ClosedLoopDictionaryController { vNFType.setModifiedDate(new Date()); commonClassDao.update(vNFType); } - responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(VnfType.class)); } else { responseString = duplicateResponseString; } @@ -308,34 +323,29 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_vnfType"}, method = {RequestMethod.POST}) - public void removeVnfType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, vnfTypeDatas, VNFType.class); + utils.removeData(request, response, vnfTypeDatas, VnfType.class); } @RequestMapping(value = {"/cl_dictionary/save_pepOptions"}, method = {RequestMethod.POST}) - public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PEPOptions pEPOptions; + PepOptions pEPOptions; GridData gridData; String userId = null; if (fromAPI) { - pEPOptions = - mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); + pEPOptions = mapper.readValue(root.get(dictionaryFields).toString(), PepOptions.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); userId = "API"; } else { - pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), - PEPOptions.class); - gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), - GridData.class); + pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PepOptions.class); + gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); @@ -344,18 +354,16 @@ public class ClosedLoopDictionaryController { pEPOptions.setActions(utils.appendKeyValue(gridData.getAttributes(), ":#@", "=#@")); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), - pepName, PEPOptions.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PepOptions.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - PEPOptions data = (PEPOptions) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + PepOptions data = (PepOptions) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { pEPOptions.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != pEPOptions.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != pEPOptions.getId()))) { duplicateflag = true; } } @@ -369,8 +377,7 @@ public class ClosedLoopDictionaryController { pEPOptions.setModifiedDate(new Date()); commonClassDao.update(pEPOptions); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PepOptions.class)); } else { responseString = duplicateResponseString; } @@ -387,15 +394,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_pepOptions"}, method = {RequestMethod.POST}) - public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, pepOptionDatas, VNFType.class); + utils.removeData(request, response, pepOptionDatas, VnfType.class); } @RequestMapping(value = {"/cl_dictionary/save_service"}, method = {RequestMethod.POST}) - public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -405,29 +410,25 @@ public class ClosedLoopDictionaryController { ClosedLoopD2Services serviceData; String userId = null; if (fromAPI) { - serviceData = mapper.readValue(root.get(dictionaryFields).toString(), - ClosedLoopD2Services.class); + serviceData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class); userId = "API"; } else { - serviceData = - mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), - ClosedLoopD2Services.class); + serviceData = mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), + ClosedLoopD2Services.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, + ClosedLoopD2Services.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { serviceData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != serviceData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != serviceData.getId()))) { duplicateflag = true; } } @@ -441,8 +442,7 @@ public class ClosedLoopDictionaryController { serviceData.setModifiedDate(new Date()); commonClassDao.update(serviceData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); } else { responseString = duplicateResponseString; } @@ -458,15 +458,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_Service"}, method = {RequestMethod.POST}) - public void removeServiceType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, closedLoopDatas, VNFType.class); + utils.removeData(request, response, closedLoopDatas, VnfType.class); } @RequestMapping(value = {"/cl_dictionary/save_siteName"}, method = {RequestMethod.POST}) - public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -476,28 +474,24 @@ public class ClosedLoopDictionaryController { ClosedLoopSite siteData; String userId = null; if (fromAPI) { - siteData = mapper.readValue(root.get(dictionaryFields).toString(), - ClosedLoopSite.class); + siteData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class); userId = "API"; } else { - siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), - ClosedLoopSite.class); + siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), - siteName, ClosedLoopSite.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { siteData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != siteData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != siteData.getId()))) { duplicateflag = true; } } @@ -511,8 +505,7 @@ public class ClosedLoopDictionaryController { siteData.setModifiedDate(new Date()); commonClassDao.update(siteData); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); } else { responseString = duplicateResponseString; } @@ -528,15 +521,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_site"}, method = {RequestMethod.POST}) - public void removeSiteType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, closedLoopSiteDatas, VNFType.class); + utils.removeData(request, response, closedLoopSiteDatas, VnfType.class); } @RequestMapping(value = {"/cl_dictionary/save_varbind"}, method = {RequestMethod.POST}) - public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -546,28 +537,25 @@ public class ClosedLoopDictionaryController { VarbindDictionary varbindDictionary; String userId = null; if (fromAPI) { - varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), - VarbindDictionary.class); + varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class); userId = "API"; } else { - varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), - VarbindDictionary.class); + varbindDictionary = + mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), + varbindName, VarbindDictionary.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { varbindDictionary.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != varbindDictionary.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != varbindDictionary.getId()))) { duplicateflag = true; } } @@ -582,8 +570,7 @@ public class ClosedLoopDictionaryController { varbindDictionary.setModifiedDate(new Date()); commonClassDao.update(varbindDictionary); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); } else { responseString = duplicateResponseString; } @@ -599,9 +586,8 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_varbindDict"}, method = {RequestMethod.POST}) - public void removeVarbind(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, varbindDatas, VNFType.class); + utils.removeData(request, response, varbindDatas, VnfType.class); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java index c89d21e91..4b6492baa 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java @@ -23,12 +23,15 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.DecisionSettings; @@ -66,16 +69,18 @@ public class DecisionPolicyDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_SettingsDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SettingsDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, - HttpServletResponse response) { + public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, settingDatas, xacmlId, DecisionSettings.class); } - - @RequestMapping(value = {"/get_SettingsDictionaryData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SettingsDictionaryData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSettingsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -83,8 +88,8 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/decision_dictionary/save_Settings"}, method = {RequestMethod.POST}) - public ModelAndView saveSettingsDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -95,27 +100,24 @@ public class DecisionPolicyDictionaryController { String userId = null; if (fromAPI) { - decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), - DecisionSettings.class); + decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), DecisionSettings.class); userId = "API"; } else { - decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), - DecisionSettings.class); + decisionSettings = + mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { DecisionSettings data = (DecisionSettings) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { decisionSettings.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != decisionSettings.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != decisionSettings.getId()))) { duplicateflag = true; } } @@ -133,8 +135,7 @@ public class DecisionPolicyDictionaryController { decisionSettings.setModifiedDate(new Date()); commonClassDao.update(decisionSettings); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); } else { responseString = duplicateResponseString; } @@ -150,21 +151,23 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/settings_dictionary/remove_settings"}, method = {RequestMethod.POST}) - public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, settingDatas, DecisionSettings.class); } - @RequestMapping(value = {"/get_RainyDayDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RainyDayDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, - HttpServletResponse response) { + public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, rainDayDatas, bbID, RainyDayTreatments.class); } - @RequestMapping(value = {"/get_RainyDayDictionaryData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RainyDayDictionaryData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getRainyDayDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -172,8 +175,8 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/decision_dictionary/save_RainyDay"}, method = {RequestMethod.POST}) - public ModelAndView saveRainyDayDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -183,32 +186,26 @@ public class DecisionPolicyDictionaryController { RainyDayTreatments decisionRainyDay; TreatmentValues treatmentsData = null; if (fromAPI) { - decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), - RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), - TreatmentValues.class); + decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), TreatmentValues.class); } else { - decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(), - RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), - TreatmentValues.class); + decisionRainyDay = + mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class); } - decisionRainyDay.setTreatments( - utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); + decisionRainyDay.setTreatments(utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), - "bbid:workstep", RainyDayTreatments.class); + decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), "bbid:workstep", + RainyDayTreatments.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { decisionRainyDay.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != decisionRainyDay.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != decisionRainyDay.getId()))) { duplicateflag = true; } } @@ -219,8 +216,7 @@ public class DecisionPolicyDictionaryController { } else { commonClassDao.update(decisionRainyDay); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); } else { responseString = duplicateResponseString; } @@ -236,8 +232,7 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/decision_dictionary/remove_rainyDay"}, method = {RequestMethod.POST}) - public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, rainDayDatas, RainyDayTreatments.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java index 51c8a1d91..1645b0af9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; @@ -65,24 +68,27 @@ public class DescriptiveDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_DescriptiveScopeByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DescriptiveScopeByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, descriptiveDatas, dScopeName, DescriptiveScope.class); } - @RequestMapping(value = {"/get_DescriptiveScope"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DescriptiveScope"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDescriptiveDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, descriptiveDatas, DescriptiveScope.class); } - @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, - method = {RequestMethod.POST}) - public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, method = {RequestMethod.POST}) + public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -93,32 +99,27 @@ public class DescriptiveDictionaryController { GridData data; String userId = null; if (fromAPI) { - descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), - DescriptiveScope.class); + descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); userId = "API"; } else { descriptiveScope = - mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), - DescriptiveScope.class); - data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), - GridData.class); + mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); + data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); userId = root.get("userid").textValue(); } descriptiveScope.setSearch(utils.appendKeyValue(data.getAttributes(), "AND", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), dScopeName, + DescriptiveScope.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { DescriptiveScope data1 = (DescriptiveScope) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { descriptiveScope.setId(data1.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data1.getId() != descriptiveScope.getId()))) { + || (request.getParameter(operation) == null && (data1.getId() != descriptiveScope.getId()))) { duplicateflag = true; } } @@ -132,8 +133,7 @@ public class DescriptiveDictionaryController { descriptiveScope.setModifiedDate(new Date()); commonClassDao.update(descriptiveScope); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); } else { responseString = "Duplicate"; } @@ -148,10 +148,9 @@ public class DescriptiveDictionaryController { return null; } - @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, - method = {RequestMethod.POST}) - public void removeDescriptiveDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, method = {RequestMethod.POST}) + public void removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, descriptiveDatas, DescriptiveScope.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java index 94275e7c1..2c0278ed5 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -52,7 +55,7 @@ public class DictionaryController { private static String operation = "operation"; private static String dictionaryFields = "dictionaryFields"; private static String duplicateResponseString = "Duplicate"; - private static String onapName = "onapName"; + private static String onapName = "name"; private static String attributeDatas = "attributeDictionaryDatas"; private static String onapNameDatas = "onapNameDictionaryDatas"; @@ -69,7 +72,9 @@ public class DictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_AttributeDatabyAttributeName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AttributeDatabyAttributeName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -77,7 +82,9 @@ public class DictionaryController { } // Attribute Dictionary - @RequestMapping(value = "/get_AttributeData", method = RequestMethod.GET, + @RequestMapping( + value = "/get_AttributeData", + method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public void getAttributeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -85,8 +92,8 @@ public class DictionaryController { } @RequestMapping(value = {"/attribute_dictionary/save_attribute"}, method = {RequestMethod.POST}) - public ModelAndView saveAttributeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -97,38 +104,33 @@ public class DictionaryController { AttributeValues attributeValueData = null; String userId = null; if (fromAPI) { - attributeData = - mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); - attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), - AttributeValues.class); + attributeData = mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); + attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class); userId = "API"; } else { - attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), - Attribute.class); - attributeValueData = mapper.readValue( - root.get("attributeDictionaryData").toString(), AttributeValues.class); + attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); + attributeValueData = + mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { Attribute data = (Attribute) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { attributeData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != attributeData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != attributeData.getId()))) { duplicateflag = true; } } if (attributeValueData.getUserDataTypeValues() != null && !attributeValueData.getUserDataTypeValues().isEmpty()) { - attributeData.setAttributeValue(utils.appendKey( - attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); + attributeData.setAttributeValue( + utils.appendKey(attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); } if (attributeData.getDatatypeBean().getShortName() != null) { @@ -162,16 +164,16 @@ public class DictionaryController { return null; } - @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, - method = {RequestMethod.POST}) - public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, method = {RequestMethod.POST}) + public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, attributeDatas, Attribute.class); } // OnapName Dictionary - @RequestMapping(value = {"/get_OnapNameDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_OnapNameDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response) { LOGGER.info("get_OnapNameDataByName is called"); @@ -179,7 +181,9 @@ public class DictionaryController { utils.getDataByEntity(response, onapNameDatas, onapName, OnapName.class); } - @RequestMapping(value = {"/get_OnapNameData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_OnapNameData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getOnapNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -201,24 +205,21 @@ public class DictionaryController { onapData = mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class); userId = "API"; } else { - onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), - OnapName.class); + onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), - onapName, OnapName.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), onapName, OnapName.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { OnapName data = (OnapName) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -248,8 +249,7 @@ public class DictionaryController { } @RequestMapping(value = {"/onap_dictionary/remove_onap"}, method = {RequestMethod.POST}) - public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, onapNameDatas, OnapName.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java index b42731d61..029582213 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -21,16 +21,20 @@ package org.onap.policy.pap.xacml.rest.controller; import au.com.bytecode.opencsv.CSVReader; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.compress.utils.IOUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -40,9 +44,9 @@ import org.onap.policy.rest.jpa.ActionList; import org.onap.policy.rest.jpa.ActionPolicyDict; import org.onap.policy.rest.jpa.AddressGroup; import org.onap.policy.rest.jpa.Attribute; -import org.onap.policy.rest.jpa.BRMSController; -import org.onap.policy.rest.jpa.BRMSDependency; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsController; +import org.onap.policy.rest.jpa.BrmsDependency; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.Category; import org.onap.policy.rest.jpa.ClosedLoopD2Services; import org.onap.policy.rest.jpa.ClosedLoopSite; @@ -52,15 +56,15 @@ import org.onap.policy.rest.jpa.DescriptiveScope; import org.onap.policy.rest.jpa.GroupServiceList; import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.OnapName; -import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.PepOptions; import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.ProtocolList; import org.onap.policy.rest.jpa.SecurityZone; import org.onap.policy.rest.jpa.ServiceList; import org.onap.policy.rest.jpa.TermList; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.jpa.VNFType; -import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VnfType; +import org.onap.policy.rest.jpa.VsclAction; import org.onap.policy.rest.jpa.VarbindDictionary; import org.onap.policy.rest.jpa.Zone; import org.springframework.beans.factory.annotation.Autowired; @@ -68,7 +72,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; - @Controller public class DictionaryImportController { private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); @@ -92,8 +95,7 @@ public class DictionaryImportController { } @RequestMapping(value = {"/dictionary/import_dictionary"}, method = {RequestMethod.POST}) - public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String userId = request.getParameter("userId"); @@ -211,7 +213,7 @@ public class DictionaryImportController { for (int j = 0; j < rows.length; j++) { if ("onap_name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Onap Name".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setOnapName(rows[j]); + attribute.setName(rows[j]); } if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); @@ -250,10 +252,10 @@ public class DictionaryImportController { attribute.setEnumValues(rows[j]); } if ("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setRef_attributes(rows[j]); + attribute.setRefAttributes(rows[j]); } if ("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setSub_attributes(rows[j]); + attribute.setSubAttributes(rows[j]); } if ("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAnnotation(rows[j]); @@ -273,8 +275,7 @@ public class DictionaryImportController { String[] rows = dictSheet.get(i); for (int j = 0; j < rows.length; j++) { if ("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) - || "Optimization Service Model" - .equalsIgnoreCase(dictSheet.get(0)[j])) { + || "Optimization Service Model".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setModelName(rows[j]); } if ("version".equalsIgnoreCase(dictSheet.get(0)[j]) @@ -294,10 +295,10 @@ public class DictionaryImportController { attribute.setEnumValues(rows[j]); } if ("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setRef_attributes(rows[j]); + attribute.setRefAttributes(rows[j]); } if ("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setSub_attributes(rows[j]); + attribute.setSubAttributes(rows[j]); } if ("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAnnotation(rows[j]); @@ -310,7 +311,7 @@ public class DictionaryImportController { if (dictionaryName.startsWith("VNFType")) { for (int i = 1; i < dictSheet.size(); i++) { - VNFType attribute = new VNFType(); + VnfType attribute = new VnfType(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); @@ -319,7 +320,7 @@ public class DictionaryImportController { for (int j = 0; j < rows.length; j++) { if ("vnf_type".equalsIgnoreCase(dictSheet.get(0)[j]) || "VNF Type".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setVnftype(rows[j]); + attribute.setType(rows[j]); } if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); @@ -330,7 +331,7 @@ public class DictionaryImportController { } if (dictionaryName.startsWith("VSCLAction")) { for (int i = 1; i < dictSheet.size(); i++) { - VSCLAction attribute = new VSCLAction(); + VsclAction attribute = new VsclAction(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); @@ -339,7 +340,7 @@ public class DictionaryImportController { for (int j = 0; j < rows.length; j++) { if ("vscl_action".equalsIgnoreCase(dictSheet.get(0)[j]) || "VSCL Action".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setVsclaction(rows[j]); + attribute.setAction(rows[j]); } if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); @@ -388,9 +389,9 @@ public class DictionaryImportController { commonClassDao.save(attribute); } } - if (dictionaryName.startsWith("PEPOptions")) { + if (dictionaryName.startsWith("PepOptions")) { for (int i = 1; i < dictSheet.size(); i++) { - PEPOptions attribute = new PEPOptions(); + PepOptions attribute = new PepOptions(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); @@ -430,7 +431,7 @@ public class DictionaryImportController { } if ("varbind_oid".equalsIgnoreCase(dictSheet.get(0)[j]) || "Varbind OID".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setVarbindOID(rows[j]); + attribute.setVarbindOid(rows[j]); } } commonClassDao.save(attribute); @@ -438,7 +439,7 @@ public class DictionaryImportController { } if (dictionaryName.startsWith("BRMSParamDictionary")) { for (int i = 1; i < dictSheet.size(); i++) { - BRMSParamTemplate attribute = new BRMSParamTemplate(); + BrmsParamTemplate attribute = new BrmsParamTemplate(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); @@ -460,7 +461,7 @@ public class DictionaryImportController { } if (dictionaryName.startsWith("BRMSControllerDictionary")) { for (int i = 1; i < dictSheet.size(); i++) { - BRMSController attribute = new BRMSController(); + BrmsController attribute = new BrmsController(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); @@ -482,7 +483,7 @@ public class DictionaryImportController { } if (dictionaryName.startsWith("BRMSDependencyDictionary")) { for (int i = 1; i < dictSheet.size(); i++) { - BRMSDependency attribute = new BRMSDependency(); + BrmsDependency attribute = new BrmsDependency(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); @@ -614,7 +615,7 @@ public class DictionaryImportController { } if ("serviceTrasProtocol".equalsIgnoreCase(dictSheet.get(0)[j]) || "Transport Protocol".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setServiceTransProtocol(rows[j]); + attribute.setServiceTransportProtocol(rows[j]); } if ("serviceAppProtocol".equalsIgnoreCase(dictSheet.get(0)[j]) || "APP Protocol".equalsIgnoreCase(dictSheet.get(0)[j])) { @@ -716,19 +717,19 @@ public class DictionaryImportController { } if ("fromZone".equalsIgnoreCase(dictSheet.get(0)[j]) || "From Zone".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setFromZones(rows[j]); + attribute.setFromZone(rows[j]); } if ("toZone".equalsIgnoreCase(dictSheet.get(0)[j]) || "To Zone".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setToZones(rows[j]); + attribute.setToZone(rows[j]); } if ("srcIPList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Source-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setSrcIPList(rows[j]); + attribute.setSrcIpList(rows[j]); } if ("destIPList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Destination-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])) { - attribute.setDestIPList(rows[j]); + attribute.setDestIpList(rows[j]); } if ("srcPortList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Source-Port-List".equalsIgnoreCase(dictSheet.get(0)[j])) { @@ -800,7 +801,7 @@ public class DictionaryImportController { case VSCLAction: case ClosedLoopService: case ClosedLoopSite: - case PEPOptions: + case PepOptions: case VarbindDictionary: case BRMSParamDictionary: case BRMSControllerDictionary: diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java index 7cf12043c..3c3cbac30 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java @@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.PrintWriter; import java.net.UnknownHostException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.jboss.netty.handler.ipfilter.CIDR; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -39,8 +42,8 @@ import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionList; import org.onap.policy.rest.jpa.AddressGroup; -import org.onap.policy.rest.jpa.FWTag; -import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.FwTag; +import org.onap.policy.rest.jpa.FwTagPicker; import org.onap.policy.rest.jpa.FirewallDictionaryList; import org.onap.policy.rest.jpa.GroupServiceList; import org.onap.policy.rest.jpa.PortList; @@ -58,7 +61,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; - @Controller public class FirewallDictionaryController { @@ -95,7 +97,6 @@ public class FirewallDictionaryController { private static String fwTagPickerDatas = "fwTagPickerDictionaryDatas"; private static String fwTagDatas = "fwTagDictionaryDatas"; - @Autowired public FirewallDictionaryController(CommonClassDao commonClassDao) { FirewallDictionaryController.commonClassDao = commonClassDao; @@ -113,14 +114,18 @@ public class FirewallDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_PrefixListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PrefixListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPrefixListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, pfListDatas, prefixListName, PrefixList.class); } - @RequestMapping(value = {"/get_PrefixListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PrefixListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPrefixListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -128,8 +133,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_prefixList"}, method = {RequestMethod.POST}) - public ModelAndView savePrefixListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -138,25 +143,21 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PrefixList prefixList; if (fromAPI) { - prefixList = - mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); + prefixList = mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); } else { - prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), - PrefixList.class); + prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - prefixList.getPrefixListName(), prefixListName, PrefixList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), + prefixListName, PrefixList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PrefixList data = (PrefixList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { prefixList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != prefixList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != prefixList.getId()))) { duplicateflag = true; } } @@ -167,8 +168,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(prefixList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); } else { responseString = duplicateResponseString; } @@ -191,15 +191,14 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/validate_prefixList"}, method = {RequestMethod.POST}) - public void validatePrefixListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void validatePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PrefixList prefixList = mapper - .readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + PrefixList prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); String responseValidation = successMessage; try { CIDR.newCIDR(prefixList.getPrefixListValue()); @@ -219,7 +218,9 @@ public class FirewallDictionaryController { } } - @RequestMapping(value = {"/get_PortListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PortListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPortListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -227,8 +228,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_portName"}, method = {RequestMethod.POST}) - public ModelAndView savePortListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -239,21 +240,18 @@ public class FirewallDictionaryController { if (fromAPI) { portList = mapper.readValue(root.get(dictionaryFields).toString(), PortList.class); } else { - portList = mapper.readValue(root.get("portListDictionaryData").toString(), - PortList.class); + portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), - "portName", PortList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PortList data = (PortList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { portList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != portList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != portList.getId()))) { duplicateflag = true; } } @@ -280,20 +278,23 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_PortList"}, method = {RequestMethod.POST}) - public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, portListDatas, PortList.class); } - @RequestMapping(value = {"/get_ProtocolListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ProtocolListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getProtocolListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value = {"/get_ProtocolListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ProtocolListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -301,8 +302,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_protocolList"}, method = {RequestMethod.POST}) - public ModelAndView saveProtocolListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -311,24 +312,20 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ProtocolList protocolList; if (fromAPI) { - protocolList = - mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); + protocolList = mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); } else { - protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), - ProtocolList.class); + protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - protocolList.getProtocolName(), protocolName, ProtocolList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), + protocolName, ProtocolList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ProtocolList data = (ProtocolList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { protocolList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != protocolList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != protocolList.getId()))) { duplicateflag = true; } } @@ -339,8 +336,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(protocolList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); } else { responseString = duplicateResponseString; } @@ -356,20 +352,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_protocol"}, method = {RequestMethod.POST}) - public void removeProtocolListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value = {"/get_AddressGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AddressGroupDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, addressGroupDatas, "name", AddressGroup.class); } - @RequestMapping(value = {"/get_AddressGroupData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AddressGroupData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getAddressGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -377,8 +377,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_addressGroup"}, method = {RequestMethod.POST}) - public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -388,32 +388,27 @@ public class FirewallDictionaryController { AddressGroup addressGroup; GridData gridData; if (fromAPI) { - addressGroup = - mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); + addressGroup = mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), - AddressGroup.class); - gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), - GridData.class); + addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class); + gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class); } if (!addressGroup.getGroupName().startsWith(groupNameStart)) { String groupName = groupNameStart + addressGroup.getGroupName(); addressGroup.setGroupName(groupName); } addressGroup.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { AddressGroup data = (AddressGroup) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { addressGroup.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != addressGroup.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != addressGroup.getId()))) { duplicateflag = true; } } @@ -424,8 +419,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(addressGroup); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); } else { responseString = duplicateResponseString; } @@ -441,20 +435,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_AddressGroup"}, method = {RequestMethod.POST}) - public void removeAddressGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value = {"/get_ActionListDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ActionListDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getActionListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, actionListDatas, "actionName", ActionList.class); } - @RequestMapping(value = {"/get_ActionListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ActionListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getActionListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -462,8 +460,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_ActionList"}, method = {RequestMethod.POST}) - public ModelAndView saveActionListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -472,24 +470,20 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ActionList actionList; if (fromAPI) { - actionList = - mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); + actionList = mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); } else { - actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), - ActionList.class); + actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - actionList.getActionName(), "actionName", ActionList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ActionList data = (ActionList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { actionList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != actionList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != actionList.getId()))) { duplicateflag = true; } } @@ -500,8 +494,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(actionList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); } else { responseString = duplicateResponseString; } @@ -523,14 +516,18 @@ public class FirewallDictionaryController { utils.removeData(request, response, actionListDatas, ActionList.class); } - @RequestMapping(value = {"/get_ServiceGroupData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceGroupData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value = {"/get_ServiceGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceGroupDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -538,8 +535,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_serviceGroup"}, method = {RequestMethod.POST}) - public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -549,32 +546,28 @@ public class FirewallDictionaryController { GroupServiceList groupServiceList; GridData gridData; if (fromAPI) { - groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), - GroupServiceList.class); + groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), GroupServiceList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - groupServiceList = mapper.readValue( - root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); - gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), - GridData.class); + groupServiceList = + mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); + gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); } if (!groupServiceList.getGroupName().startsWith(groupNameStart)) { String groupName = groupNameStart + groupServiceList.getGroupName(); groupServiceList.setGroupName(groupName); } groupServiceList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - groupServiceList.getGroupName(), "name", GroupServiceList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { GroupServiceList data = (GroupServiceList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { groupServiceList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != groupServiceList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != groupServiceList.getId()))) { duplicateflag = true; } } @@ -585,8 +578,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(groupServiceList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); } else { responseString = duplicateResponseString; } @@ -602,20 +594,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_serviceGroup"}, method = {RequestMethod.POST}) - public void removeServiceGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value = {"/get_SecurityZoneDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SecurityZoneDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, securityZoneDatas, zoneName, SecurityZone.class); } - @RequestMapping(value = {"/get_SecurityZoneData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SecurityZoneData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSecurityZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -623,8 +619,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_securityZone"}, method = {RequestMethod.POST}) - public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -633,24 +629,20 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); SecurityZone securityZone; if (fromAPI) { - securityZone = - mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); + securityZone = mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); } else { - securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), - SecurityZone.class); + securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); } - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { SecurityZone data = (SecurityZone) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { securityZone.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != securityZone.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != securityZone.getId()))) { duplicateflag = true; } } @@ -661,8 +653,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(securityZone); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); } else { responseString = duplicateResponseString; } @@ -678,21 +669,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_securityZone"}, method = {RequestMethod.POST}) - public void removeSecurityZoneDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, securityZoneDatas, SecurityZone.class); } - - @RequestMapping(value = {"/get_ServiceListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceListDatas, ServiceList.class); } - @RequestMapping(value = {"/get_ServiceListDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceListDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -700,8 +694,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_serviceList"}, method = {RequestMethod.POST}) - public ModelAndView saveServiceListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -711,33 +705,27 @@ public class FirewallDictionaryController { ServiceList serviceList; GridData serviceListGridData; if (fromAPI) { - serviceList = - mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); - serviceListGridData = - mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); + serviceList = mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); + serviceListGridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), - ServiceList.class); - serviceListGridData = mapper.readValue( - root.get("serviceListDictionaryData").toString(), GridData.class); + serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); + serviceListGridData = + mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); } - serviceList.setServiceTransProtocol( - utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); - serviceList.setServiceAppProtocol( - utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); + serviceList + .setServiceTransportProtocol(utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); + serviceList.setServiceAppProtocol(utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); serviceList.setServiceType("SERVICE"); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - serviceList.getServiceName(), serviceName, ServiceList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ServiceList data = (ServiceList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { serviceList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != serviceList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != serviceList.getId()))) { duplicateflag = true; } } @@ -748,8 +736,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(serviceList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); } else { responseString = duplicateResponseString; } @@ -765,20 +752,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_serviceList"}, method = {RequestMethod.POST}) - public void removeServiceListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeServiceListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceListDatas, ServiceList.class); } - @RequestMapping(value = {"/get_ZoneData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ZoneData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, zoneDatas, Zone.class); } - @RequestMapping(value = {"/get_ZoneDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ZoneDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -800,18 +791,15 @@ public class FirewallDictionaryController { } else { zone = mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); } - List<Object> duplicateData = - commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { Zone data = (Zone) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { zone.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != zone.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != zone.getId()))) { duplicateflag = true; } } @@ -838,20 +826,23 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_zone"}, method = {RequestMethod.POST}) - public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, zoneDatas, Zone.class); } - @RequestMapping(value = {"/get_TermListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TermListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTermListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, termListDictDatas, termName, TermList.class); } - @RequestMapping(value = {"/get_TermListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TermListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTermListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -859,8 +850,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_termList"}, method = {RequestMethod.POST}) - public ModelAndView saveTermListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -872,41 +863,33 @@ public class FirewallDictionaryController { String userId = null; if (fromAPI) { termList = mapper.readValue(root.get(dictionaryFields).toString(), TermList.class); - termListDatas = - mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); + termListDatas = mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); userId = "API"; } else { - termList = mapper.readValue(root.get("termListDictionaryData").toString(), - TermList.class); - termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), - TermListData.class); + termList = mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); + termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); userId = root.get(userid).textValue(); } - termList.setFromZones(utils.appendKey(termListDatas.getFromZoneDatas(), option, ",")); - termList.setToZones(utils.appendKey(termListDatas.getToZoneDatas(), option, ",")); - termList.setSrcIPList(utils.appendKey(termListDatas.getSourceListDatas(), option, ",")); - termList.setDestIPList( - utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); - termList.setSrcPortList( - utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); - termList.setDestPortList( - utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); + termList.setFromZone(utils.appendKey(termListDatas.getFromZoneDatas(), option, ",")); + termList.setToZone(utils.appendKey(termListDatas.getToZoneDatas(), option, ",")); + termList.setSrcIpList(utils.appendKey(termListDatas.getSourceListDatas(), option, ",")); + termList.setDestIpList(utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); + termList.setSrcPortList(utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); + termList.setDestPortList(utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); termList.setAction(utils.appendKey(termListDatas.getActionListDatas(), option, ",")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), - termName, TermList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { TermList data = (TermList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { termList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != termList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != termList.getId()))) { duplicateflag = true; } } @@ -936,22 +919,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_termList"}, method = {RequestMethod.POST}) - public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, termListDictDatas, TermList.class); } // ParentList Dictionary Data - @RequestMapping(value = {"/get_FWDictionaryListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_FWDictionaryListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, fwDictListDatas, "parentItemName", - FirewallDictionaryList.class); + utils.getDataByEntity(response, fwDictListDatas, "parentItemName", FirewallDictionaryList.class); } - @RequestMapping(value = {"/get_FWDictionaryListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_FWDictionaryListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getFWDictionaryListEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -959,8 +944,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_FWDictionaryList"}, method = {RequestMethod.POST}) - public ModelAndView saveFWDictionaryList(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -970,31 +955,27 @@ public class FirewallDictionaryController { FirewallDictionaryList fwDictList; GridData gridData; if (fromAPI) { - fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), - FirewallDictionaryList.class); + fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), FirewallDictionaryList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), - FirewallDictionaryList.class); - gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), - GridData.class); + fwDictList = + mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); + gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); } fwDictList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); fwDictList.setAddressList(utils.appendKey(gridData.getAlAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), + "parentItemName", FirewallDictionaryList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { FirewallDictionaryList data = (FirewallDictionaryList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { fwDictList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != fwDictList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != fwDictList.getId()))) { duplicateflag = true; } } @@ -1005,8 +986,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(fwDictList); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); } else { responseString = duplicateResponseString; } @@ -1021,69 +1001,65 @@ public class FirewallDictionaryController { return null; } - @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, - method = {RequestMethod.POST}) - public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) - throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, method = {RequestMethod.POST}) + public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwDictListDatas, FirewallDictionaryList.class); } - - @RequestMapping(value = {"/get_TagPickerNameByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagPickerNameByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagPickerNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FWTagPicker.class); + utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FwTagPicker.class); } - @RequestMapping(value = {"/get_TagPickerListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagPickerListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagPickerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, fwTagPickerDatas, FWTagPicker.class); + utils.getData(response, fwTagPickerDatas, FwTagPicker.class); } @RequestMapping(value = {"/fw_dictionary/save_fwTagPicker"}, method = {RequestMethod.POST}) - public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - FWTagPicker fwTagPicker; + FwTagPicker fwTagPicker; TagGridValues data; String userId = ""; if (fromAPI) { - fwTagPicker = - mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); + fwTagPicker = mapper.readValue(root.get(dictionaryFields).toString(), FwTagPicker.class); data = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; } else { - fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), - FWTagPicker.class); - data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), - TagGridValues.class); + fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FwTagPicker.class); + data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); userId = root.get(userid).textValue(); } fwTagPicker.setTagValues(utils.appendKeyValue(data.getTags(), "#", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), + tagPickerName, FwTagPicker.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - FWTagPicker data1 = (FWTagPicker) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + FwTagPicker data1 = (FwTagPicker) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { fwTagPicker.setId(data1.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data1.getId() != fwTagPicker.getId()))) { + || (request.getParameter(operation) == null && (data1.getId() != fwTagPicker.getId()))) { duplicateflag = true; } } @@ -1097,8 +1073,7 @@ public class FirewallDictionaryController { fwTagPicker.setModifiedDate(new Date()); commonClassDao.update(fwTagPicker); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(FwTagPicker.class)); } else { responseString = duplicateResponseString; } @@ -1114,65 +1089,64 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_tagPicker"}, method = {RequestMethod.POST}) - public void removeFirewallTagPickerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, fwTagPickerDatas, FWTagPicker.class); + utils.removeData(request, response, fwTagPickerDatas, FwTagPicker.class); } - @RequestMapping(value = {"/get_TagListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, fwTagDatas, FWTag.class); + utils.getData(response, fwTagDatas, FwTag.class); } - @RequestMapping(value = {"/get_TagNameByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagNameByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, fwTagDatas, "fwTagName", FWTag.class); + utils.getDataByEntity(response, fwTagDatas, "fwTagName", FwTag.class); } - @RequestMapping(value = {"/fw_dictionary/save_fwTag"}, method = {RequestMethod.POST}) - public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - FWTag fwTag; + FwTag fwTag; TagGridValues tagGridValues; String userId = ""; if (fromAPI) { - fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), - TagGridValues.class); + fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FwTag.class); + tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; } else { - fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), - TagGridValues.class); + fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FwTag.class); + tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); userId = root.get(userid).textValue(); } fwTag.setTagValues(utils.appendKey(tagGridValues.getTags(), "tags", ",")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), - "fwTagName", FWTag.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FwTag.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { - FWTag data = (FWTag) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + FwTag data = (FwTag) duplicateData.get(0); + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { fwTag.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != fwTag.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != fwTag.getId()))) { duplicateflag = true; } } @@ -1186,7 +1160,7 @@ public class FirewallDictionaryController { fwTag.setModifiedDate(new Date()); commonClassDao.update(fwTag); } - responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(FwTag.class)); } else { responseString = duplicateResponseString; } @@ -1202,10 +1176,10 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_tagList"}, method = {RequestMethod.POST}) - public void removeFirewallTagDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, fwTagDatas, FWTag.class); + utils.removeData(request, response, fwTagDatas, FwTag.class); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index ee274d2a7..566ac1447 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -32,8 +33,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -42,7 +45,7 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.pap.xacml.rest.util.JsonMessage; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.DCAEuuid; +import org.onap.policy.rest.jpa.DcaeUuid; import org.onap.policy.rest.jpa.DictionaryData; import org.onap.policy.rest.jpa.MicroServiceAttribute; import org.onap.policy.rest.jpa.MicroServiceConfigName; @@ -51,8 +54,8 @@ import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults; import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; @@ -72,11 +75,9 @@ public class MicroServiceDictionaryController { private static String getDictionary = "getDictionary"; private static String errorMsg = "error"; private static String dictionaryDBQuery = "dictionaryDBQuery"; - private LinkedHashMap<String, MSAttributeObject> classMap; + private LinkedHashMap<String, MsAttributeObject> classMap; private List<String> modelList = new ArrayList<>(); - private static String apiflag = "apiflag"; private static String dictionaryFields = "dictionaryFields"; - private static String update = "update"; private static String duplicateResponseString = "Duplicate"; private static String microServiceModelsDictionaryDatas = "microServiceModelsDictionaryDatas"; private static String modelName = "modelName"; @@ -108,22 +109,26 @@ public class MicroServiceDictionaryController { MicroServiceDictionaryController.commonClassDao = commonClassDao; } - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); private MicroServiceModels newModel; - @RequestMapping(value = {"/get_DCAEUUIDDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DCAEUUIDDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDCAEUUIDDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, dcaeUUIDDatas, "name", DCAEuuid.class); + utils.getDataByEntity(response, dcaeUUIDDatas, "name", DcaeUuid.class); } - @RequestMapping(value = {"/get_DCAEUUIDData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DCAEUUIDData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDCAEUUIDDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getData(response, dcaeUUIDDatas, DCAEuuid.class); + utils.getData(response, dcaeUUIDDatas, DcaeUuid.class); } @RequestMapping(value = {"/ms_dictionary/save_dcaeUUID"}, method = {RequestMethod.POST}) @@ -135,17 +140,17 @@ public class MicroServiceDictionaryController { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - DCAEuuid dCAEuuid; + DcaeUuid dCAEuuid; if (fromAPI) { - dCAEuuid = mapper.readValue(root.get(dictionaryFields).toString(), DCAEuuid.class); + dCAEuuid = mapper.readValue(root.get(dictionaryFields).toString(), DcaeUuid.class); } else { - dCAEuuid = mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class); + dCAEuuid = mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DcaeUuid.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DcaeUuid.class); boolean duplicateflag = false; if (duplicateData != null && !duplicateData.isEmpty()) { - DCAEuuid data = (DCAEuuid) duplicateData.get(0); + DcaeUuid data = (DcaeUuid) duplicateData.get(0); if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { dCAEuuid.setId(data.getId()); } else if ((request.getParameter(operation) != null @@ -161,7 +166,7 @@ public class MicroServiceDictionaryController { } else { commonClassDao.update(dCAEuuid); } - responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(DcaeUuid.class)); } else { responseString = duplicateResponseString; } @@ -179,24 +184,30 @@ public class MicroServiceDictionaryController { @RequestMapping(value = {"/ms_dictionary/remove_dcaeuuid"}, method = {RequestMethod.POST}) public void removeDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.removeData(request, response, dcaeUUIDDatas, DCAEuuid.class); + utils.removeData(request, response, dcaeUUIDDatas, DcaeUuid.class); } - @RequestMapping(value = {"/get_MicroServiceConfigNameDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceConfigNameDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceConfigNameDatas, "name", MicroServiceConfigName.class); } - @RequestMapping(value = {"/get_MicroServiceConfigNameData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceConfigNameData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceConfigNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, microServiceConfigNameDatas, MicroServiceConfigName.class); } - @RequestMapping(value = {"/get_MicroServiceDictData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceDictData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceDictNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -330,14 +341,18 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceConfigNameDatas, MicroServiceConfigName.class); } - @RequestMapping(value = {"/get_MicroServiceLocationDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceLocationDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceLocationDatas, "name", MicroServiceLocation.class); } - @RequestMapping(value = {"/get_MicroServiceLocationData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceLocationData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceLocationDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -405,14 +420,18 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceLocationDatas, MicroServiceLocation.class); } - @RequestMapping(value = {"/get_MicroServiceAttributeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceAttributeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceAttributeDatas, "name", MicroServiceAttribute.class); } - @RequestMapping(value = {"/get_MicroServiceAttributeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceAttributeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceAttributeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -483,15 +502,18 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceAttributeDatas, MicroServiceAttribute.class); } - - @RequestMapping(value = {"/get_MicroServiceModelsDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceModelsDictionaryDatas, modelName, MicroServiceModels.class); } - @RequestMapping(value = {"/get_MicroServiceModelsDataByVersion"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataByVersion"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request, HttpServletResponse response) { @@ -517,14 +539,18 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value = {"/get_MicroServiceModelsData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, microServiceModelsDictionaryDatas, MicroServiceModels.class); } - @RequestMapping(value = {"/get_MicroServiceModelsDataServiceVersion"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataServiceVersion"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletResponse response) { try { @@ -552,7 +578,9 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value = {"/get_MicroServiceModelsDataByClass"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataByClass"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryClassEntityData(HttpServletResponse response) { try { @@ -622,15 +650,15 @@ public class MicroServiceDictionaryController { Set<String> keys = jsonObject.keySet(); for (String key : keys) { String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class); classMap.put(key, msAttributeObject); } userId = root.get("userid").textValue(); - MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); + MsAttributeObject mainClass = classMap.get(this.newModel.getModelName()); this.newModel.setDependency("[]"); String value = new Gson().toJson(mainClass.getSubClass()); - this.newModel.setSub_attributes(value); + this.newModel.setSubAttributes(value); String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", ""); int equalsIndexForAttributes = attributes.indexOf('='); String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1); @@ -638,7 +666,7 @@ public class MicroServiceDictionaryController { String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); int equalsIndex = refAttributes.indexOf("="); String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1); - this.newModel.setRef_attributes(refAttributesAfterFirstEquals); + this.newModel.setRefAttributes(refAttributesAfterFirstEquals); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); this.newModel .setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); @@ -675,7 +703,7 @@ public class MicroServiceDictionaryController { Set<String> keys = jsonObject.keySet(); for (String key : keys) { String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class); classMap.put(key, msAttributeObject); } } @@ -685,10 +713,10 @@ public class MicroServiceDictionaryController { } } microServiceModels.setAttributes(this.newModel.getAttributes()); - microServiceModels.setRef_attributes(this.newModel.getRef_attributes()); + microServiceModels.setRefAttributes(this.newModel.getRefAttributes()); microServiceModels.setDependency(this.newModel.getDependency()); microServiceModels.setModelName(this.newModel.getModelName()); - microServiceModels.setSub_attributes(this.newModel.getSub_attributes()); + microServiceModels.setSubAttributes(this.newModel.getSubAttributes()); microServiceModels.setVersion(this.newModel.getVersion()); microServiceModels.setEnumValues(this.newModel.getEnumValues()); microServiceModels.setAnnotation(this.newModel.getAnnotation()); @@ -741,11 +769,11 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceModelsDictionaryDatas, MicroServiceModels.class); } - private void addValuesToNewModel(HashMap<String, MSAttributeObject> classMap) { + private void addValuesToNewModel(HashMap<String, MsAttributeObject> classMap) { // Loop through the classmap and pull out the required info for the new file. String subAttribute = null; - MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); + MsAttributeObject mainClass = classMap.get(this.newModel.getModelName()); if (mainClass != null) { String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "}, @@ -753,7 +781,7 @@ public class MicroServiceDictionaryController { ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(","))); dependency = getFullDependencyList(dependency); for (String element : dependency) { - MSAttributeObject temp = classMap.get(element); + MsAttributeObject temp = classMap.get(element); if (temp != null) { mainClass.addAllRefAttribute(temp.getRefAttribute()); mainClass.addAllAttribute(temp.getAttribute()); @@ -770,9 +798,9 @@ public class MicroServiceDictionaryController { } if (mainClass != null) { this.newModel.setDependency(mainClass.getDependency()); - this.newModel.setSub_attributes(subAttribute); + this.newModel.setSubAttributes(subAttribute); this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setRefAttributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); } @@ -784,7 +812,7 @@ public class MicroServiceDictionaryController { returnList.addAll(dependency); for (String element : dependency) { if (classMap.containsKey(element)) { - MSAttributeObject value = classMap.get(element); + MsAttributeObject value = classMap.get(element); String rawValue = StringUtils.replaceEach(value.getDependency(), new String[] {"[", "]"}, new String[] {"", ""}); workingList = new ArrayList<>(Arrays.asList(rawValue.split(","))); @@ -800,21 +828,24 @@ public class MicroServiceDictionaryController { return returnList; } - @RequestMapping(value = {"/get_MicroServiceHeaderDefaultsDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceHeaderDefaultsDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceHeaderDefaultsEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceHeaderDefaultDatas, "modelName", MicroserviceHeaderdeFaults.class); } - @RequestMapping(value = {"/get_MicroServiceHeaderDefaultsData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceHeaderDefaultsData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceHeaderDefaultsEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, microServiceHeaderDefaultDatas, MicroserviceHeaderdeFaults.class); } - @RequestMapping(value = {"/ms_dictionary/save_headerDefaults"}, method = {RequestMethod.POST}) public ModelAndView saveMicroServiceHeaderDefaultValues(HttpServletRequest request, HttpServletResponse response) throws IOException { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java index 3d1dba905..a24ee0275 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,8 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -37,8 +43,8 @@ import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; @@ -46,18 +52,13 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; - @Controller public class OptimizationDictionaryController { private static CommonClassDao commonClassDao; private static String operation = "operation"; - private LinkedHashMap<String,MSAttributeObject > classMap; - private static String dictionaryFields ="dictionaryFields"; + private LinkedHashMap<String, MsAttributeObject> classMap; + private static String dictionaryFields = "dictionaryFields"; private static String duplicateResponseString = "Duplicate"; private static String optimizationModelsDictionaryDatas = "optimizationModelsDictionaryDatas"; private static String modelName = "modelName"; @@ -67,41 +68,48 @@ public class OptimizationDictionaryController { private static String classMapData = "classMap"; private static final String UPDATE = "update"; - - public OptimizationDictionaryController(){ + public OptimizationDictionaryController() { super(); - } + } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - + @Autowired - public OptimizationDictionaryController(CommonClassDao commonClassDao){ + public OptimizationDictionaryController(CommonClassDao commonClassDao) { setCommonClassDao(commonClassDao); } + public static void setCommonClassDao(CommonClassDao commonClassDao) { OptimizationDictionaryController.commonClassDao = commonClassDao; } - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); private OptimizationModels newModel; - @RequestMapping(value={"/get_OptimizationModelsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response){ + @RequestMapping( + value = {"/get_OptimizationModelsData"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils dUtils = getDictionaryUtilsInstance(); dUtils.getData(response, optimizationModelsDictionaryDatas, OptimizationModels.class); } - @RequestMapping(value={"/get_OptimizationModelsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping( + value = {"/get_OptimizationModelsDataByName"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils dUtils = getDictionaryUtilsInstance(); dUtils.getDataByEntity(response, optimizationModelsDictionaryDatas, modelName, OptimizationModels.class); } - @RequestMapping(value={"/oof_dictionary/save_model"}, method={RequestMethod.POST}) - public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/oof_dictionary/save_model"}, method = {RequestMethod.POST}) + public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils dUtils = getDictionaryUtilsInstance(); try { this.newModel = new OptimizationModels(); @@ -113,24 +121,27 @@ public class OptimizationDictionaryController { String userId = null; String dataOrderInfo = null; - if(root.has("dataOrderInfo")){ + if (root.has("dataOrderInfo")) { dataOrderInfo = root.get("dataOrderInfo").toString(); } - if(root.has("modelType")){ + if (root.has("modelType")) { JsonNode dataType = root.get("modelType"); - String modelType= dataType.toString(); - if(modelType.contains("yml")){ - if (root.has(optimizationModelsDictionaryData)){ - if (root.get(optimizationModelsDictionaryData).has(description)){ - optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", "")); + String modelType = dataType.toString(); + if (modelType.contains("yml")) { + if (root.has(optimizationModelsDictionaryData)) { + if (root.get(optimizationModelsDictionaryData).has(description)) { + optimizationModels.setDescription(root.get(optimizationModelsDictionaryData) + .get(description).asText().replace("\"", "")); } - if (root.get(optimizationModelsDictionaryData).has(modelName)){ - optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(modelName)) { + optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName) + .asText().replace("\"", "")); this.newModel.setModelName(optimizationModels.getModelName()); } - if (root.get(optimizationModelsDictionaryData).has(version)){ - optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(version)) { + optimizationModels.setVersion( + root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); this.newModel.setVersion(optimizationModels.getVersion()); } } @@ -138,63 +149,70 @@ public class OptimizationDictionaryController { classMap = new LinkedHashMap<>(); JsonNode data = root.get(classMapData); ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); + String data1 = data.toString().substring(1, data.toString().length() - 1); data1 = data1.replace("\\", ""); - data1=data1.replace("\"{","{"); - data1=data1.replace("}\"","}"); + data1 = data1.replace("\"{", "{"); + data1 = data1.replace("}\"", "}"); JSONObject jsonObject = new JSONObject(data1); Set<String> keys = jsonObject.keySet(); - for(String key : keys){ + for (String key : keys) { String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class); classMap.put(key, msAttributeObject); } userId = root.get("userid").textValue(); - MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); + MsAttributeObject mainClass = classMap.get(this.newModel.getModelName()); this.newModel.setDependency("[]"); String value = new Gson().toJson(mainClass.getSubClass()); this.newModel.setSubattributes(value); - String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf('='); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1); + String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes = attributes.indexOf('='); + String atttributesAfterFirstEquals = + attributes.substring(equalsIndexForAttributes + 1, attributes.length() - 1); this.newModel.setAttributes(atttributesAfterFirstEquals); - String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf('='); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1); + String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex = refAttributes.indexOf('='); + String refAttributesAfterFirstEquals = + refAttributes.substring(equalsIndex + 1, refAttributes.length() - 1); this.newModel.setRefattributes(refAttributesAfterFirstEquals); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); - this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + this.newModel + .setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); - }else{ + } else { if (fromAPI) { - optimizationModels = mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class); + optimizationModels = + mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class); userId = "API"; } else { - if (root.has(optimizationModelsDictionaryData)){ - if (root.get(optimizationModelsDictionaryData).has(description)){ - optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", "")); + if (root.has(optimizationModelsDictionaryData)) { + if (root.get(optimizationModelsDictionaryData).has(description)) { + optimizationModels.setDescription(root.get(optimizationModelsDictionaryData) + .get(description).asText().replace("\"", "")); } - if (root.get(optimizationModelsDictionaryData).has(modelName)){ - optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(modelName)) { + optimizationModels.setModelName(root.get(optimizationModelsDictionaryData) + .get(modelName).asText().replace("\"", "")); this.newModel.setModelName(optimizationModels.getModelName()); } - if (root.get(optimizationModelsDictionaryData).has(version)){ - optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(version)) { + optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version) + .asText().replace("\"", "")); this.newModel.setVersion(optimizationModels.getVersion()); } } - if(root.has(classMapData)){ + if (root.has(classMapData)) { classMap = new LinkedHashMap<>(); JsonNode data = root.get(classMapData); ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); + String data1 = data.toString().substring(1, data.toString().length() - 1); data1 = data1.replace("\\", ""); JSONObject jsonObject = new JSONObject(data1); Set<String> keys = jsonObject.keySet(); - for(String key : keys){ + for (String key : keys) { String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class); classMap.put(key, msAttributeObject); } } @@ -212,80 +230,83 @@ public class OptimizationDictionaryController { optimizationModels.setEnumValues(this.newModel.getEnumValues()); optimizationModels.setAnnotation(this.newModel.getAnnotation()); - if(dataOrderInfo != null){ + if (dataOrderInfo != null) { optimizationModels.setDataOrderInfo(dataOrderInfo); } String checkName = optimizationModels.getModelName() + ":" + optimizationModels.getVersion(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class); boolean duplicateflag = false; - if(duplicateData!=null && !duplicateData.isEmpty()){ + if (duplicateData != null && !duplicateData.isEmpty()) { OptimizationModels data = (OptimizationModels) duplicateData.get(0); - if(request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))) { optimizationModels.setId(data.getId()); - }else if((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))){ + } else if ((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation))) + || (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))) { duplicateflag = true; } } UserInfo userInfo = dUtils.getUserInfo(userId); String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { optimizationModels.setUserCreatedBy(userInfo); - if(optimizationModels.getId() == 0){ + if (optimizationModels.getId() == 0) { commonClassDao.save(optimizationModels); - }else{ + } else { commonClassDao.update(optimizationModels); } responseString = mapper.writeValueAsString(commonClassDao.getData(OptimizationModels.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return dUtils.getResultForApi(responseString); - }else{ + } else { dUtils.setResponseData(response, optimizationModelsDictionaryDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { dUtils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/oof_dictionary/remove_model"}, method={RequestMethod.POST}) - public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/oof_dictionary/remove_model"}, method = {RequestMethod.POST}) + public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils dUtils = getDictionaryUtilsInstance(); dUtils.removeData(request, response, optimizationModelsDictionaryDatas, OptimizationModels.class); } - private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) { - //Loop through the classmap and pull out the required info for the new file. + private void addValuesToNewModel(HashMap<String, MsAttributeObject> classMap) { + // Loop through the classmap and pull out the required info for the new file. String subAttribute = null; - MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); + MsAttributeObject mainClass = classMap.get(this.newModel.getModelName()); - if (mainClass !=null){ - String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + if (mainClass != null) { + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "}, + new String[] {"", "", ""}); ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(","))); dependency = getFullDependencyList(dependency); - for (String element : dependency){ - MSAttributeObject temp = classMap.get(element); - if (temp!=null){ + for (String element : dependency) { + MsAttributeObject temp = classMap.get(element); + if (temp != null) { mainClass.addAllRefAttribute(temp.getRefAttribute()); mainClass.addAllAttribute(temp.getAttribute()); } } subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - }else{ + } else { subAttribute = "{}"; this.newModel.setDependency(""); } - if (mainClass != null && mainClass.getDependency()==null){ + if (mainClass != null && mainClass.getDependency() == null) { mainClass.setDependency(""); } - if(mainClass != null){ + if (mainClass != null) { this.newModel.setDependency(mainClass.getDependency()); this.newModel.setSubattributes(subAttribute); this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); @@ -299,13 +320,14 @@ public class OptimizationDictionaryController { ArrayList<String> returnList = new ArrayList<>(); ArrayList<String> workingList; returnList.addAll(dependency); - for (String element : dependency ){ - if (classMap.containsKey(element)){ - MSAttributeObject value = classMap.get(element); - String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); + for (String element : dependency) { + if (classMap.containsKey(element)) { + MsAttributeObject value = classMap.get(element); + String rawValue = + StringUtils.replaceEach(value.getDependency(), new String[] {"[", "]"}, new String[] {"", ""}); workingList = new ArrayList<>(Arrays.asList(rawValue.split(","))); - for(String depend : workingList){ - if (!returnList.contains(depend) && !depend.isEmpty()){ + for (String depend : workingList) { + if (!returnList.contains(depend) && !depend.isEmpty()) { returnList.add(depend.trim()); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java index c0e7729db..a230ebe38 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.ArrayList; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -49,8 +52,7 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PolicyScopeDictionaryController { - private static final Logger LOGGER = - FlexLogger.getLogger(PolicyScopeDictionaryController.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); private static CommonClassDao commonClassDao; private static String operation = "operation"; @@ -81,24 +83,27 @@ public class PolicyScopeDictionaryController { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - @RequestMapping(value = {"/get_GroupPolicyScopeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_GroupPolicyScopeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, groupPolicyScopeDatas, "name", GroupPolicyScopeList.class); } - @RequestMapping(value = {"/get_GroupPolicyScopeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_GroupPolicyScopeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getGroupPolicyScopeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, - method = {RequestMethod.POST}) - public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, method = {RequestMethod.POST}) + public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -109,40 +114,33 @@ public class PolicyScopeDictionaryController { GroupPolicyScope groupData = null; boolean duplicateGroupFlag = false; if (fromAPI) { - gpdata = mapper.readValue(root.get(dictionaryFields).toString(), - GroupPolicyScopeList.class); + gpdata = mapper.readValue(root.get(dictionaryFields).toString(), GroupPolicyScopeList.class); try { - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), - GroupPolicyScope.class); + groupData = + mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); } catch (Exception e) { groupData = new GroupPolicyScope(); - groupData.setResource(root.get(dictionaryFields).get("resource").toString() - .replace("\"", "")); - groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString() - .replace("\"", "")); - groupData.setService( - root.get(dictionaryFields).get("service").toString().replace("\"", "")); - groupData.setType( - root.get(dictionaryFields).get("type").toString().replace("\"", "")); + groupData.setResource(root.get(dictionaryFields).get("resource").toString().replace("\"", "")); + groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString().replace("\"", "")); + groupData.setService(root.get(dictionaryFields).get("service").toString().replace("\"", "")); + groupData.setType(root.get(dictionaryFields).get("type").toString().replace("\"", "")); LOGGER.error(e); } } else { - gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), - GroupPolicyScopeList.class); + gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); try { - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), - GroupPolicyScope.class); + groupData = + mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); } catch (Exception e) { LOGGER.error(e); groupData = new GroupPolicyScope(); - groupData.setResource(root.get(groupPolicyScopeListData1).get("resource") - .toString().replace("\"", "")); - groupData.setClosedloop(root.get(groupPolicyScopeListData1).get("closedloop") - .toString().replace("\"", "")); - groupData.setService(root.get(groupPolicyScopeListData1).get("service") - .toString().replace("\"", "")); - groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString() - .replace("\"", "")); + groupData.setResource( + root.get(groupPolicyScopeListData1).get("resource").toString().replace("\"", "")); + groupData.setClosedloop( + root.get(groupPolicyScopeListData1).get("closedloop").toString().replace("\"", "")); + groupData.setService( + root.get(groupPolicyScopeListData1).get("service").toString().replace("\"", "")); + groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString().replace("\"", "")); } } if (!gpdata.getGroupName().startsWith(policyScope)) { @@ -158,15 +156,15 @@ public class PolicyScopeDictionaryController { valueList.add("service=" + serviceValue); valueList.add("type=" + typeValue); valueList.add("closedLoopControlName=" + closedLoopValue); - String list = StringUtils.replaceEach(valueList.toString(), - new String[] {"[", "]", " "}, new String[] {"", "", ""}); + String list = StringUtils.replaceEach(valueList.toString(), new String[] {"[", "]", " "}, + new String[] {"", "", ""}); gpdata.setGroupList(list); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), - "name", GroupPolicyScopeList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); if (duplicateData.isEmpty()) { - duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), - "groupList", GroupPolicyScopeList.class); + duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", + GroupPolicyScopeList.class); if (duplicateData.isEmpty()) { duplicateGroupFlag = true; } @@ -174,13 +172,11 @@ public class PolicyScopeDictionaryController { boolean duplicateflag = false; if (!duplicateData.isEmpty()) { GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { gpdata.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != gpdata.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != gpdata.getId()))) { duplicateflag = true; } } @@ -191,8 +187,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(gpdata); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); } else if (duplicateGroupFlag) { responseString = "DuplicateGroup"; } else { @@ -209,22 +204,25 @@ public class PolicyScopeDictionaryController { return null; } - @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, - method = {RequestMethod.POST}) - public void removePSGroupScopeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, method = {RequestMethod.POST}) + public void removePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value = {"/get_PSClosedLoopDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSClosedLoopDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSClosedLoopEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psCLDatas, "name", OnapName.class); } - @RequestMapping(value = {"/get_PSClosedLoopData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSClosedLoopData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSClosedLoopEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -232,8 +230,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psClosedLoop"}, method = {RequestMethod.POST}) - public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -242,25 +240,22 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeClosedLoop onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeClosedLoop.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeClosedLoop.class); } else { onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), PolicyScopeClosedLoop.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeClosedLoop.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -271,8 +266,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); } else { responseString = duplicateResponseString; } @@ -288,20 +282,24 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/remove_PSClosedLoop"}, method = {RequestMethod.POST}) - public void removePSClosedLoopDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value = {"/get_PSServiceDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSServiceDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSServiceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psServiceDatas, "name", PolicyScopeService.class); } - @RequestMapping(value = {"/get_PSServiceData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSServiceData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSServiceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -309,8 +307,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psService"}, method = {RequestMethod.POST}) - public ModelAndView savePSServiceDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -319,25 +317,21 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeService onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeService.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeService.class); } else { - onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), - PolicyScopeService.class); + onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeService.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -348,8 +342,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); } else { responseString = duplicateResponseString; } @@ -365,20 +358,23 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/remove_PSService"}, method = {RequestMethod.POST}) - public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value = {"/get_PSTypeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSTypeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSTypeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psTypeDatas, "name", PolicyScopeType.class); } - @RequestMapping(value = {"/get_PSTypeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSTypeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSTypeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -386,8 +382,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psType"}, method = {RequestMethod.POST}) - public ModelAndView savePSTypeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -396,25 +392,21 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeType onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeType.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeType.class); } else { - onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), - PolicyScopeType.class); + onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeType.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -425,8 +417,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); } else { responseString = duplicateResponseString; } @@ -442,20 +433,23 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/remove_PSType"}, method = {RequestMethod.POST}) - public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value = {"/get_PSResourceDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSResourceDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSResourceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psResourceDatas, "name", PolicyScopeResource.class); } - @RequestMapping(value = {"/get_PSResourceData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSResourceData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSResourceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -463,8 +457,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psResource"}, method = {RequestMethod.POST}) - public ModelAndView savePSResourceDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -473,25 +467,21 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeResource onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeResource.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeResource.class); } else { - onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), - PolicyScopeResource.class); + onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeResource.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -502,8 +492,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); } else { responseString = duplicateResponseString; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java index 17fce7142..b7b63a9e0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java @@ -24,6 +24,7 @@ import com.att.research.xacml.api.pap.PAPException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -32,9 +33,11 @@ import java.io.ObjectOutputStream; import java.net.URI; import java.util.List; import java.util.UUID; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -93,8 +96,8 @@ public class PushPolicyController { LOGGER.info("No request ID provided, sending generated ID: " + requestID); } LOGGER.info("Push policy Request to get the selectedPolicy : " + root.asText()); - String policyVersionName = policyScope.replace(".", File.separator) + File.separator - + filePrefix + policyName; + String policyVersionName = + policyScope.replace(".", File.separator) + File.separator + filePrefix + policyName; List<?> policyVersionObject = commonClassDao.getDataById(PolicyVersion.class, policyNames, policyVersionName); if (policyVersionObject != null) { @@ -120,10 +123,10 @@ public class PushPolicyController { } private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, - HttpServletResponse response) { + HttpServletResponse response) { StdPDPGroup selectedPDPGroup = null; StdPDPPolicy selectedPolicy = null; - //Get the selected PDP Group to push the policy + // Get the selected PDP Group to push the policy try { selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup); } catch (PAPException e1) { @@ -147,16 +150,15 @@ public class PushPolicyController { params.put("scope", policyScope); params.put(policyNames, policyName.substring(policyScope.length() + 1)); List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params); - LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames - + " from PolicyEntity"); + LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames + " from PolicyEntity"); PolicyEntity policyEntity = null; if (!createPolicyQueryList.isEmpty()) { policyEntity = (PolicyEntity) createPolicyQueryList.get(0); } else { PolicyLogger - .error("Somehow, more than one policy with the same scope, name, and deleted status were found in" + - " the database"); + .error("Somehow, more than one policy with the same scope, name, and deleted status were found in" + + " the database"); String message = "Unknown Policy '" + policyName + "'"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); response.addHeader(errorMsg, "unknownPolicy"); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java index 6e794d966..577870c70 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.RiskType; @@ -66,14 +69,18 @@ public class SafePolicyController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_RiskTypeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RiskTypeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, riskTypeDatas, "name", RiskType.class); } - @RequestMapping(value = {"/get_RiskTypeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RiskTypeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -81,8 +88,8 @@ public class SafePolicyController { } @RequestMapping(value = {"/sp_dictionary/save_riskType"}, method = {RequestMethod.POST}) - public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -92,27 +99,23 @@ public class SafePolicyController { RiskType riskTypeData; String userId = null; if (fromAPI) { - riskTypeData = - mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); + riskTypeData = mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); userId = "API"; } else { - riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), - RiskType.class); + riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(riskTypeData.getName(), "name", RiskType.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { RiskType data = (RiskType) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { riskTypeData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != riskTypeData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != riskTypeData.getId()))) { duplicateflag = true; } } @@ -142,30 +145,32 @@ public class SafePolicyController { } @RequestMapping(value = {"/sp_dictionary/remove_riskType"}, method = {RequestMethod.POST}) - public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, riskTypeDatas, RiskType.class); } - @RequestMapping(value = {"/get_SafePolicyWarningDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SafePolicyWarningDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, safePolicyWarningDatas, "name", SafePolicyWarning.class); } - @RequestMapping(value = {"/get_SafePolicyWarningData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SafePolicyWarningData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, safePolicyWarningDatas, SafePolicyWarning.class); } - @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, - method = {RequestMethod.POST}) - public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, method = {RequestMethod.POST}) + public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -174,25 +179,22 @@ public class SafePolicyController { JsonNode root = mapper.readTree(request.getReader()); SafePolicyWarning safePolicyWarning; if (fromAPI) { - safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), - SafePolicyWarning.class); + safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); } else { - safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), - SafePolicyWarning.class); + safePolicyWarning = + mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - safePolicyWarning.getName(), "name", SafePolicyWarning.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { safePolicyWarning.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != safePolicyWarning.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != safePolicyWarning.getId()))) { duplicateflag = true; } } @@ -203,8 +205,7 @@ public class SafePolicyController { } else { commonClassDao.update(safePolicyWarning); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); } else { responseString = duplicateResponseString; } @@ -219,10 +220,9 @@ public class SafePolicyController { return null; } - @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, - method = {RequestMethod.POST}) - public void removeSafePolicyWarningDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, method = {RequestMethod.POST}) + public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, safePolicyWarningDatas, SafePolicyWarning.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java index bb42fb6aa..7e940a2a1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -18,5 +18,4 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest.controller; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java index 2688d7d3c..ee5c22f1c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java @@ -22,7 +22,9 @@ package org.onap.policy.pap.xacml.rest.daoimpl; import java.util.List; import java.util.Map; + import javax.script.SimpleBindings; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; @@ -51,10 +53,8 @@ public class CommonClassDaoImpl implements CommonClassDao { private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); - private static SessionFactory sessionFactory; - @Autowired private CommonClassDaoImpl(SessionFactory sessionFactory) { CommonClassDaoImpl.sessionFactory = sessionFactory; @@ -78,14 +78,12 @@ public class CommonClassDaoImpl implements CommonClassDao { try { session.close(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } return data; } - @SuppressWarnings({"rawtypes", "unchecked"}) @Override public List<Object> getDataById(Class className, String columnName, String key) { @@ -109,8 +107,7 @@ public class CommonClassDaoImpl implements CommonClassDao { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; @@ -131,8 +128,7 @@ public class CommonClassDaoImpl implements CommonClassDao { try { session.close(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } return data; @@ -146,14 +142,12 @@ public class CommonClassDaoImpl implements CommonClassDao { session.persist(entity); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Saving data to Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } @@ -167,20 +161,17 @@ public class CommonClassDaoImpl implements CommonClassDao { session.delete(entity); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Deleting data from Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } } - @Override public void update(Object entity) { Session session = sessionFactory.openSession(); @@ -189,20 +180,17 @@ public class CommonClassDaoImpl implements CommonClassDao { session.update(entity); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating data to Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } } - @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { @@ -231,20 +219,18 @@ public class CommonClassDaoImpl implements CommonClassDao { data = cr.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying for Duplicate Entries for Table" + e + className); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table" + + e + className); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; } - @SuppressWarnings("unchecked") @Override public List<Object> getDataByQuery(String query, SimpleBindings params) { @@ -263,21 +249,18 @@ public class CommonClassDaoImpl implements CommonClassDao { data = hbquery.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying Database Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e); throw e; } finally { try { session.close(); } catch (HibernateException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement", e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement", e1); } } return data; } - @Override public void updateQuery(String query) { Session session = sessionFactory.openSession(); @@ -287,19 +270,16 @@ public class CommonClassDaoImpl implements CommonClassDao { hbquery.executeUpdate(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating Database Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } } - @SuppressWarnings("rawtypes") @Override public Object getEntityItem(Class className, String columnName, String key) { @@ -320,20 +300,17 @@ public class CommonClassDaoImpl implements CommonClassDao { data = cr.list().get(0); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying Database Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; } - @SuppressWarnings("unchecked") @Override public List<PolicyRoles> getUserRoles() { @@ -355,20 +332,17 @@ public class CommonClassDaoImpl implements CommonClassDao { rolesData = cr.add(disjunction).list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying PolicyRoles Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return rolesData; } - @SuppressWarnings("unchecked") @Override public void updateClAlarms(String clName, String alarms) { @@ -384,14 +358,12 @@ public class CommonClassDaoImpl implements CommonClassDao { session.update(closedloop); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating ClosedLoops Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table" + e); } finally { session.close(); } } - @SuppressWarnings("unchecked") @Override public void updateClYaml(String clName, String yaml) { @@ -407,14 +379,12 @@ public class CommonClassDaoImpl implements CommonClassDao { session.update(closedloop); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating ClosedLoops Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table" + e); } finally { session.close(); } } - @SuppressWarnings("unchecked") @Override public void deleteAll() { @@ -438,8 +408,8 @@ public class CommonClassDaoImpl implements CommonClassDao { tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error while deleting ClosedLoops from the table" + e); + LOGGER.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table" + e); } finally { session.close(); } @@ -447,8 +417,7 @@ public class CommonClassDaoImpl implements CommonClassDao { @SuppressWarnings({"unchecked"}) @Override - public List<Object> checkExistingGroupListforUpdate(String groupListValue, - String groupNameValue) { + public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); List<Object> data = null; @@ -461,23 +430,20 @@ public class CommonClassDaoImpl implements CommonClassDao { tx.commit(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table" - + e); + + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; } - @Override - public List<Object> getMultipleDataOnAddingConjunction( - @SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) { + public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, + String columnName, List<String> data) { return null; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java index f04be861b..cfae68091 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.elk.client; import com.google.gson.Gson; + import io.searchbox.client.JestClientFactory; import io.searchbox.client.config.HttpClientConfig; import io.searchbox.client.http.JestHttpClient; @@ -28,6 +29,7 @@ import io.searchbox.core.Bulk; import io.searchbox.core.Bulk.Builder; import io.searchbox.core.BulkResult; import io.searchbox.core.Index; + import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; @@ -43,6 +45,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -50,13 +53,12 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.util.XACMLPolicyScanner; - - /** * This code will deals with parsing the XACML content on reading from * database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables) @@ -126,54 +128,53 @@ public class ElasticSearchPolicyUpdate { String policyEntityQuery = "Select * from PolicyEntity"; result = stmt.executeQuery(policyEntityQuery); - while(result.next()){ + while (result.next()) { StringBuilder policyDataString = new StringBuilder("{"); String scope = result.getString("scope"); String policyName = result.getString("policyName"); - if(policyName != null){ - policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\","); + if (policyName != null) { + policyDataString.append("\"policyName\":\"" + scope + "." + policyName + "\","); } String description = result.getString("description"); - if(description != null){ - policyDataString.append("\"policyDescription\":\""+description+"\","); + if (description != null) { + policyDataString.append("\"policyDescription\":\"" + description + "\","); } Object policyData = result.getString("policydata"); - if(scope != null){ - policyDataString.append("\"scope\":\""+scope+"\","); + if (scope != null) { + policyDataString.append("\"scope\":\"" + scope + "\","); } String actionbodyid = result.getString("actionbodyid"); String configurationdataid = result.getString("configurationdataid"); - String policyWithScopeName = scope + "." + policyName; String _type = null; - if(policyWithScopeName.contains(".Config_")){ + if (policyWithScopeName.contains(".Config_")) { policyDataString.append("\"policyType\":\"Config\","); - if(policyWithScopeName.contains(".Config_Fault_")){ + if (policyWithScopeName.contains(".Config_Fault_")) { _type = "closedloop"; policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\","); - }else if(policyWithScopeName.contains(".Config_PM_")){ + } else if (policyWithScopeName.contains(".Config_PM_")) { _type = "closedloop"; policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\","); - }else{ + } else { _type = "config"; policyDataString.append("\"configPolicyType\":\"Base\","); } - }else if(policyWithScopeName.contains(".Action_")){ + } else if (policyWithScopeName.contains(".Action_")) { _type = "action"; policyDataString.append("\"policyType\":\"Action\","); - }else if(policyWithScopeName.contains(".Decision_")){ + } else if (policyWithScopeName.contains(".Decision_")) { _type = "decision"; policyDataString.append("\"policyType\":\"Decision\","); } - if(!"decision".equals(_type)){ - if(configurationdataid != null){ + if (!"decision".equals(_type)) { + if (configurationdataid != null) { updateConfigData(conn, configurationdataid, policyDataString); } - if(actionbodyid != null){ + if (actionbodyid != null) { updateActionData(conn, actionbodyid, policyDataString); } } @@ -181,72 +182,72 @@ public class ElasticSearchPolicyUpdate { String _id = policyWithScopeName; String dataString = constructPolicyData(policyData, policyDataString); - dataString = dataString.substring(0, dataString.length()-1); + dataString = dataString.substring(0, dataString.length() - 1); dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}"; dataString = dataString.replace("null", "\"\""); dataString = dataString.replaceAll("\n", ""); - try{ + try { Gson gson = new Gson(); gson.fromJson(dataString, Object.class); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(e); continue; } - if("config".equals(_type)){ + if ("config".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build()); - }else if("closedloop".equals(_type)){ + } else if ("closedloop".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build()); - }else if("action".equals(_type)){ + } else if ("action".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build()); - }else if("decision".equals(_type)){ + } else if ("decision".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build()); } } result.close(); bulk = new Bulk.Builder(); - for(int i =0; i < listIndex.size(); i++){ + for (int i = 0; i < listIndex.size(); i++) { bulk.addAction(listIndex.get(i)); } BulkResult searchResult = client.execute(bulk.build()); - if(searchResult.isSucceeded()){ + if (searchResult.isSucceeded()) { LOGGER.debug("Success"); - }else{ + } else { LOGGER.error("Failure"); } } catch (Exception e) { - LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e); - }finally{ - if(result != null){ - try { - result.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the resultset"+e); - } + LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade" + e); + } finally { + if (result != null) { + try { + result.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the resultset" + e); } - if(stmt != null){ - try { - stmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the statement"+e); - } + } + if (stmt != null) { + try { + stmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the statement" + e); } - if(conn != null){ + } + if (conn != null) { try { conn.close(); } catch (Exception e) { - LOGGER.error("Exception Occured while closing the connection"+e); + LOGGER.error("Exception Occured while closing the connection" + e); } } } } - public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){ + public static String constructPolicyData(Object policyContent, StringBuilder policyDataString) { InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8)); Object policyData = XACMLPolicyScanner.readPolicy(stream); - if(policyData instanceof PolicyType){ + if (policyData instanceof PolicyType) { PolicyType policy = (PolicyType) policyData; TargetType target = policy.getTarget(); if (target != null) { @@ -278,19 +279,19 @@ public class ElasticSearchPolicyUpdate { String attributeId = designator.getAttributeId(); // First match in the target is OnapName, so set that value. if ("ONAPName".equals(attributeId)) { - policyDataString.append("\"onapName\":\""+value+"\","); + policyDataString.append("\"onapName\":\"" + value + "\","); } - if ("RiskType".equals(attributeId)){ - policyDataString.append("\"riskType\":\""+value+"\","); + if ("RiskType".equals(attributeId)) { + policyDataString.append("\"riskType\":\"" + value + "\","); } - if ("RiskLevel".equals(attributeId)){ - policyDataString.append("\"riskLevel\":\""+value+"\","); + if ("RiskLevel".equals(attributeId)) { + policyDataString.append("\"riskLevel\":\"" + value + "\","); } - if ("guard".equals(attributeId)){ - policyDataString.append("\"guard\":\""+value+"\","); + if ("guard".equals(attributeId)) { + policyDataString.append("\"guard\":\"" + value + "\","); } - if ("ConfigName".equals(attributeId)){ - policyDataString.append("\"configName\":\""+value+"\","); + if ("ConfigName".equals(attributeId)) { + policyDataString.append("\"configName\":\"" + value + "\","); } } } @@ -303,79 +304,82 @@ public class ElasticSearchPolicyUpdate { return policyDataString.toString(); } - private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) throws Exception { - - PreparedStatement pstmt = null; - ResultSet configResult = null; - try { - String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?"; - pstmt = null; - pstmt = conn.prepareStatement(configEntityQuery); - pstmt.setString(1, configurationdataid); - configResult = pstmt.executeQuery(); - while(configResult.next()){ - String configBody = configResult.getString("configbody"); - String configType = configResult.getString("configtype"); - if(configBody!=null){ - configBody = configBody.replace("null", "\"\""); - configBody= configBody.replace("\"", "\\\""); - policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\","); - } + private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) + throws Exception { + + PreparedStatement pstmt = null; + ResultSet configResult = null; + try { + String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?"; + pstmt = null; + pstmt = conn.prepareStatement(configEntityQuery); + pstmt.setString(1, configurationdataid); + configResult = pstmt.executeQuery(); + while (configResult.next()) { + String configBody = configResult.getString("configbody"); + String configType = configResult.getString("configtype"); + if (configBody != null) { + configBody = configBody.replace("null", "\"\""); + configBody = configBody.replace("\"", "\\\""); + policyDataString + .append("\"jsonBodyData\":\"" + configBody + "\",\"configType\":\"" + configType + "\","); } - } catch(Exception e) { - LOGGER.error("Exception Occured while updating configData"+e); - throw(e); - } finally { - if(configResult != null){ - try { - configResult.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the ResultSet"+e); - } + } + } catch (Exception e) { + LOGGER.error("Exception Occured while updating configData" + e); + throw (e); + } finally { + if (configResult != null) { + try { + configResult.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the ResultSet" + e); } - if(pstmt != null){ - try { - pstmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the PreparedStatement"+e); - } + } + if (pstmt != null) { + try { + pstmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the PreparedStatement" + e); } - } + } + } } - private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception { - - PreparedStatement pstmt = null; - ResultSet actionResult = null; - try { - String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?"; - pstmt = conn.prepareStatement(actionEntityQuery); - pstmt.setString(1, actionbodyid); - actionResult = pstmt.executeQuery(); - while(actionResult.next()){ - String actionBody = actionResult.getString("actionbody"); - actionBody = actionBody.replace("null", "\"\""); - actionBody = actionBody.replace("\"", "\\\""); - policyDataString.append("\"jsonBodyData\":\""+actionBody+"\","); - } - } catch(Exception e) { - LOGGER.error("Exception Occured while updating actionData"+e); - throw(e); - } finally { - if(actionResult != null){ - try { - actionResult.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the ResultSet"+e); - } + private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) + throws Exception { + + PreparedStatement pstmt = null; + ResultSet actionResult = null; + try { + String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?"; + pstmt = conn.prepareStatement(actionEntityQuery); + pstmt.setString(1, actionbodyid); + actionResult = pstmt.executeQuery(); + while (actionResult.next()) { + String actionBody = actionResult.getString("actionbody"); + actionBody = actionBody.replace("null", "\"\""); + actionBody = actionBody.replace("\"", "\\\""); + policyDataString.append("\"jsonBodyData\":\"" + actionBody + "\","); + } + } catch (Exception e) { + LOGGER.error("Exception Occured while updating actionData" + e); + throw (e); + } finally { + if (actionResult != null) { + try { + actionResult.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the ResultSet" + e); } - if(pstmt != null){ - try { - pstmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the PreparedStatement"+e); - } + } + if (pstmt != null) { + try { + pstmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the PreparedStatement" + e); } - } + } + } } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java index d64b71763..d3f7f4dea 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -20,9 +20,10 @@ package org.onap.policy.pap.xacml.rest.elk.client; - import io.searchbox.client.JestResult; + import java.util.Map; + import org.onap.policy.rest.adapter.PolicyRestAdapter; public interface ElkConnector { @@ -44,8 +45,7 @@ public interface ElkConnector { public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException; - public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException; + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException; public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) throws IllegalStateException, IllegalArgumentException; @@ -54,8 +54,7 @@ public interface ElkConnector { public ElkConnector singleton = new ElkConnectorImpl(); - public static PolicyIndexType toPolicyIndexType(String policyName) - throws IllegalArgumentException { + public static PolicyIndexType toPolicyIndexType(String policyName) throws IllegalArgumentException { if (policyName == null) throw new IllegalArgumentException("Unsupported NULL policy name conversion"); @@ -76,8 +75,7 @@ public interface ElkConnector { } else if (policyName.startsWith("Config")) { return PolicyIndexType.config; } else { - throw new IllegalArgumentException( - "Unsupported policy name conversion to index: " + policyName); + throw new IllegalArgumentException("Unsupported policy name conversion to index: " + policyName); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index 6bbe033a3..4d84526a5 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -32,9 +32,11 @@ import io.searchbox.core.Search.Builder; import io.searchbox.indices.IndicesExists; import io.searchbox.indices.type.TypeExist; import io.searchbox.params.Parameters; + import java.io.IOException; import java.util.Map; import java.util.Map.Entry; + import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryStringQueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; @@ -56,8 +58,7 @@ public class ElkConnectorImpl implements ElkConnector { if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER: -"); } - HttpClientConfig jestClientConfig = - new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); jestFactory.setHttpClientConfig(jestClientConfig); jestClient = jestFactory.getObject(); } @@ -68,8 +69,7 @@ public class ElkConnectorImpl implements ElkConnector { } try { - Action<JestResult> typeQuery = - new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); + Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); JestResult result = jestClient.execute(typeQuery); if (LOGGER.isInfoEnabled()) { @@ -80,9 +80,7 @@ public class ElkConnectorImpl implements ElkConnector { } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn( - "Error checking type existance of " + type.toString() + ": " + e.getMessage(), - e); + LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); throw e; } } @@ -100,9 +98,7 @@ public class ElkConnectorImpl implements ElkConnector { } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn( - "Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), - e); + LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); throw e; } } @@ -112,8 +108,7 @@ public class ElkConnectorImpl implements ElkConnector { } @Override - public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException { + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("ENTER: " + text); } @@ -129,9 +124,8 @@ public class ElkConnectorImpl implements ElkConnector { QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*" + text + "*"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(mQ); - Builder searchBuilder = - new Search.Builder(searchSourceBuilder.toString()).addIndex(ELK_INDEX_POLICY) - .setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).addIndex(ELK_INDEX_POLICY) + .setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); if (type == null || type == PolicyIndexType.all) { for (PolicyIndexType pT : PolicyIndexType.values()) { @@ -148,24 +142,21 @@ public class ElkConnectorImpl implements ElkConnector { try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), - ioe); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " - + result.getPathToResult() + ":" + System.lineSeparator() - + result.getJsonString()); + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + result.getPathToResult() + ":" + + System.lineSeparator() + result.getJsonString()); } } else { /* Unsuccessful search */ if (LOGGER.isWarnEnabled()) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() - + ": " + search.getURI() + ":" + result.getPathToResult() + ":" - + result.getJsonString() + ":" + result.getErrorMessage()); + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + ": " + + search.getURI() + ":" + result.getPathToResult() + ":" + result.getJsonString() + ":" + + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -173,24 +164,19 @@ public class ElkConnectorImpl implements ElkConnector { String xMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -201,7 +187,6 @@ public class ElkConnectorImpl implements ElkConnector { return result; } - @Override public JestResult search(PolicyIndexType type, String text, Map<String, String> filter_s) throws IllegalStateException, IllegalArgumentException { @@ -218,8 +203,8 @@ public class ElkConnectorImpl implements ElkConnector { } String matches_s = ""; - matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" - + " \"query\": {\n" + " \"bool\" : {\n" + " \"must\" : ["; + matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + " \"query\": {\n" + + " \"bool\" : {\n" + " \"must\" : ["; String match_params = ""; boolean first = true; @@ -230,8 +215,7 @@ public class ElkConnectorImpl implements ElkConnector { match_params = "\"match\" : {\"" + key + "\" : \"" + value + "\" }},"; first = false; } else { - match_params = - match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },"; + match_params = match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },"; } } if (match_params.endsWith(",")) { @@ -271,24 +255,21 @@ public class ElkConnectorImpl implements ElkConnector { try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), - ioe); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " - + result.getPathToResult() + ":" + System.lineSeparator() - + result.getJsonString()); + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + result.getPathToResult() + ":" + + System.lineSeparator() + result.getJsonString()); } } else { /* Unsuccessful search */ if (LOGGER.isWarnEnabled()) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() - + ": " + search.getURI() + ":" + result.getPathToResult() + ":" - + result.getJsonString() + ":" + result.getErrorMessage()); + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + ": " + + search.getURI() + ":" + result.getPathToResult() + ":" + result.getJsonString() + ":" + + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -296,24 +277,19 @@ public class ElkConnectorImpl implements ElkConnector { String xMessage = errorMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -347,22 +323,20 @@ public class ElkConnectorImpl implements ElkConnector { } PolicyElasticData elasticData = new PolicyElasticData(policyData); JSONObject jsonObj = new JSONObject(elasticData); - Index elkPut = new Index.Builder(jsonObj.toString()).index(ELK_INDEX_POLICY) - .type(indexType.name()).id(elasticData.getPolicyName()).refresh(true).build(); + Index elkPut = new Index.Builder(jsonObj.toString()).index(ELK_INDEX_POLICY).type(indexType.name()) + .id(elasticData.getPolicyName()).refresh(true).build(); JestResult result = jestClient.execute(elkPut); if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" - + result.isSucceeded() + "[" + result.getResponseCode() + ":" - + result.getPathToResult() + "]" + System.lineSeparator() + LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" - + result.isSucceeded() + "[" + result.getResponseCode() + ":" - + result.getPathToResult() + "]" + System.lineSeparator() + LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } @@ -387,31 +361,29 @@ public class ElkConnectorImpl implements ElkConnector { String[] splitPolicyName = policyName.split(":"); indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); if (!isType(indexType)) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + " Type: " - + indexType + " is not configured"); + throw new IllegalStateException( + "ELK: Index: " + ELK_INDEX_POLICY + " Type: " + indexType + " is not configured"); } PolicyElasticData elasticData = new PolicyElasticData(policyData); - Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()) - .index(ELK_INDEX_POLICY).type(indexType.name()).build(); + Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY) + .type(indexType.name()).build(); result = jestClient.execute(deleteRequest); } catch (IllegalArgumentException | IOException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + indexType + ": null" - + ":" + policyData.getNewFileName() + ": " + e.getMessage(), e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + indexType + ": null" + ":" + + policyData.getNewFileName() + ": " + e.getMessage(), e); throw new IllegalStateException(e); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: DELETE operation of " + indexType + ":" - + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() - + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" - + System.lineSeparator() + result.getJsonString()); + LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" - + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() - + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" - + System.lineSeparator() + result.getJsonString()); + LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } return result.isSucceeded(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java index 2b0c94bf3..cd3fc4f0c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,17 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; -public class Pair<L,R> { +public class Pair<L, R> { private L left; private R right; - public Pair(L l, R r){ + + public Pair(L l, R r) { + this.left = l; + this.right = r; + } + + public L left() { + return left; + } + + public R right() { + return right; + } + + public void left(L l) { this.left = l; + } + + public void right(R r) { this.right = r; } - public L left(){ return left; } - public R right(){ return right; } - public void left(L l){ this.left = l; } - public void right(R r){ this.right = r; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java index 988640ca6..70964c487 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; import java.util.ArrayList; @@ -46,14 +47,14 @@ public class PolicyElasticData { private Map<?, ?> description; private Map<?, ?> attributeFields; - //Safe Policy + // Safe Policy private String policyScope; private String providerComboBox; private String riskType; private String riskLevel; private String guard; private String ttlDate; - private Map<String,String> matching; + private Map<String, String> matching; private List<Object> triggerSignatures; private List<Object> symptomSignatures; @@ -62,39 +63,39 @@ public class PolicyElasticData { public String gocServerScope; private String supressionType; - //MicroSerice + // MicroSerice private String serviceType; private String uuid; private String location; private String priority; private String msLocation; - //BRMS Policies + // BRMS Policies private String ruleName; - private Map<String,String> brmsParamBody; + private Map<String, String> brmsParamBody; private String brmsController; private List<String> brmsDependency; - private LinkedHashMap<?, ?> ruleData; - private LinkedHashMap<?,?> ruleListData; - private Map<String,String> drlRuleAndUIParams; + private LinkedHashMap<?, ?> ruleData; + private LinkedHashMap<?, ?> ruleListData; + private Map<String, String> drlRuleAndUIParams; - //ClosedLoop + // ClosedLoop private String clearTimeOut; private String trapMaxAge; private String verificationclearTimeOut; - public Map<String , String> dynamicLayoutMap; + public Map<String, String> dynamicLayoutMap; - //FireWall + // FireWall private String fwPolicyType; private List<Object> fwattributes; private String parentForChild; private String securityZone; - //Action & Decision + // Action & Decision private String ruleCombiningAlgId; - private Map<String,String> dynamicFieldConfigAttributes; - private Map<String,String> dynamicSettingsMap; - private Map<String,String> dropDownMap; + private Map<String, String> dynamicFieldConfigAttributes; + private Map<String, String> dynamicSettingsMap; + private Map<String, String> dropDownMap; private String actionPerformer; private String actionAttribute; private List<String> dynamicRuleAlgorithmLabels; @@ -117,15 +118,15 @@ public class PolicyElasticData { this.policyType = policyData.getPolicyType(); this.configPolicyType = policyData.getConfigPolicyType(); this.configBodyData = policyData.getConfigBodyData(); - this.policyName = policyData.getNewFileName(); - this.policyDescription = policyData.getPolicyDescription(); + this.policyName = policyData.getNewFileName(); + this.policyDescription = policyData.getPolicyDescription(); this.onapName = policyData.getOnapName(); this.configName = policyData.getConfigName(); this.configType = policyData.getConfigType(); this.jsonBody = policyData.getJsonBody(); - if(configPolicyType.startsWith("ClosedLoop")){ + if (configPolicyType.startsWith("ClosedLoop")) { this.jsonBodyData = jsonBody; - }else{ + } else { this.jsonBodyData = policyData.getJsonBodyData(); } @@ -134,12 +135,12 @@ public class PolicyElasticData { this.description = policyData.getDescription(); this.attributeFields = policyData.getAttributeFields(); - //Safe Policy + // Safe Policy this.policyScope = policyData.getPolicyScope(); this.providerComboBox = policyData.getProviderComboBox(); this.riskType = policyData.getRiskType(); this.riskLevel = policyData.getRiskLevel(); - this.guard = policyData.getGuard(); + this.guard = policyData.getGuard(); this.ttlDate = policyData.getTtlDate(); this.matching = policyData.getMatching(); @@ -150,14 +151,14 @@ public class PolicyElasticData { this.gocServerScope = policyData.getGocServerScope(); this.supressionType = policyData.getSupressionType(); - //MicroSerice + // MicroSerice this.serviceType = policyData.getServiceType(); this.uuid = policyData.getUuid(); this.location = policyData.getLocation(); this.priority = policyData.getPriority(); this.msLocation = policyData.getMsLocation(); - //BRMS Policies + // BRMS Policies this.ruleName = policyData.getRuleName(); this.brmsParamBody = policyData.getBrmsParamBody(); this.brmsController = policyData.getBrmsController(); @@ -166,19 +167,19 @@ public class PolicyElasticData { this.ruleListData = policyData.getRuleListData(); this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams(); - //ClosedLoop + // ClosedLoop this.clearTimeOut = policyData.getClearTimeOut(); this.trapMaxAge = policyData.getTrapMaxAge(); this.verificationclearTimeOut = policyData.getVerificationclearTimeOut(); this.dynamicLayoutMap = policyData.getDynamicLayoutMap(); - //FireWall + // FireWall this.fwPolicyType = policyData.getFwPolicyType(); this.fwattributes = policyData.getFwattributes(); this.parentForChild = policyData.getParentForChild(); this.securityZone = policyData.getSecurityZone(); - //Action & Decision + // Action & Decision this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId(); this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes(); this.dynamicSettingsMap = policyData.getDynamicSettingsMap(); @@ -204,21 +205,27 @@ public class PolicyElasticData { public String getScope() { return scope; } + public void setScope(String scope) { this.scope = scope; } + public String getPolicyType() { return policyType; } + public void setPolicyType(String policyType) { this.policyType = policyType; } + public String getConfigPolicyType() { return configPolicyType; } + public void setConfigPolicyType(String configPolicyType) { this.configPolicyType = configPolicyType; } + public String getConfigBodyData() { return configBodyData; } @@ -226,42 +233,55 @@ public class PolicyElasticData { public void setConfigBodyData(String configBodyData) { this.configBodyData = configBodyData; } + public String getPolicyName() { return policyName; } + public void setPolicyName(String policyName) { this.policyName = policyName; } + public String getPolicyDescription() { return policyDescription; } + public void setPolicyDescription(String policyDescription) { this.policyDescription = policyDescription; } + public String getOnapName() { return onapName; } + public void setOnapName(String onapName) { this.onapName = onapName; } + public String getConfigName() { return configName; } + public void setConfigName(String configName) { this.configName = configName; } + public String getConfigType() { return configType; } + public void setConfigType(String configType) { this.configType = configType; } + public String getJsonBody() { return jsonBody; } + public void setJsonBody(String jsonBody) { this.jsonBody = jsonBody; } + public Map<?, ?> getServiceTypePolicyName() { return serviceTypePolicyName; } @@ -293,318 +313,423 @@ public class PolicyElasticData { public void setAttributeFields(LinkedHashMap<?, ?> attributeFields) { this.attributeFields = attributeFields; } + public String getPolicyScope() { return policyScope; } + public void setPolicyScope(String policyScope) { this.policyScope = policyScope; } + public String getProviderComboBox() { return providerComboBox; } + public void setProviderComboBox(String providerComboBox) { this.providerComboBox = providerComboBox; } + public String getRiskType() { return riskType; } + public void setRiskType(String riskType) { this.riskType = riskType; } + public String getRiskLevel() { return riskLevel; } + public void setRiskLevel(String riskLevel) { this.riskLevel = riskLevel; } + public String getGuard() { return guard; } + public void setGuard(String guard) { this.guard = guard; } + public String getTtlDate() { return ttlDate; } + public void setTtlDate(String ttlDate) { this.ttlDate = ttlDate; } + public Map<String, String> getMatching() { return matching; } + public void setMatching(Map<String, String> matching) { this.matching = matching; } + public List<Object> getTriggerSignatures() { return triggerSignatures; } + public void setTriggerSignatures(ArrayList<Object> triggerSignatures) { this.triggerSignatures = triggerSignatures; } + public List<Object> getSymptomSignatures() { return symptomSignatures; } + public void setSymptomSignatures(ArrayList<Object> symptomSignatures) { this.symptomSignatures = symptomSignatures; } + public String getLogicalConnector() { return logicalConnector; } + public void setLogicalConnector(String logicalConnector) { this.logicalConnector = logicalConnector; } + public String getPolicyStatus() { return policyStatus; } + public void setPolicyStatus(String policyStatus) { this.policyStatus = policyStatus; } + public String getGocServerScope() { return gocServerScope; } + public void setGocServerScope(String gocServerScope) { this.gocServerScope = gocServerScope; } + public String getSupressionType() { return supressionType; } + public void setSupressionType(String supressionType) { this.supressionType = supressionType; } + public String getServiceType() { return serviceType; } + public void setServiceType(String serviceType) { this.serviceType = serviceType; } + public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } + public String getLocation() { return location; } + public void setLocation(String location) { this.location = location; } + public String getPriority() { return priority; } + public void setPriority(String priority) { this.priority = priority; } + public String getMsLocation() { return msLocation; } + public void setMsLocation(String msLocation) { this.msLocation = msLocation; } + public String getRuleName() { return ruleName; } + public void setRuleName(String ruleName) { this.ruleName = ruleName; } + public Map<String, String> getBrmsParamBody() { return brmsParamBody; } + public void setBrmsParamBody(Map<String, String> brmsParamBody) { this.brmsParamBody = brmsParamBody; } + public String getBrmsController() { return brmsController; } + public void setBrmsController(String brmsController) { this.brmsController = brmsController; } + public List<String> getBrmsDependency() { return brmsDependency; } + public void setBrmsDependency(List<String> brmsDependency) { this.brmsDependency = brmsDependency; } + public Map<?, ?> getRuleData() { return ruleData; } + public void setRuleData(LinkedHashMap<?, ?> ruleData) { this.ruleData = ruleData; } + public Map<?, ?> getRuleListData() { return ruleListData; } + public void setRuleListData(LinkedHashMap<?, ?> ruleListData) { this.ruleListData = ruleListData; } + public Map<String, String> getDrlRuleAndUIParams() { return drlRuleAndUIParams; } + public void setDrlRuleAndUIParams(Map<String, String> drlRuleAndUIParams) { this.drlRuleAndUIParams = drlRuleAndUIParams; } + public String getClearTimeOut() { return clearTimeOut; } + public void setClearTimeOut(String clearTimeOut) { this.clearTimeOut = clearTimeOut; } + public String getTrapMaxAge() { return trapMaxAge; } + public void setTrapMaxAge(String trapMaxAge) { this.trapMaxAge = trapMaxAge; } + public String getVerificationclearTimeOut() { return verificationclearTimeOut; } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { this.verificationclearTimeOut = verificationclearTimeOut; } + public Map<String, String> getDynamicLayoutMap() { return dynamicLayoutMap; } + public void setDynamicLayoutMap(Map<String, String> dynamicLayoutMap) { this.dynamicLayoutMap = dynamicLayoutMap; } + public String getFwPolicyType() { return fwPolicyType; } + public void setFwPolicyType(String fwPolicyType) { this.fwPolicyType = fwPolicyType; } + public List<Object> getFwattributes() { return fwattributes; } + public void setFwattributes(ArrayList<Object> fwattributes) { this.fwattributes = fwattributes; } + public String getParentForChild() { return parentForChild; } + public void setParentForChild(String parentForChild) { this.parentForChild = parentForChild; } + public String getSecurityZone() { return securityZone; } + public void setSecurityZone(String securityZone) { this.securityZone = securityZone; } + public String getRuleCombiningAlgId() { return ruleCombiningAlgId; } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { this.ruleCombiningAlgId = ruleCombiningAlgId; } + public Map<String, String> getDynamicFieldConfigAttributes() { return dynamicFieldConfigAttributes; } + public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) { this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; } + public Map<String, String> getDynamicSettingsMap() { return dynamicSettingsMap; } + public void setDynamicSettingsMap(Map<String, String> dynamicSettingsMap) { this.dynamicSettingsMap = dynamicSettingsMap; } + public Map<String, String> getDropDownMap() { return dropDownMap; } + public void setDropDownMap(Map<String, String> dropDownMap) { this.dropDownMap = dropDownMap; } + public String getActionPerformer() { return actionPerformer; } + public void setActionPerformer(String actionPerformer) { this.actionPerformer = actionPerformer; } + public String getActionAttribute() { return actionAttribute; } + public void setActionAttribute(String actionAttribute) { this.actionAttribute = actionAttribute; } + public List<String> getDynamicRuleAlgorithmLabels() { return dynamicRuleAlgorithmLabels; } + public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) { this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; } + public List<String> getDynamicRuleAlgorithmCombo() { return dynamicRuleAlgorithmCombo; } + public void setDynamicRuleAlgorithmCombo(List<String> dynamicRuleAlgorithmCombo) { this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; } + public List<String> getDynamicRuleAlgorithmField1() { return dynamicRuleAlgorithmField1; } + public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) { this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; } + public List<String> getDynamicRuleAlgorithmField2() { return dynamicRuleAlgorithmField2; } + public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) { this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; } + public List<Object> getDynamicVariableList() { return dynamicVariableList; } + public void setDynamicVariableList(List<Object> dynamicVariableList) { this.dynamicVariableList = dynamicVariableList; } + public List<String> getDataTypeList() { return dataTypeList; } + public void setDataTypeList(List<String> dataTypeList) { this.dataTypeList = dataTypeList; } + public String getActionAttributeValue() { return actionAttributeValue; } + public void setActionAttributeValue(String actionAttributeValue) { this.actionAttributeValue = actionAttributeValue; } + public String getRuleProvider() { return ruleProvider; } + public void setRuleProvider(String ruleProvider) { this.ruleProvider = ruleProvider; } + public String getActionBody() { return actionBody; } + public void setActionBody(String actionBody) { this.actionBody = actionBody; } + public String getActionDictHeader() { return actionDictHeader; } + public void setActionDictHeader(String actionDictHeader) { this.actionDictHeader = actionDictHeader; } + public String getActionDictType() { return actionDictType; } + public void setActionDictType(String actionDictType) { this.actionDictType = actionDictType; } + public String getActionDictUrl() { return actionDictUrl; } + public void setActionDictUrl(String actionDictUrl) { this.actionDictUrl = actionDictUrl; } + public String getActionDictMethod() { return actionDictMethod; } + public void setActionDictMethod(String actionDictMethod) { this.actionDictMethod = actionDictMethod; } + public YAMLParams getYamlparams() { return yamlparams; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java index 50965bd2b..48dc46c1b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,8 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonArray; + +import io.searchbox.client.JestResult; import java.io.IOException; import java.io.PrintWriter; @@ -41,22 +48,22 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionPolicyDict; import org.onap.policy.rest.jpa.Attribute; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.ClosedLoopD2Services; import org.onap.policy.rest.jpa.ClosedLoopSite; -import org.onap.policy.rest.jpa.DCAEuuid; +import org.onap.policy.rest.jpa.DcaeUuid; import org.onap.policy.rest.jpa.DecisionSettings; import org.onap.policy.rest.jpa.DescriptiveScope; import org.onap.policy.rest.jpa.GroupPolicyScopeList; import org.onap.policy.rest.jpa.MicroServiceLocation; import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.OnapName; -import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.PepOptions; import org.onap.policy.rest.jpa.RiskType; import org.onap.policy.rest.jpa.SafePolicyWarning; import org.onap.policy.rest.jpa.TermList; -import org.onap.policy.rest.jpa.VNFType; -import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VnfType; +import org.onap.policy.rest.jpa.VsclAction; import org.onap.policy.rest.jpa.VarbindDictionary; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -66,24 +73,14 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.JsonArray; - -import io.searchbox.client.JestResult; - @Controller @RequestMapping({"/"}) -public class PolicyElasticSearchController{ +public class PolicyElasticSearchController { private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); - enum Mode{ - attribute, onapName, actionPolicy, brmsParam, pepOptions, - clSite, clService, clVarbind, clVnf, clVSCL, decision, - fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, - psGroupPolicy, safeRisk, safePolicyWarning + enum Mode { + attribute, onapName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, psGroupPolicy, safeRisk, safePolicyWarning } protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { @@ -108,7 +105,7 @@ public class PolicyElasticSearchController{ } public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { - if (type == null || type.isEmpty()){ + if (type == null || type.isEmpty()) { return PolicyIndexType.all; } return PolicyIndexType.valueOf(type); @@ -154,11 +151,10 @@ public class PolicyElasticSearchController{ return success; } - - @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) + @RequestMapping(value = "/searchPolicy", method = RequestMethod.POST) public void searchPolicy(HttpServletRequest request, HttpServletResponse response) { - try{ - String message=""; + try { + String message = ""; boolean result = false; boolean policyResult = false; boolean validationCheck = true; @@ -168,16 +164,16 @@ public class PolicyElasticSearchController{ PolicyElasticSearchController controller = new PolicyElasticSearchController(); Map<String, String> searchKeyValue = new HashMap<>(); List<String> policyList = new ArrayList<>(); - if(request.getParameter("policyName") != null){ + if (request.getParameter("policyName") != null) { String policyName = request.getParameter("policyName"); policyData.setNewFileName(policyName); - if("delete".equalsIgnoreCase(request.getParameter(action))){ + if ("delete".equalsIgnoreCase(request.getParameter(action))) { result = controller.deleteElk(policyData); - }else{ + } else { result = controller.updateElk(policyData); } } - if("search".equalsIgnoreCase(request.getParameter(action))){ + if ("search".equalsIgnoreCase(request.getParameter(action))) { try { JsonNode root = mapper.readTree(request.getReader()); SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class); @@ -186,111 +182,117 @@ public class PolicyElasticSearchController{ String searchText = searchData.getQuery(); String descriptivevalue = searchData.getDescriptiveScope(); - if(descriptivevalue != null){ - DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); - if(dsSearch != null){ - String[] descriptiveList = dsSearch.getSearch().split("AND"); - for(String keyValue : descriptiveList){ + if (descriptivevalue != null) { + DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao + .getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); + if (dsSearch != null) { + String[] descriptiveList = dsSearch.getSearch().split("AND"); + for (String keyValue : descriptiveList) { String[] entry = keyValue.split(":"); - if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ - if(!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)){ - message = "The Descriptive Scope Dictionary value contains space and it is invalid for Search : "+entry[1]; + if (searchData.getPolicyType() != null + && "closedLoop".equals(searchData.getPolicyType())) { + if (!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)) { + message = + "The Descriptive Scope Dictionary value contains space and it is invalid for Search : " + + entry[1]; validationCheck = false; } - searchKeyValue.put(jsonBodyData, "*" +entry[1] +"*"); - }else{ + searchKeyValue.put(jsonBodyData, "*" + entry[1] + "*"); + } else { searchText = entry[1]; } } } } - if(!PolicyUtils.policySpecialCharValidator(searchText).contains(success)){ - message = "The Search value contains space and it is invalid for Search : "+searchText; + if (!PolicyUtils.policySpecialCharValidator(searchText).contains(success)) { + message = "The Search value contains space and it is invalid for Search : " + searchText; validationCheck = false; } - if(searchData.getClosedLooppolicyType() != null){ + if (searchData.getClosedLooppolicyType() != null) { String closedLoopType; - if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ - closedLoopType = "ClosedLoop_Fault"; - }else{ - closedLoopType = "ClosedLoop_PM"; + if ("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())) { + closedLoopType = "ClosedLoop_Fault"; + } else { + closedLoopType = "ClosedLoop_PM"; } searchKeyValue.put("configPolicyType", closedLoopType); } - if(searchData.getOnapName() != null){ + if (searchData.getOnapName() != null) { searchKeyValue.put("onapName", searchData.getOnapName()); } - if(searchData.getD2Service() != null){ + if (searchData.getD2Service() != null) { String d2Service = searchData.getD2Service().trim(); - if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){ + if ("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)) { d2Service = "trinity"; - }else if("vUSP".equalsIgnoreCase(d2Service)){ + } else if ("vUSP".equalsIgnoreCase(d2Service)) { d2Service = "vUSP"; - }else if("MCR".equalsIgnoreCase(d2Service)){ + } else if ("MCR".equalsIgnoreCase(d2Service)) { d2Service = "mcr"; - }else if("Gamma".equalsIgnoreCase(d2Service)){ + } else if ("Gamma".equalsIgnoreCase(d2Service)) { d2Service = "gamma"; - }else if("vDNS".equalsIgnoreCase(d2Service)){ + } else if ("vDNS".equalsIgnoreCase(d2Service)) { d2Service = "vDNS"; } - searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); + searchKeyValue.put("jsonBodyData." + d2Service + "", "true"); } - if(searchData.getVnfType() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*"); + if (searchData.getVnfType() != null) { + searchKeyValue.put(jsonBodyData, "*" + searchData.getVnfType() + "*"); } - if(searchData.getPolicyStatus() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*"); + if (searchData.getPolicyStatus() != null) { + searchKeyValue.put(jsonBodyData, "*" + searchData.getPolicyStatus() + "*"); } - if(searchData.getVproAction() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*"); + if (searchData.getVproAction() != null) { + searchKeyValue.put(jsonBodyData, "*" + searchData.getVproAction() + "*"); } - if(searchData.getServiceType() != null){ + if (searchData.getServiceType() != null) { searchKeyValue.put("serviceType", searchData.getServiceType()); } - if(searchData.getBindTextSearch() != null){ + if (searchData.getBindTextSearch() != null) { searchKeyValue.put(searchData.getBindTextSearch(), searchText); searchText = null; } PolicyIndexType type = null; - if(policyType != null){ - if(action.equalsIgnoreCase(policyType)){ + if (policyType != null) { + if (action.equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.action; - }else if(decision.equalsIgnoreCase(policyType)){ + } else if (decision.equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.decision; - }else if(config.equalsIgnoreCase(policyType)){ + } else if (config.equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.config; - }else if("closedloop".equalsIgnoreCase(policyType)){ + } else if ("closedloop".equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.closedloop; - }else{ + } else { type = ElkConnector.PolicyIndexType.all; } - }else{ + } else { type = ElkConnector.PolicyIndexType.all; } - if(validationCheck){ + if (validationCheck) { JestResult policyResultList = controller.search(type, searchText, searchKeyValue); - if(policyResultList.isSucceeded()){ + if (policyResultList.isSucceeded()) { result = true; policyResult = true; - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject() + .get("hits").getAsJsonArray(); + for (int i = 0; i < resultObject.size(); i++) { String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); policyList.add(policyName); } - }else{ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } else { + LOGGER.error( + "Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); } } - }catch(Exception e){ + } catch (Exception e) { LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); } } - if(validationCheck){ - if(result){ + if (validationCheck) { + if (result) { message = "Elastic Server Transaction is success"; - }else{ + } else { message = "Elastic Server Transaction is failed, please check the logs"; } } @@ -298,22 +300,25 @@ public class PolicyElasticSearchController{ JSONObject j = new JSONObject(msg); response.setStatus(HttpServletResponse.SC_OK); response.addHeader(success, success); - if(policyResult){ + if (policyResult) { JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); response.getWriter().write(k.toString()); - }else{ + } else { response.getWriter().write(j.toString()); } - }catch(Exception e){ + } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); - LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage(),e); + LOGGER.error("Exception Occured While Performing Elastic Transaction" + e.getMessage(), e); } } - @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException { - try{ + @RequestMapping( + value = {"/searchDictionary"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) + throws UnsupportedEncodingException, IOException { + try { PolicyIndexType config = PolicyIndexType.config; PolicyIndexType closedloop = PolicyIndexType.closedloop; PolicyIndexType action = PolicyIndexType.action; @@ -327,105 +332,114 @@ public class PolicyElasticSearchController{ Mode mode = Mode.valueOf(dictionaryType); String value; List<String> policyList = new ArrayList<>(); - switch (mode){ - case attribute : - Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); - value = attributedata.getXacmlId(); - policyList = searchElkDatabase(all, pholder,value); - break; - case onapName : - OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); - value = onapName.getOnapName(); - policyList = searchElkDatabase(all, "onapName",value); - break; - case actionPolicy : - ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); - value = actionPolicyDict.getAttributeName(); - policyList = searchElkDatabase(action, "actionAttributeValue",value); - break; - case brmsParam : - BRMSParamTemplate bRMSParamTemplate = mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); - value = bRMSParamTemplate.getRuleName(); - policyList = searchElkDatabase(config, "ruleName",value); - break; - case pepOptions : - PEPOptions pEPOptions = mapper.readValue(root.get("data").toString(), PEPOptions.class); - value = pEPOptions.getPepName(); - policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); - break; - case clSite : - ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); - value = closedLoopSite.getSiteName(); - policyList = searchElkDatabase(closedloop,"siteNames",value); - break; - case clService : - ClosedLoopD2Services closedLoopD2Services = mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); - value = closedLoopD2Services.getServiceName(); - policyList = searchElkDatabase(closedloop, pholder,value); - break; - case clVarbind : - VarbindDictionary varbindDictionary = mapper.readValue(root.get("data").toString(), VarbindDictionary.class); - value = varbindDictionary.getVarbindName(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case clVnf : - VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class); - value = vNFType.getVnftype(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case clVSCL : - VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class); - value = vsclAction.getVsclaction(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case decision : - DecisionSettings decisionSettings = mapper.readValue(root.get("data").toString(), DecisionSettings.class); - value = decisionSettings.getXacmlId(); - policyList = searchElkDatabase(decision,pholder,value); - break; - case fwTerm : - TermList term = mapper.readValue(root.get("data").toString(), TermList.class); - value = term.getTermName(); - policyList = searchElkDatabase(config, pholder,value); - break; - case msDCAEUUID : - DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class); - value = dcaeUUID.getName(); - policyList = searchElkDatabase(config, "uuid",value); - break; - case msLocation : - MicroServiceLocation mslocation = mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); - value = mslocation.getName(); - policyList = searchElkDatabase(config, "location",value); - break; - case msModels : - MicroServiceModels msModels = mapper.readValue(root.get("data").toString(), MicroServiceModels.class); - value = msModels.getModelName(); - policyList = searchElkDatabase(config, "serviceType",value); - break; - case psGroupPolicy : - GroupPolicyScopeList groupPoilicy = mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); - value = groupPoilicy.getGroupName(); - policyList = searchElkDatabase(config, pholder,value); - break; - case safeRisk : - RiskType riskType= mapper.readValue(root.get("data").toString(), RiskType.class); - value = riskType.getRiskName(); - policyList = searchElkDatabase(config, "riskType",value); - break; - case safePolicyWarning : - SafePolicyWarning safePolicy = mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); - value = safePolicy.getName(); - policyList = searchElkDatabase(config, pholder,value); - break; - default: + switch (mode) { + case attribute: + Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); + value = attributedata.getXacmlId(); + policyList = searchElkDatabase(all, pholder, value); + break; + case onapName: + OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); + value = onapName.getName(); + policyList = searchElkDatabase(all, "onapName", value); + break; + case actionPolicy: + ActionPolicyDict actionPolicyDict = + mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + value = actionPolicyDict.getAttributeName(); + policyList = searchElkDatabase(action, "actionAttributeValue", value); + break; + case brmsParam: + BrmsParamTemplate bRMSParamTemplate = + mapper.readValue(root.get("data").toString(), BrmsParamTemplate.class); + value = bRMSParamTemplate.getRuleName(); + policyList = searchElkDatabase(config, "ruleName", value); + break; + case pepOptions: + PepOptions pEPOptions = mapper.readValue(root.get("data").toString(), PepOptions.class); + value = pEPOptions.getPepName(); + policyList = searchElkDatabase(closedloop, "jsonBodyData.pepName", value); + break; + case clSite: + ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + value = closedLoopSite.getSiteName(); + policyList = searchElkDatabase(closedloop, "siteNames", value); + break; + case clService: + ClosedLoopD2Services closedLoopD2Services = + mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + value = closedLoopD2Services.getServiceName(); + policyList = searchElkDatabase(closedloop, pholder, value); + break; + case clVarbind: + VarbindDictionary varbindDictionary = + mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + value = varbindDictionary.getVarbindName(); + policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*"); + break; + case clVnf: + VnfType vNFType = mapper.readValue(root.get("data").toString(), VnfType.class); + value = vNFType.getType(); + policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*"); + break; + case clVSCL: + VsclAction vsclAction = mapper.readValue(root.get("data").toString(), VsclAction.class); + value = vsclAction.getAction(); + policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*"); + break; + case decision: + DecisionSettings decisionSettings = + mapper.readValue(root.get("data").toString(), DecisionSettings.class); + value = decisionSettings.getXacmlId(); + policyList = searchElkDatabase(decision, pholder, value); + break; + case fwTerm: + TermList term = mapper.readValue(root.get("data").toString(), TermList.class); + value = term.getTermName(); + policyList = searchElkDatabase(config, pholder, value); + break; + case msDCAEUUID: + DcaeUuid dcaeUUID = mapper.readValue(root.get("data").toString(), DcaeUuid.class); + value = dcaeUUID.getName(); + policyList = searchElkDatabase(config, "uuid", value); + break; + case msLocation: + MicroServiceLocation mslocation = + mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + value = mslocation.getName(); + policyList = searchElkDatabase(config, "location", value); + break; + case msModels: + MicroServiceModels msModels = + mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + value = msModels.getModelName(); + policyList = searchElkDatabase(config, "serviceType", value); + break; + case psGroupPolicy: + GroupPolicyScopeList groupPoilicy = + mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + value = groupPoilicy.getGroupName(); + policyList = searchElkDatabase(config, pholder, value); + break; + case safeRisk: + RiskType riskType = mapper.readValue(root.get("data").toString(), RiskType.class); + value = riskType.getName(); + policyList = searchElkDatabase(config, "riskType", value); + break; + case safePolicyWarning: + SafePolicyWarning safePolicy = + mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + value = safePolicy.getName(); + policyList = searchElkDatabase(config, pholder, value); + break; + default: } response.setStatus(HttpServletResponse.SC_OK); response.addHeader(success, success); JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); response.getWriter().write(k.toString()); - }catch(Exception e){ + } catch (Exception e) { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -435,30 +449,31 @@ public class PolicyElasticSearchController{ return null; } - //Search the Elk database - public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){ + // Search the Elk database + public List<String> searchElkDatabase(PolicyIndexType type, String key, String value) { PolicyElasticSearchController controller = new PolicyElasticSearchController(); Map<String, String> searchKeyValue = new HashMap<>(); - if(!pholder.equals(key)){ + if (!pholder.equals(key)) { searchKeyValue.put(key, value); } List<String> policyList = new ArrayList<>(); JestResult policyResultList = controller.search(type, value, searchKeyValue); - if(policyResultList.isSucceeded()){ - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ + if (policyResultList.isSucceeded()) { + JsonArray resultObject = + policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for (int i = 0; i < resultObject.size(); i++) { String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); policyList.add(policyName); } - }else{ + } else { LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); } return policyList; } public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) { - return ElkConnector.singleton.search(type, text, searchKeyValue); + return ElkConnector.singleton.search(type, text, searchKeyValue); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java index 9338cdbbd..95930ede8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; public class PolicyLocator { @@ -27,11 +28,10 @@ public class PolicyLocator { public final String policyId; public final String version; - public PolicyLocator(String policyType, String policyName, - String owner, String scope, String policyId, - String version) { + public PolicyLocator(String policyType, String policyName, String owner, String scope, String policyId, + String version) { this.policyType = policyType; - this.policyName= policyName; + this.policyName = policyName; this.owner = owner; this.scope = scope; this.policyId = policyId; @@ -39,13 +39,8 @@ public class PolicyLocator { } public String toString() { - return "[" + - this.owner + "|" + - this.scope + "|" + - this.policyType + "|" + - this.policyName + "|" + - this.policyId + "|" + - "v" + this.version + "|" + "]"; + return "[" + this.owner + "|" + this.scope + "|" + this.policyType + "|" + this.policyName + "|" + this.policyId + + "|" + "v" + this.version + "|" + "]"; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java index 46c2b1160..4baa13fda 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -21,8 +21,10 @@ package org.onap.policy.pap.xacml.rest.handler; import java.io.IOException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.pap.xacml.rest.service.ImportService; import org.onap.policy.pap.xacml.rest.service.MetricService; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java index fd98279e9..b300f6dd1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +24,16 @@ package org.onap.policy.pap.xacml.rest.handler; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -37,7 +41,7 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; import org.onap.policy.pap.xacml.rest.model.RemoveGroupPolicy; import org.onap.policy.pap.xacml.rest.util.JPAUtils; @@ -450,7 +454,7 @@ public class DeleteHandler { } private String deletePolicyFromPdpGroup(OnapPDPGroup group, OnapLoggingContext loggingContext, String userId) { - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); + PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); String response = null; loggingContext.setServiceName("API:PAP.DeleteHandler"); OnapPDPGroup existingGroup = null; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java index 89ce18835..e9edde66c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,16 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.handler; +import com.att.research.xacml.util.XACMLProperties; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import com.att.research.xacml.util.XACMLProperties; - public interface DictionaryHandler { public static final Logger logger = FlexLogger.getLogger(DictionaryHandler.class); String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName(); @@ -34,13 +35,14 @@ public interface DictionaryHandler { /* * Get Instance */ - public static DictionaryHandler getInstance(){ + public static DictionaryHandler getInstance() { try { - Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); + Class<?> dictionaryHandler = + Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance(); return instance; } catch (Exception e) { - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } return null; } @@ -49,6 +51,7 @@ public interface DictionaryHandler { * Get Equivalent for Dictionary Services. */ public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response); + /* * Put Equivalent for Dictionary Services. */ @@ -59,7 +62,9 @@ public interface DictionaryHandler { * * getflag=true indicates Get Request. * getflag=false indicates Put Request. + * * @return */ - public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag); + public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, + boolean getflag); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java index 5fc737887..f16c2031c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.pap.xacml.rest.service.DictionaryService; @@ -55,7 +56,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler { case "VNFType": dictionary.getVnfType(response); break; - case "PEPOptions": + case "PepOptions": dictionary.getPEPOptions(response); break; case "Varbind": @@ -205,7 +206,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler { case "VNFType": result = dictionary.saveVnfType(request, response); break; - case "PEPOptions": + case "PepOptions": result = dictionary.savePEPOptions(request, response); break; case "Varbind": @@ -313,7 +314,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler { response.addHeader("error", message); return; } - if(("Success").equalsIgnoreCase(result)) { + if (("Success").equalsIgnoreCase(result)) { response.setStatus(HttpServletResponse.SC_OK); response.addHeader("successMapKey", "success"); if (operation.equalsIgnoreCase("update")) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java index ed1c57369..81da91107 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java @@ -21,12 +21,15 @@ package org.onap.policy.pap.xacml.rest.handler; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.net.URI; import java.util.List; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -104,21 +107,22 @@ public class PushPolicyHandler { } } - public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){ + public boolean preSafetyCheck(StdPDPPolicy policy, String configHome) { return true; } - public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){ + public boolean preSafetyCheck(OnapPDPGroup policy, String configHome) { return true; } public static PushPolicyHandler getInstance() { try { - Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); + Class<?> pushPolicyHandler = Class.forName( + XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); return instance; } catch (Exception e) { - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } return null; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java index 90f8b5a70..8a7c60490 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -21,12 +21,15 @@ package org.onap.policy.pap.xacml.rest.handler; import com.att.research.xacml.util.XACMLProperties; + 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.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -45,11 +48,11 @@ public class SavePolicyHandler { String policyType = request.getParameter("policyType"); String apiflag = request.getParameter("apiflag"); PolicyCreation creation = new PolicyCreation(); - if ( policyType != null ) { + if (policyType != null) { PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - if("update".equalsIgnoreCase(operation)){ + if ("update".equalsIgnoreCase(operation)) { policyAdapter.setEditPolicy(true); - }else{ + } else { policyAdapter.setEditPolicy(false); } @@ -58,10 +61,10 @@ public class SavePolicyHandler { // 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() : ""; + json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - if(policyAdapter.isEditPolicy()){ + if (policyAdapter.isEditPolicy()) { PolicyLogger.info("SavePolicyHandler: JSON request from API to update a policy: " + json); } else { PolicyLogger.info("SavePolicyHandler: JSON request from API to create a policy: " + json); @@ -69,67 +72,68 @@ public class SavePolicyHandler { // 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) + // Set policyAdapter values including parentPath (Common to all policy types) try { PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter"); policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag); - if(!extendedPolicyOptions(policyAdapter, response)){ + if (!extendedPolicyOptions(policyAdapter, response)) { creation.savePolicy(policyAdapter, response); } if ("update".equalsIgnoreCase(operation)) { - response.addHeader("operation", "update"); + response.addHeader("operation", "update"); } else { response.addHeader("operation", "create"); } } catch (Exception e1) { - logger.error("Could not set data to policy adapter "+e1.getMessage(),e1); + logger.error("Could not set data to policy adapter " + e1.getMessage(), e1); } } } - private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{ + 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 + // Common among policy types policyAdapter.setPolicyName(policy.getPolicyName()); policyAdapter.setPolicyDescription(policy.getPolicyDescription()); - policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies + policyAdapter.setOnapName(policy.getOnapName()); // 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()); - //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 + // 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.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.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 + // 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 + // Decision Policy Specific policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); policyAdapter.setRuleProvider(policy.getProviderComboBox()); policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); @@ -139,24 +143,25 @@ public class SavePolicyHandler { return policyAdapter; } - public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){ + public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response) { return false; } - public void addErrorHeader(String key, String value){ - if(ErrorHeaders==null){ - ErrorHeaders= new HashMap<>(); + public void addErrorHeader(String key, String value) { + if (ErrorHeaders == null) { + ErrorHeaders = new HashMap<>(); } ErrorHeaders.put(key, value); } public static SavePolicyHandler getInstance() { try { - Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); + Class<?> savePolicyHandler = Class.forName( + XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); return instance; } catch (Exception e) { - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } return null; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java index 42c815aa8..908353ba3 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java @@ -21,17 +21,19 @@ package org.onap.policy.pap.xacml.rest.model; import com.att.research.xacml.api.pap.PDPPolicy; + import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.onap.policy.rest.util.PDPPolicyContainer; + +import org.onap.policy.rest.util.PdpPolicyContainer; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; public class RemoveGroupPolicy { // Container from where we are fetching the policies - private static PDPPolicyContainer policyContainer; + private static PdpPolicyContainer policyContainer; private StdPDPGroup updatedObject; private final StdPDPGroup group; @@ -55,7 +57,7 @@ public class RemoveGroupPolicy { if (this.group == null) { return; } - setRemoveGroupPolicy(new PDPPolicyContainer(group)); + setRemoveGroupPolicy(new PdpPolicyContainer(group)); } /** @@ -69,7 +71,7 @@ public class RemoveGroupPolicy { this.isSaved = true; } - private static void setRemoveGroupPolicy(PDPPolicyContainer pdpPolicyContainer) { + private static void setRemoveGroupPolicy(PdpPolicyContainer pdpPolicyContainer) { RemoveGroupPolicy.policyContainer = pdpPolicyContainer; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java index 51d988887..f5ade96ac 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,4 +17,5 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.model; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index d8a77269c..f2f2e8dbc 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +22,7 @@ package org.onap.policy.pap.xacml.rest.policycontroller; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.File; import java.util.Date; import java.util.HashMap; @@ -28,8 +30,10 @@ import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -45,14 +49,14 @@ import org.onap.policy.pap.xacml.rest.components.FirewallConfigPolicy; import org.onap.policy.pap.xacml.rest.components.MicroServiceConfigPolicy; import org.onap.policy.pap.xacml.rest.components.OptimizationConfigPolicy; import org.onap.policy.pap.xacml.rest.components.Policy; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; import org.onap.policy.pap.xacml.rest.util.AbstractPolicyCreation; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionPolicyDict; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; @@ -68,37 +72,68 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; - +/** + * The Class PolicyCreation. + */ @RestController @RequestMapping("/") -public class PolicyCreation extends AbstractPolicyCreation{ +public class PolicyCreation extends AbstractPolicyCreation { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); - private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); + // Recurring constants + private static final String INVALID_ATTRIBUTE = "invalidAttribute"; + private static final String SUCCESS = "success"; + private static final String ERROR = "error"; + private static final String POLICY_NAME = "policyName"; private String ruleID = ""; - private PolicyDBDao policyDBDao; - String CLName = null; + private String clName = null; private static CommonClassDao commonClassDao; + /** + * Gets the common class dao. + * + * @return the common class dao + */ public static CommonClassDao getCommonClassDao() { return commonClassDao; } + /** + * Sets the common class dao. + * + * @param commonClassDao the new common class dao + */ public static void setCommonClassDao(CommonClassDao commonClassDao) { PolicyCreation.commonClassDao = commonClassDao; } + /** + * Instantiates a new policy creation. + * + * @param commonClassDao the common class dao + */ @Autowired - public PolicyCreation(CommonClassDao commonClassDao){ + public PolicyCreation(CommonClassDao commonClassDao) { PolicyCreation.commonClassDao = commonClassDao; } - public PolicyCreation(){} - - @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST) + /** + * Instantiates a new policy creation. + */ + public PolicyCreation() {} + + /** + * Save policy. + * + * @param policyData the policy data + * @param response the response + * @return the response entity + */ + @RequestMapping(value = "/policycreation/save_policy", method = RequestMethod.POST) @ResponseBody - public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){ + public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) { String body = null; HttpStatus status = HttpStatus.BAD_REQUEST; Map<String, String> successMap = new HashMap<>(); @@ -110,11 +145,11 @@ public class PolicyCreation extends AbstractPolicyCreation{ String policyConfigType = null; String userId = policyData.getUserId(); - if (policyData.getTtlDate()==null){ + if (policyData.getTtlDate() == null) { policyData.setTtlDate("NA"); - }else{ - String dateTTL = policyData.getTtlDate(); - String newDate = convertDate(dateTTL); + } else { + String dateTtl = policyData.getTtlDate(); + String newDate = convertDate(dateTtl); policyData.setTtlDate(newDate); } @@ -125,19 +160,19 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyConfigType = policyData.getConfigPolicyType(); if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_FW_"; - }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_Fault_"; - }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_PM_"; - }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { + } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_MS_"; - }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + } else if ("Optimization".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_OOF_"; - }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_BRMS_Raw_"; - }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_BRMS_Param_"; - }else { + } else { filePrefix = "Config_"; } } else if ("Action".equalsIgnoreCase(policyType)) { @@ -151,8 +186,9 @@ public class PolicyCreation extends AbstractPolicyCreation{ String createdBy; String modifiedBy; String scopeCheck = policyData.getDomainDir().replace(".", File.separator); - PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); - if(policyEditorScope == null){ + PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao + .getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); + if (policyEditorScope == null) { UserInfo userInfo = new UserInfo(); userInfo.setUserName("API"); userInfo.setUserLoginId("API"); @@ -162,21 +198,22 @@ public class PolicyCreation extends AbstractPolicyCreation{ editorScope.setUserModifiedBy(userInfo); commonClassDao.save(editorScope); } - //get the highest version of policy from policy version table. - String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); + // get the highest version of policy from policy version table. + String dbCheckPolicyName = + policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName); - if(policyVersion == null){ + if (policyVersion == null) { highestVersion = 0; - }else{ + } else { highestVersion = policyVersion.getHigherVersion(); } - if(highestVersion != 0 && policyVersion != null){ - if(policyData.isEditPolicy()){ - version = highestVersion +1; - if(userId ==null){ + if (highestVersion != 0 && policyVersion != null) { + if (policyData.isEditPolicy()) { + version = highestVersion + 1; + if (userId == null) { modifiedBy = "API"; - }else{ + } else { modifiedBy = userId; } policyData.setUserId("API"); @@ -186,30 +223,31 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyVersionDao.setHigherVersion(version); policyVersionDao.setModifiedBy(modifiedBy); policyVersionDao.setModifiedDate(new Date()); - }else{ + } else { body = "policyExists"; status = HttpStatus.CONFLICT; response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "policyExists"); - response.addHeader("policyName", policyData.getPolicyName()); + response.addHeader(ERROR, "policyExists"); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); return new ResponseEntity<>(body, status); } - }else{ + } else { // if policy does not exist and the request is updatePolicy return error - if(policyData.isEditPolicy()){ + if (policyData.isEditPolicy()) { body = "policyNotAvailableForEdit"; status = HttpStatus.NOT_FOUND; response.setStatus(HttpServletResponse.SC_NOT_FOUND); - response.addHeader("error", body); - response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); + response.addHeader(ERROR, body); + response.addHeader("message", + policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); return new ResponseEntity<>(body, status); } version = 1; - if(userId == null){ + if (userId == null) { createdBy = "API"; modifiedBy = "API"; policyData.setUserId("API"); - }else{ + } else { createdBy = userId; modifiedBy = userId; policyData.setUserId("API"); @@ -225,15 +263,16 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyData.setPolicyID(newPolicyID()); policyData.setRuleID(ruleID); - String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml"; + String policyFileName = dbCheckPolicyName.replace(File.separator, ".") + "." + version + ".xml"; policyData.setNewFileName(policyFileName); - policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + policyData.setPolicyDescription(policyData.getPolicyDescription() + "@CreatedBy:" + createdBy + + "@CreatedBy:" + "@ModifiedBy:" + modifiedBy + "@ModifiedBy:"); policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); - if(policyData.getApiflag() == null){ - //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON - if(policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ + if (policyData.getApiflag() == null) { + // set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + if (policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()) { + for (Object attribute : policyData.getAttributes()) { + if (attribute instanceof LinkedHashMap<?, ?>) { String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); attributeMap.put(key, value); @@ -250,97 +289,105 @@ public class PolicyCreation extends AbstractPolicyCreation{ if ("Config".equalsIgnoreCase(policyType)) { if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { newPolicy = new FirewallConfigPolicy(policyData); - }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_RAW_RULE"); newPolicy = new CreateBrmsRawPolicy(policyData); - }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_PARAM_RULE"); - Map<String, String> drlRuleAndUIParams = new HashMap<>(); - if(policyData.getApiflag() == null){ + Map<String, String> drlRuleAndUiParams = new HashMap<>(); + if (policyData.getApiflag() == null) { // If there is any dynamic field create the matches here - String key="templateName"; - String value= policyData.getRuleName(); - drlRuleAndUIParams.put(key, value); - if(policyData.getRuleData().size() > 0){ - for(Object keyValue: policyData.getRuleData().keySet()){ - drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); + String key = "templateName"; + String value = policyData.getRuleName(); + drlRuleAndUiParams.put(key, value); + if (policyData.getRuleData().size() > 0) { + for (Object keyValue : policyData.getRuleData().keySet()) { + drlRuleAndUiParams.put(keyValue.toString(), + policyData.getRuleData().get(keyValue).toString()); } } - policyData.setBrmsParamBody(drlRuleAndUIParams); - }else{ - drlRuleAndUIParams=policyData.getBrmsParamBody(); - String modelName= drlRuleAndUIParams.get("templateName"); - PolicyLogger.info("Template name from API is: "+modelName); - - BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); - if(template == null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " - + modelName + " was not found in the dictionary."; + policyData.setBrmsParamBody(drlRuleAndUiParams); + } else { + drlRuleAndUiParams = policyData.getBrmsParamBody(); + String modelName = drlRuleAndUiParams.get("templateName"); + PolicyLogger.info("Template name from API is: " + modelName); + + BrmsParamTemplate template = (BrmsParamTemplate) commonClassDao + .getEntityItem(BrmsParamTemplate.class, "ruleName", modelName); + if (template == null) { + String message = + XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + + modelName + " was not found in the dictionary."; body = message; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); + response.addHeader(ERROR, message); response.addHeader("modelName", modelName); - return new ResponseEntity<String>(body, status); + return new ResponseEntity<>(body, status); } } newPolicy = new CreateBrmsParamPolicy(policyData); - }else if ("Base".equalsIgnoreCase(policyConfigType)) { - newPolicy = new ConfigPolicy(policyData); - }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { + } else if ("Base".equalsIgnoreCase(policyConfigType)) { + newPolicy = new ConfigPolicy(policyData); + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { newPolicy = new ClosedLoopPolicy(policyData); - }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { - if(policyData.getApiflag() == null){ - policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { + if (policyData.getApiflag() == null) { + policyData.setServiceType( + policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); ObjectMapper jsonMapper = new ObjectMapper(); String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); - jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); + jsonBody = jsonBody.replaceFirst("\\{", + "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); policyData.setJsonBody(jsonBody); } newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); - }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { + } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { newPolicy = new MicroServiceConfigPolicy(policyData); - }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + } else if ("Optimization".equalsIgnoreCase(policyConfigType)) { newPolicy = new OptimizationConfigPolicy(policyData); } - }else if("Action".equalsIgnoreCase(policyType)) { - if(policyData.getApiflag() == null){ + } else if ("Action".equalsIgnoreCase(policyType)) { + if (policyData.getApiflag() == null) { List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); - - if(!policyData.getRuleAlgorithmschoices().isEmpty()){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap<?, ?>){ + if (!policyData.getRuleAlgorithmschoices().isEmpty()) { + for (Object attribute : policyData.getRuleAlgorithmschoices()) { + if (attribute instanceof LinkedHashMap<?, ?>) { String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); - String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); dynamicRuleAlgorithmLabels.add(label); + String key = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); dynamicRuleAlgorithmField1.add(key); + String rule = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); dynamicRuleAlgorithmCombo.add(rule); + String value = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); dynamicRuleAlgorithmField2.add(value); } } } String actionDictValue = policyData.getActionAttributeValue(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); - if(jsonData!=null){ - String actionBodyString = jsonData.getBody(); + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, + "attributeName", actionDictValue)); + if (jsonData != null) { String actionDictHeader = jsonData.getHeader(); - String actionDictType = jsonData.getType(); - String actionDictUrl = jsonData.getUrl(); - String actionDictMethod = jsonData.getMethod(); policyData.setActionDictHeader(actionDictHeader); + String actionDictType = jsonData.getType(); policyData.setActionDictType(actionDictType); + String actionDictUrl = jsonData.getUrl(); policyData.setActionDictUrl(actionDictUrl); + String actionDictMethod = jsonData.getMethod(); policyData.setActionDictMethod(actionDictMethod); + String actionBodyString = jsonData.getBody(); if (actionBodyString != null) { policyData.setActionBody(actionBodyString); } @@ -350,11 +397,12 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - }else{ + } else { // API request. String comboDictValue = policyData.getActionAttribute(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue)); - if(jsonData!=null){ + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, + "attributeName", comboDictValue)); + if (jsonData != null) { policyData.setActionBody(jsonData.getBody()); policyData.setActionDictHeader(jsonData.getHeader()); policyData.setActionDictType(jsonData.getType()); @@ -364,37 +412,37 @@ public class PolicyCreation extends AbstractPolicyCreation{ } newPolicy = new ActionPolicy(policyData, commonClassDao); } else if ("Decision".equalsIgnoreCase(policyType)) { - if(policyData.getApiflag() == null){ - Map<String, String> settingsMap = new HashMap<>(); + if (policyData.getApiflag() == null) { Map<String, String> treatmentMap = new HashMap<>(); - List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); - List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); - List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); - List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); - List<Object> dynamicVariableList = new LinkedList<>(); - List<String> dataTypeList = new LinkedList<>(); - List<String> errorCodeList = new LinkedList<>(); - List<String> treatmentList = new LinkedList<>(); - - if(!policyData.getSettings().isEmpty()){ - for(Object settingsData : policyData.getSettings()){ - if(settingsData instanceof LinkedHashMap<?, ?>){ + Map<String, String> settingsMap = new HashMap<>(); + if (!policyData.getSettings().isEmpty()) { + for (Object settingsData : policyData.getSettings()) { + if (settingsData instanceof LinkedHashMap<?, ?>) { String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString(); String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString(); settingsMap.put(key, value); } } } - if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap<?, ?>){ + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); + List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); + if (policyData.getRuleAlgorithmschoices() != null + && !policyData.getRuleAlgorithmschoices().isEmpty()) { + for (Object attribute : policyData.getRuleAlgorithmschoices()) { + if (attribute instanceof LinkedHashMap<?, ?>) { String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); - String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); dynamicRuleAlgorithmLabels.add(label); + String key = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); dynamicRuleAlgorithmField1.add(key); + String rule = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); dynamicRuleAlgorithmCombo.add(rule); + String value = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); dynamicRuleAlgorithmField2.add(value); } } @@ -455,6 +503,11 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } + List<Object> dynamicVariableList = new LinkedList<>(); + List<String> dataTypeList = new LinkedList<>(); + List<String> errorCodeList = new LinkedList<>(); + List<String> treatmentList = new LinkedList<>(); + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); @@ -470,125 +523,143 @@ public class PolicyCreation extends AbstractPolicyCreation{ newPolicy = new DecisionPolicy(policyData); } - if(newPolicy != null){ + if (newPolicy != null) { newPolicy.prepareToSave(); - }else{ - body = "error"; + } else { + body = ERROR; status = HttpStatus.INTERNAL_SERVER_ERROR; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); + response.addHeader(ERROR, ERROR); return new ResponseEntity<>(body, status); } - PolicyDBDaoTransaction policyDBDaoTransaction = null; - try{ - policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(); - policyDBDaoTransaction = policyDBDao.getNewTransaction(); - policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); + PolicyDbDaoTransaction policyDbDaoTransaction = null; + try { + PolicyDbDao policyDbDao = PolicyDbDao.getPolicyDbDaoInstance(); + policyDbDaoTransaction = policyDbDao.getNewTransaction(); + policyDbDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); successMap = newPolicy.savePolicies(); - if(successMap.containsKey("success")){ - policyDBDaoTransaction.commitTransaction(); - if(policyData.isEditPolicy()){ + if (successMap.containsKey(SUCCESS)) { + policyDbDaoTransaction.commitTransaction(); + if (policyData.isEditPolicy()) { commonClassDao.update(policyVersionDao); - }else{ + } else { commonClassDao.save(policyVersionDao); } - try{ - PolicyElasticSearchController search= new PolicyElasticSearchController(); + try { + PolicyElasticSearchController search = new PolicyElasticSearchController(); search.updateElk(policyData); - }catch(Exception e){ - LOGGER.error("Error Occured while saving policy to Elastic Database"+e); + } catch (Exception e) { + LOGGER.error("Error Occured while saving policy to Elastic Database" + e); } - body = "success"; + body = SUCCESS; status = HttpStatus.OK; response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("policyName", policyData.getNewFileName()); + response.addHeader("successMapKey", SUCCESS); + response.addHeader(POLICY_NAME, policyData.getNewFileName()); - //get message from the SafetyCheckerResults if present + // get message from the SafetyCheckerResults if present String safetyCheckerResponse = policyData.getClWarning(); - String existingCLName = policyData.getExistingCLName(); + String existingClName = policyData.getExistingCLName(); - //if safetyCheckerResponse is not null add a header to send back with response - if(safetyCheckerResponse!=null) { + // if safetyCheckerResponse is not null add a header to send back with response + if (safetyCheckerResponse != null) { PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse); response.addHeader("safetyChecker", safetyCheckerResponse); - response.addHeader("newCLName", CLName); - response.addHeader("conflictCLName", existingCLName); + response.addHeader("newCLName", clName); + response.addHeader("conflictCLName", existingClName); } else { PolicyLogger.info("SafetyCheckerResponse was empty or null."); } - }else if (successMap.containsKey("invalidAttribute")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); - body = "invalidAttribute"; + } else if (successMap.containsKey(INVALID_ATTRIBUTE)) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + + policyData.getActionAttribute() + " in the ActionPolicyDict table."); + body = INVALID_ATTRIBUTE; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("invalidAttribute", policyData.getActionAttribute()); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - }else if (successMap.containsKey("fwdberror")) { - policyDBDaoTransaction.rollbackTransaction(); + response.addHeader(INVALID_ATTRIBUTE, policyData.getActionAttribute()); + + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; + response.addHeader(ERROR, message); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); + } else if (successMap.containsKey("fwdberror")) { + policyDbDaoTransaction.rollbackTransaction(); body = "fwdberror"; status = HttpStatus.BAD_REQUEST; String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into the database."; PolicyLogger.error(message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - } else if (successMap.get("error").equals("Validation Failed")) { - policyDBDaoTransaction.rollbackTransaction(); - String message = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Error Validating the Policy on the PAP."; + response.addHeader(ERROR, message); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); + } else if (successMap.get(ERROR).equals("Validation Failed")) { + policyDbDaoTransaction.rollbackTransaction(); + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Validating the Policy on the PAP."; PolicyLogger.error(message); body = "Validation"; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - }else { - policyDBDaoTransaction.rollbackTransaction(); - body = "error"; + response.addHeader(ERROR, message); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); + } else { + policyDbDaoTransaction.rollbackTransaction(); + body = ERROR; status = HttpStatus.INTERNAL_SERVER_ERROR; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); + response.addHeader(ERROR, ERROR); } - }catch(Exception e){ - LOGGER.error("Exception Occured : ",e); - if(policyDBDaoTransaction != null){ - policyDBDaoTransaction.rollbackTransaction(); + } catch (Exception e) { + LOGGER.error("Exception Occured : ", e); + if (policyDbDaoTransaction != null) { + policyDbDaoTransaction.rollbackTransaction(); } } - } - catch (Exception e){ - LOGGER.error("Exception Occured : "+e.getMessage(),e); - body = "error"; - response.addHeader("error", e.getMessage()); + } catch (Exception e) { + LOGGER.error("Exception Occured : " + e.getMessage(), e); + body = ERROR; + // + // Because we are catching any old exception instead of a dedicated exception, + // its possible the e.getMessage() returns a null value. You cannot add a header + // to the response with a null value, it will throw an exception. This is something + // this is undesirable. + // + response.addHeader(ERROR, (e.getMessage() == null ? "missing exception message" : e.getMessage())); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(body, status); } + /** + * Message not readable exception handler. + * + * @param req the req + * @param exception the exception + * @return the response entity + */ @ExceptionHandler({ HttpMessageNotReadableException.class }) - public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { + public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, + HttpMessageNotReadableException exception) { LOGGER.error("Request not readable: {}", exception); StringBuilder message = new StringBuilder(); message.append(exception.getMessage()); if (exception.getCause() != null) { - message.append(" Reason Caused: " - + exception.getCause().getMessage()); + message.append(" Reason Caused: " + exception.getCause().getMessage()); } return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); } - public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){ - PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); - if (entityItem != null) { - if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ - return entityItem; - } + /** + * Gets the policy version data. + * + * @param dbCheckPolicyName the db check policy name + * @return the policy version data + */ + public PolicyVersion getPolicyVersionData(String dbCheckPolicyName) { + PolicyVersion entityItem = + (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, POLICY_NAME, dbCheckPolicyName); + if (entityItem != null && entityItem.getPolicyName().equals(dbCheckPolicyName)) { + return entityItem; } return entityItem; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java index bb5307573..6c0891513 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,4 +17,5 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.pap.xacml.rest.policycontroller;
\ No newline at end of file + +package org.onap.policy.pap.xacml.rest.policycontroller; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java index 2dea96517..45e82cc54 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -21,8 +21,10 @@ package org.onap.policy.pap.xacml.rest.service; import java.io.IOException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; import org.onap.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; @@ -37,7 +39,6 @@ import org.onap.policy.pap.xacml.rest.controller.SafePolicyController; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; - // TODO: Auto-generated Javadoc /** * The Class DictionaryService. @@ -387,8 +388,6 @@ public class DictionaryService { return result.getViewName(); } - - /** * Save micro service location dictionary. * @@ -608,7 +607,6 @@ public class DictionaryService { return result.getViewName(); } - /** * Gets the onap dictionary. * @@ -854,7 +852,6 @@ public class DictionaryService { dictionary.getTermListDictionaryEntityData(response); } - /** * Gets the micro service location dictionary. * diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java index 01fbff7ce..050bcc561 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -30,6 +30,7 @@ import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -72,7 +73,8 @@ public class ImportService { StringBuilder builder = new StringBuilder(); int ch; try { - while ((ch = request.getInputStream().read()) != -1) { + ServletInputStream stream = request.getInputStream(); + while ((ch = stream.read()) != -1) { builder.append((char) ch); } } catch (IOException e) { @@ -84,8 +86,7 @@ public class ImportService { response.addHeader(service, serviceName); } CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); - successMap = - brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); + successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); } else if (("MICROSERVICE").equals(importServiceCreation)) { CreateNewMicroServiceModel newMS = null; String randomID = UUID.randomUUID().toString(); @@ -114,8 +115,7 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Service"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID + type), - "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), "utf-8"))) { writer.write(xmi); } catch (IOException e) { logger.error(e); @@ -125,7 +125,7 @@ public class ImportService { } else { InputStream inputStream = null; try (FileOutputStream outputStream = - new FileOutputStream(extractDir + File.separator + randomID + ".zip")) { + new FileOutputStream(extractDir + File.separator + randomID + ".zip")) { inputStream = request.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; @@ -141,14 +141,12 @@ public class ImportService { inputStream.close(); } } catch (IOException e) { - PolicyLogger.error( - "Exception Occured while closing the input/output stream" + e); + PolicyLogger.error("Exception Occured while closing the input/output stream" + e); } } } - newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, - randomID); + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); successMap = newMS.addValuesToNewModel(type); @@ -180,8 +178,7 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Optimization Service Model"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID + type), - "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), "utf-8"))) { writer.write(yml); } catch (IOException e) { logger.error(e); @@ -189,8 +186,7 @@ public class ImportService { return; } - newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", - version, randomID); + newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); successMap = newOOF.addValuesToNewModel(); if (successMap.containsKey(successMessage)) { successMap.clear(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java index 0a539dcbb..36dd5fdee 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.service; import com.att.research.xacml.api.pap.PDPPolicy; +import com.google.common.annotations.VisibleForTesting; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -48,8 +49,9 @@ public class MetricService { } + @VisibleForTesting @Autowired - private MetricService(CommonClassDao commonClassDao) { + protected MetricService(CommonClassDao commonClassDao) { MetricService.commonClassDao = commonClassDao; } @@ -76,7 +78,7 @@ public class MetricService { json.put("totalCount", totalCount); if (pdpCount > 0 && papCount > 0 && totalCount > 0) { PolicyLogger.info( - "Metrics have been found on the Policy Engine for the number of policies on the PAP and PDP."); + "Metrics have been found on the Policy Engine for the number of policies on the PAP and PDP."); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("successMapKey", "success"); response.addHeader("operation", "getMetrics"); @@ -84,7 +86,7 @@ public class MetricService { return; } else { String message = - "The policy count on the PAP and PDP is 0. Please check the database and file system to correct this error."; + "The policy count on the PAP and PDP is 0. Please check the database and file system to correct this error."; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader(errorMsg, message); return; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java index f411e7d98..db68fb29f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,82 +17,83 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.util; +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Joiner; import java.util.UUID; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.springframework.stereotype.Component; -import com.att.research.xacml.util.XACMLProperties; -import com.google.common.base.Joiner; - @Component public abstract class AbstractPolicyCreation { public static String getDomain() { - return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + return XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_DOMAIN, "urn"); } public String newPolicyID() { - return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"), + return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null : "urn"), getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); } public String convertDate(String dateTTL) { String formateDate = null; - if(dateTTL.contains("/")){ + if (dateTTL.contains("/")) { formateDate = dateTTL.replace("/", "-"); - }else { + } else { formateDate = dateTTL; } return formateDate; } - - - public void updatePolicyCreationToDatabase(){ + public void updatePolicyCreationToDatabase() { // Add it into our tree -/* Path finalPolicyPath = null; - finalPolicyPath = Paths.get(successMap.get("success")); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - controller.updateElk(finalPolicyPath.toString()); - File file = finalPolicyPath.toFile(); - if(file != null){ - String policyName = file.toString(); - String removePath = policyName.substring(policyName.indexOf("repository")+11); - String removeXml = removePath.replace(".xml", ""); - String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); - List<Object> policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", removeExtension); - if (policyVersionList.size() > 0) { - for(int i = 0; i < policyVersionList.size(); i++) { - PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); - if(entityItem.getPolicyName().equals(removeExtension)){ - version = entityItem.getHigherVersion() +1; - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setModifiedBy(userId); - commonClassDao.update(entityItem); - if(policyData.isEditPolicy){ - PolicyNotificationMail email = new PolicyNotificationMail(); - String mode = "EditPolicy"; - String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; - email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); - } - } - } - }else{ - PolicyVersion entityItem = new PolicyVersion(); - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setPolicyName(removeExtension); - entityItem.setCreatedBy(userId); - entityItem.setModifiedBy(userId); - commonClassDao.save(entityItem); - } - }*/ + /* + * Path finalPolicyPath = null; + * finalPolicyPath = Paths.get(successMap.get("success")); + * PolicyElasticSearchController controller = new PolicyElasticSearchController(); + * controller.updateElk(finalPolicyPath.toString()); + * File file = finalPolicyPath.toFile(); + * if(file != null){ + * String policyName = file.toString(); + * String removePath = policyName.substring(policyName.indexOf("repository")+11); + * String removeXml = removePath.replace(".xml", ""); + * String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + * List<Object> policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", + * removeExtension); + * if (policyVersionList.size() > 0) { + * for(int i = 0; i < policyVersionList.size(); i++) { + * PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); + * if(entityItem.getPolicyName().equals(removeExtension)){ + * version = entityItem.getHigherVersion() +1; + * entityItem.setActiveVersion(version); + * entityItem.setHigherVersion(version); + * entityItem.setModifiedBy(userId); + * commonClassDao.update(entityItem); + * if(policyData.isEditPolicy){ + * PolicyNotificationMail email = new PolicyNotificationMail(); + * String mode = "EditPolicy"; + * String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + + * ".xml"; + * email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); + * } + * } + * } + * }else{ + * PolicyVersion entityItem = new PolicyVersion(); + * entityItem.setActiveVersion(version); + * entityItem.setHigherVersion(version); + * entityItem.setPolicyName(removeExtension); + * entityItem.setCreatedBy(userId); + * entityItem.setModifiedBy(userId); + * commonClassDao.save(entityItem); + * } + * } + */ } - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java index e88efa931..ec27e0304 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java @@ -23,14 +23,17 @@ package org.onap.policy.pap.xacml.rest.util; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; @@ -80,8 +83,7 @@ public class DictionaryUtils { } public boolean isRequestFromAPI(HttpServletRequest request) { - return request.getParameter(apiflag) != null - && "api".equalsIgnoreCase(request.getParameter(apiflag)); + return request.getParameter(apiflag) != null && "api".equalsIgnoreCase(request.getParameter(apiflag)); } public String appendKey(List<Object> objects, String key1, String appendValue) { @@ -134,8 +136,7 @@ public class DictionaryUtils { } public Category getCategory() { - return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource") - .get(0); + return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); } public ModelAndView getResultForApi(String inResponseString) { @@ -148,8 +149,7 @@ public class DictionaryUtils { return result; } - public void setResponseData(HttpServletResponse response, String key, String responseString) - throws IOException { + public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException { response.setCharacterEncoding(utf8); response.setContentType(applicationJsonContentType); @@ -166,13 +166,11 @@ public class DictionaryUtils { } @SuppressWarnings("rawtypes") - public void getDataByEntity(HttpServletResponse response, String key, String value, - Class className) { + public void getDataByEntity(HttpServletResponse response, String key, String value, Class className) { try { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - model.put(key, - mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); + model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); @@ -206,8 +204,7 @@ public class DictionaryUtils { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - commonClassDao - .delete(mapper.readValue(root.get("data").toString(), className)); + commonClassDao.delete(mapper.readValue(root.get("data").toString(), className)); String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); setResponseData(response, key, responseString); } catch (Exception e) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java index cb9abb9db..efb8287f0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.util; import java.util.List; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.XacmlAdminAuthorization; @@ -41,7 +42,6 @@ public class JPAUtils { JPAUtils.commonClassDao = commonClassDao; } - /** * Get an instance of a JPAUtils. It creates one if it does not exist. Only one instance is allowed * to be created per server. diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java index 6ea0c79ee..cafeb0c92 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -25,17 +25,19 @@ public class JsonMessage { private String data; private String data2; private String data3; + public JsonMessage(String data) { super(); this.data = data; } - public JsonMessage(String data,String data2) { + + public JsonMessage(String data, String data2) { super(); this.data = data; this.data2 = data2; } - public JsonMessage(String data,String data2,String data3) { + public JsonMessage(String data, String data2, String data3) { super(); this.data = data; this.data2 = data2; @@ -49,19 +51,21 @@ public class JsonMessage { public void setData(String data) { this.data = data; } + public String getData2() { return data2; } + public void setData2(String data2) { this.data2 = data2; } + public String getData3() { return data3; } + public void setData3(String data3) { this.data3 = data3; } - } - diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java index 10cc81549..4e938acff 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java @@ -21,16 +21,18 @@ package org.onap.policy.pap.xacml.restAuth; import com.att.research.xacml.util.XACMLProperties; + import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.StringTokenizer; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.utils.PeCryptoUtils; public class AuthenticationService { - private String papId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + private String papId = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID); private String papPass = null; /** @@ -49,9 +51,9 @@ public class AuthenticationService { String usernameAndPassword = null; try { - String secretKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY); + String secretKey = XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY); PeCryptoUtils.initAesKey(secretKey); - papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); + papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)); } catch (Exception e) { PolicyLogger.error(e); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java index 181dd0910..ab1576715 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.restAuth; import com.att.research.xacml.api.pap.PAPException; + import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -37,6 +38,7 @@ import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.Properties; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -73,19 +75,20 @@ public class CheckPDP { String pdpFile = XACMLPapServlet.getPDPFile(); if (pdpFile == null) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); } if (pdpPath == null) { pdpPath = Paths.get(pdpFile); if (Files.notExists(pdpPath)) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "File doesn't exist in the specified Path : " + pdpPath.toString()); } if (pdpPath.toString().endsWith(".properties")) { readProps(); } else { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); } } // Check if File is updated recently @@ -98,7 +101,7 @@ public class CheckPDP { } } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) private static void readProps() throws PAPException { InputStream in; pdpProp = new Properties(); @@ -137,45 +140,47 @@ public class CheckPDP { } if (pdpMap == null || pdpMap.isEmpty()) { logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); } } - private static void readPDPParam(String pdpVal) throws PAPException{ - if(pdpVal.contains(",")){ + private static void readPDPParam(String pdpVal) throws PAPException { + if (pdpVal.contains(",")) { List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ + if (pdpValues.size() == 3) { // 1:2 will be UserID:Password String userID = pdpValues.get(1); String pass = PeCryptoUtils.decrypt(pdpValues.get(2)); Base64.Encoder encoder = Base64.getEncoder(); // 0 - PDPURL - pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ + pdpMap.put(pdpValues.get(0), + encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); + } else { PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request"); - throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + throw new PAPException( + XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); } - }else{ + } else { PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); - throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request."); } } - public static String getEncoding(String pdpID){ + public static String getEncoding(String pdpID) { try { readFile(); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file"); } String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ + if (pdpMap != null && (!pdpMap.isEmpty())) { + try { encoding = pdpMap.get(pdpID); - } catch(Exception e){ + } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding"); } return encoding; - }else{ + } else { return null; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java index 94cd9c798..323b89a01 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -41,13 +41,12 @@ import org.apache.commons.logging.LogFactory; @WebFilter("/*") public class PAPAuthenticationFilter implements Filter { - private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); + private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); public static final String AUTHENTICATION_HEADER = "Authorization"; @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filter) throws IOException, ServletException { - + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) + throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; @@ -57,7 +56,7 @@ public class PAPAuthenticationFilter implements Filter { logger.info("Request URI: " + url); - //getting authentication credentials + // getting authentication credentials authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); // Check Authentication credentials @@ -65,17 +64,17 @@ public class PAPAuthenticationFilter implements Filter { boolean authenticationStatus = authenticationService.authenticate(authCredentials); if (authenticationStatus) { - //indicates the request comes from Traditional Admin Console or PolicyEngineAPI - if ("/pap/".equals(url)){ + // indicates the request comes from Traditional Admin Console or PolicyEngineAPI + if ("/pap/".equals(url)) { logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI"); - //forward request to the XACMLPAPServlet if authenticated + // forward request to the XACMLPAPServlet if authenticated request.getRequestDispatcher("/pap/pap/").forward(request, response); - }else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse){ - //indicates the request comes from the ONAP Portal onap-sdk-app - HttpServletResponse alteredResponse = ((HttpServletResponse)response); + } else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse) { + // indicates the request comes from the ONAP Portal onap-sdk-app + HttpServletResponse alteredResponse = ((HttpServletResponse) response); addCorsHeader(alteredResponse); logger.info("Request comes from Onap Portal"); - //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path + // Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path filter.doFilter(request, response); } } else { @@ -88,22 +87,23 @@ public class PAPAuthenticationFilter implements Filter { } } - //method to add CorsHeaders for onap portal rest call + // method to add CorsHeaders for onap portal rest call private void addCorsHeader(HttpServletResponse response) { logger.info("Adding Cors Response Headers!!!"); response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD"); - response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); - response.addHeader("Access-Control-Max-Age", "1728000"); + response.addHeader("Access-Control-Allow-Headers", + "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); + response.addHeader("Access-Control-Max-Age", "1728000"); } @Override public void destroy() { - //Empty + // Empty } @Override public void init(FilterConfig arg0) throws ServletException { - //Empty + // Empty } } |