diff options
Diffstat (limited to 'ONAP-PAP-REST/src')
5 files changed, 629 insertions, 39 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 41c91ec27..52e4060b5 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 @@ -185,7 +185,8 @@ public class ConsoleAndApiService { if (policyId.contains("Config_MS_") || policyId.contains("BRMS_Param")) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); policyForSafetyCheck.setId(policyId); - if (pushPolicyHandler.preSafetyCheck(policyForSafetyCheck, XACMLPapServlet.getConfigHome())) { + if (pushPolicyHandler.preSafetyCheck(policyForSafetyCheck, + XACMLPapServlet.getConfigHome())) { LOGGER.debug("Precheck Successful."); } } @@ -218,8 +219,8 @@ public class ConsoleAndApiService { } /* - * If request comes from the API we need to run the PolicyDBDao updateGroup() to - * notify other paps of the change. The GUI does this from the POLICY-SDK-APP code. + * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of + * the change. The GUI does this from the POLICY-SDK-APP code. */ // Get new transaction to perform updateGroup() @@ -288,7 +289,8 @@ 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 = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDBDaoTransaction setDefaultGroupTransaction = + XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { setDefaultGroupTransaction.changeDefaultGroup(group, PAPSERVLETDOACPOST); papEngine.setDefaultGroup(group); @@ -587,6 +589,7 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message); + acPutTransaction.rollbackTransaction(); return; } if (request.getParameter("policy") != null) { @@ -601,6 +604,7 @@ public class ConsoleAndApiService { PolicyLogger.audit(TRANSACTIONFAILED); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); + acPutTransaction.rollbackTransaction(); return; } else if (request.getParameter("pdpId") != null) { // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP @@ -708,6 +712,7 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + acPutTransaction.rollbackTransaction(); return; } else { // Assume that this is an update of an existing PDP Group @@ -824,6 +829,7 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'"); + removePdpOrGroupTransaction.rollbackTransaction(); return; } // determine the operation needed based on the parameters in the @@ -836,6 +842,7 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + removePdpOrGroupTransaction.rollbackTransaction(); return; } else if (request.getParameter("pdpId") != null) { // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP @@ -865,6 +872,7 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + removePdpOrGroupTransaction.rollbackTransaction(); return; } else { // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> 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 571a82036..780ed86c7 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 @@ -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,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; @@ -31,18 +32,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; - -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.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.FunctionDefinition; -import org.onap.policy.xacml.api.XACMLErrorConstants; - -import com.att.research.xacml.api.pap.PAPException; - 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; @@ -58,12 +47,17 @@ 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; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.xacml.api.XACMLErrorConstants; public class ActionPolicy extends Policy { - /** - * ActionPolicy Fields - */ private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class); public static final String JSON_CONFIG = "JSON"; @@ -93,7 +87,7 @@ public class ActionPolicy extends Policy { private static boolean isAttribute = false; - private synchronized static boolean getAttribute() { + private static synchronized boolean getAttribute() { return isAttribute; } @@ -122,7 +116,7 @@ public class ActionPolicy extends Policy { } if (!isPreparedToSave()) { - //Prep and configure the policy for saving + // Prep and configure the policy for saving prepareToSave(); } @@ -133,13 +127,13 @@ public class ActionPolicy 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; } @@ -165,15 +159,15 @@ public class ActionPolicy extends Policy { String actionBody = policyAdapter.getActionBody(); setAttribute(false); - //if actionBody is null or empty then we know the ActionAttribute in the request does not exist in the + // if actionBody is null or empty then we know the ActionAttribute in the request does not exist in the // dictionary if (!(actionBody == null || "".equals(actionBody))) { saveActionBody(policyName, actionBody); setAttribute(true); } else { if (!getAttribute()) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue + - " in the ActionPolicyDict table."); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue + + " in the ActionPolicyDict table."); return false; } } @@ -237,8 +231,8 @@ public class ActionPolicy extends Policy { } // if rule algorithm not a compound if (!isCompound) { - condition.setExpression(new ObjectFactory().createApply(getInnerActionApply( - dynamicLabelRuleAlgorithms.get(index)))); + condition.setExpression(new ObjectFactory() + .createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index)))); } rule.setCondition(condition); } @@ -247,8 +241,8 @@ public class ActionPolicy extends Policy { actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(actionPolicy); } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + Objects - .requireNonNull(policyAdapter.getData()).getClass().getCanonicalName()); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + + Objects.requireNonNull(policyAdapter.getData()).getClass().getCanonicalName()); } setPreparedToSave(true); @@ -502,11 +496,11 @@ public class ActionPolicy extends Policy { public String getFunctionDefinitionId(String key) { FunctionDefinition object = - (FunctionDefinition) commonClassDao.getDataById(FunctionDefinition.class, "short_name", key); + (FunctionDefinition) commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", key); if (object != null) { return object.getXacmlid(); } return null; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java index 6a3a9dc8d..6ebc74a91 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -65,8 +66,10 @@ import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; 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.Category; +import org.onap.policy.rest.jpa.FunctionDefinition; import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PolicyUtils; @@ -307,10 +310,10 @@ public class XACMLPAPTest { matchingAttributes.put("guardActiveEnd", "10:00"); StdPAPPolicy newPAPPolicy = - new StdPAPPolicy( - StdPAPPolicyParams.builder().policyName("testGuardMinMax").description("test rule").onapName("PDPD") - .providerComboBox("GUARD_MIN_MAX").dynamicFieldConfigAttributes(matchingAttributes) - .editPolicy(false).domain("test").highestVersion(0).build()); + new StdPAPPolicy(StdPAPPolicyParams.builder().policyName("testGuardMinMax").description("test rule") + .onapName("PDPD").providerComboBox("GUARD_MIN_MAX") + .dynamicFieldConfigAttributes(matchingAttributes).editPolicy(false).domain("test") + .highestVersion(0).build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); @@ -370,6 +373,63 @@ public class XACMLPAPTest { Mockito.verify(httpServletResponse).addHeader("operation", "create"); } + @Test + public void testActionPolicy() throws IOException, ServletException, SQLException { + setPolicyCreation(); + httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn("DEVL"); + Mockito.when(httpServletRequest.getMethod()).thenReturn("PUT"); + Mockito.when(httpServletRequest.getParameter("apiflag")).thenReturn("API"); + Mockito.when(httpServletRequest.getParameter("operation")).thenReturn("create"); + Mockito.when(httpServletRequest.getParameter("policyType")).thenReturn("Action"); + + CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class); + PolicyCreation.setCommonClassDao(commonClassDao); + ActionPolicyDict actionDict = new ActionPolicyDict(); + actionDict.setBody("{\"test\":\"test\"}"); + actionDict.setHeader("test122=test12:test22=test34"); + actionDict.setType("REST"); + actionDict.setMethod("GET"); + actionDict.setUrl("testsomeurl.com"); + Mockito.when(commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", "test")) + .thenReturn(actionDict); + FunctionDefinition funcDefn = new FunctionDefinition(); + funcDefn.setXacmlid("urn:oasis:names:tc:xacml:1.0:function:and"); + Mockito.when(commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", "and")).thenReturn(funcDefn); + funcDefn.setXacmlid("urn:oasis:names:tc:xacml:1.0:function:integer-equal"); + Mockito.when(commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", "integer-equal")) + .thenReturn(funcDefn); + funcDefn.setXacmlid("urn:oasis:names:tc:xacml:3.0:function:string-contains"); + Mockito.when(commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", "string-contains")) + .thenReturn(funcDefn); + funcDefn.setXacmlid("urn:oasis:names:tc:xacml:1.0:function:integer-greater-than"); + Mockito.when(commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", "integer-greater-than")) + .thenReturn(funcDefn); + funcDefn.setXacmlid("urn:oasis:names:tc:xacml:1.0:function:or"); + Mockito.when(commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", "or")).thenReturn(funcDefn); + + Map<String, String> componentAttributes = new HashMap<>(); + componentAttributes.put("java", "test"); + StdPAPPolicy newPapPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().policyName("test").description("test") + .dynamicFieldConfigAttributes(componentAttributes) + .dynamicRuleAlgorithmLabels(Arrays.asList("A1", "A2", "A3", "A4", "A5", "A6", "A7")) + .dynamicRuleAlgorithmCombo(Arrays.asList("integer-equal", "string-contains", "integer-equal", "and", + "integer-greater-than", "or", "and")) + .dynamicRuleAlgorithmField1(Arrays.asList("cobal", "cap", "cobal", "A2", "Config", "A4", "A1")) + .dynamicRuleAlgorithmField2(Arrays.asList("90", "ca", "90", "A3", "45", "A5", "A6")) + .actionPerformer("PDP").actionAttribute("test").editPolicy(false).domain("com").highestVersion(0) + .build()); + newPapPolicy.setActionBody("{\"test\":\"test\"}"); + + MockServletInputStream mockInput = + new MockServletInputStream(PolicyUtils.objectToJsonString(newPapPolicy).getBytes()); + Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); + + pap.service(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); + } + + private void setPolicyCreation() { CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class); PolicyCreation.setCommonClassDao(commonClassDao); @@ -396,7 +456,6 @@ public class XACMLPAPTest { template.setRule(rule); Mockito.when(commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", "testPolicy")) .thenReturn(template); - } @Test diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java new file mode 100644 index 000000000..bad043d0f --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java @@ -0,0 +1,373 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +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.apache.commons.io.IOUtils; +import org.hibernate.SessionFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.common.logging.ONAPLoggingContext; +import org.onap.policy.pap.xacml.rest.components.ConfigPolicy; +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.PolicyDBDaoTest; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.xacml.std.pap.StdEngine; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.springframework.mock.web.DelegatingServletInputStream; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletConfig; + +public class ConsoleAndApiServiceTest { + private static final String TESTGRP5 = "testgrp5"; + private static final String POLICY_ID = "policyId"; + private static final String TESTGRP1 = "testgrp1"; + private static final String TESTGROUP2 = "testgroup2"; + private static final String DEFAULT = "default"; + private static final String PDPS = "pdps"; + private static final String TESTGRP2 = "testgrp2"; + private static final String POLICY_NAME = "com.Config_SampleTest1206.1.xml"; + private static final String PUT = "PUT"; + private static final String POST = "POST"; + private static final String DEVL = "DEVL"; + private static final String TESTGRP4 = "testgrp4"; + private static final String API2 = "api"; + private static final String API = "API"; + private static final String GROUP_DESCRIPTION = "groupDescription"; + private static final String GROUP_NAME = "groupName"; + private static final String PDP_ID = "pdpId"; + private static final String USER_ID = "userId"; + private static final String APIFLAG = "apiflag"; + private static final String ENVIRONMENT_HEADER = "Environment"; + private static PolicyDBDao dbd; + private static Path repository; + private static StdEngine stdEngine = null; + private static SessionFactory sessionFactory = null; + private static List<String> headers = new ArrayList<>(); + private static ConsoleAndApiService consoleAndApi; + private static MockServletConfig servletConfig; + private static XACMLPapServlet pap; + private HttpServletRequest httpServletRequest; + private HttpServletResponse httpServletResponse; + private static final ONAPLoggingContext logContext = Mockito.mock(ONAPLoggingContext.class); + + /** + * Sets the up before class. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); + try { + sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("testConsoleApi"); + } catch (Exception e) { + Assert.fail(); + } + + PolicyDBDao.setJunit(true); + dbd = PolicyDBDao.getPolicyDBDaoInstance(); + PolicyDBDao.setJunit(true); + + consoleAndApi = new ConsoleAndApiService(); + + servletConfig = Mockito.mock(MockServletConfig.class); + System.setProperty("com.sun.management.jmxremote.port", "9993"); + Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) + .thenReturn("src/test/resources/xacml.pap.properties"); + pap = new XACMLPapServlet(); + pap.init(servletConfig); + } + + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @Before + public void setUp() throws Exception { + httpServletRequest = Mockito.mock(HttpServletRequest.class); + httpServletResponse = new MockHttpServletResponse(); + Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); + Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); + CommonClassDaoImpl.setSessionfactory(sessionFactory); + PolicyCreation.setCommonClassDao(new CommonClassDaoImpl()); + repository = Paths.get("src/test/resources/pdps"); + stdEngine = new StdEngine(repository); + dbd.setPapEngine(stdEngine); + } + + @Test + public void testGroupCreation() { + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(POST); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn("test"); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGRP1); + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP1, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGroupNotExistInDb() { + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(POST); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn("testgrpNotExist"); + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, "testgrpNotExist", logContext, stdEngine); + assertTrue(HttpServletResponse.SC_INTERNAL_SERVER_ERROR == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGroupChange() { + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(POST); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn("test"); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGRP2); + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP2, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + + Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn(null); + Mockito.when(httpServletRequest.getParameter(DEFAULT)).thenReturn(DEFAULT); + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP2, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPushPolicy() throws Exception { + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(POST); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn(null); + Mockito.when(httpServletRequest.getParameter(POLICY_ID)).thenReturn(POLICY_NAME); + repository = Paths.get(PDPS); + stdEngine = new StdEngine(repository); + dbd.setPapEngine(stdEngine); + populatePolicyInDb(); + + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, DEFAULT, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testCreatePolicy() throws Exception { + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(PUT); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter("policy")).thenReturn(POLICY_NAME); + repository = Paths.get(PDPS); + stdEngine = new StdEngine(repository); + dbd.setPapEngine(stdEngine); + + try { + consoleAndApi.doAcPut(httpServletRequest, httpServletResponse, DEFAULT, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testCreateAndMovePdp() throws Exception { + // create two groups, create a pdp on one group and then move it to another group + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(POST); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn("test"); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGRP4); + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGRP5); + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + + Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn(null); + Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/"); + Mockito.when(httpServletRequest.getMethod()).thenReturn(PUT); + httpServletResponse = new MockHttpServletResponse(); + StdPDP newPdp = new StdPDP("http://localhost:4344/pdp/", "newpdp", "new desc", 9999); + ObjectWriter ow = new ObjectMapper().writer(); + when(httpServletRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(ow.writeValueAsString(newPdp).getBytes(StandardCharsets.UTF_8)))); + try { + consoleAndApi.doAcPut(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + + httpServletRequest = Mockito.mock(HttpServletRequest.class); + httpServletResponse = new MockHttpServletResponse(); + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn(POST); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/"); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGRP4); + try { + consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + + httpServletRequest = Mockito.mock(HttpServletRequest.class); + httpServletResponse = new MockHttpServletResponse(); + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn("DELETE"); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/"); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGRP4); + try { + consoleAndApi.doAcDelete(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + + } + + @Test + public void testGet() throws Exception { + Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); + Mockito.when(httpServletRequest.getMethod()).thenReturn("GET"); + Mockito.when(httpServletRequest.getParameter(APIFLAG)).thenReturn(API2); + Mockito.when(httpServletRequest.getParameter(USER_ID)).thenReturn(API); + Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/"); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(""); + try { + consoleAndApi.doAcGet(httpServletRequest, httpServletResponse, "", logContext, stdEngine); + assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus()); + httpServletResponse = new MockHttpServletResponse(); + Mockito.when(httpServletRequest.getParameter(DEFAULT)).thenReturn(DEFAULT); + consoleAndApi.doAcGet(httpServletRequest, httpServletResponse, "", logContext, stdEngine); + assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus()); + Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn(null); + Mockito.when(httpServletRequest.getParameter(DEFAULT)).thenReturn(null); + consoleAndApi.doAcGet(httpServletRequest, httpServletResponse, "", logContext, stdEngine); + assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus()); + Mockito.when(httpServletRequest.getParameter("getPDPGroup")).thenReturn(TESTGROUP2); + Mockito.when(httpServletRequest.getParameter(GROUP_NAME)).thenReturn(TESTGROUP2); + consoleAndApi.doAcGet(httpServletRequest, httpServletResponse, TESTGROUP2, logContext, stdEngine); + assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus()); + } catch (IOException e) { + fail(e.getMessage()); + } + + } + + private static void populatePolicyInDb() { + CommonClassDaoImpl.setSessionfactory(sessionFactory); + PolicyCreation.setCommonClassDao(new CommonClassDaoImpl()); + Policy policyObject = new ConfigPolicy(); + policyObject.policyAdapter = new PolicyRestAdapter(); + policyObject.policyAdapter.setConfigName("testpolicyhandle"); + policyObject.policyAdapter.setPolicyDescription("my description"); + policyObject.policyAdapter.setConfigBodyData("this is my test config file"); + policyObject.policyAdapter.setPolicyName("SampleTest1206"); + policyObject.policyAdapter.setConfigType(ConfigPolicy.OTHER_CONFIG); + policyObject.policyAdapter.setPolicyType("Config"); + policyObject.policyAdapter.setDomainDir("com"); + policyObject.policyAdapter.setVersion("1"); + policyObject.policyAdapter.setHighestVersion(1); + PolicyType policyTypeObject = new PolicyType(); + policyObject.policyAdapter.setPolicyData(policyTypeObject); + ClassLoader classLoader = ConsoleAndApiServiceTest.class.getClassLoader(); + PolicyType policyConfig = new PolicyType(); + policyConfig.setVersion("1"); + policyConfig.setPolicyId(""); + policyConfig.setTarget(new TargetType()); + policyObject.policyAdapter.setData(policyConfig); + try { + policyObject.policyAdapter + .setParentPath(IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"))); + } catch (Exception e2) { + fail(); + } + + PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); + try { + transaction.createPolicy(policyObject, API); + transaction.commitTransaction(); + } catch (Exception e) { + transaction.rollbackTransaction(); + Assert.fail(); + } + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java new file mode 100644 index 000000000..f979d1efa --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import static org.junit.Assert.fail; +import com.att.research.xacml.util.XACMLProperties; +import java.nio.file.Path; +import java.nio.file.Paths; +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.apache.commons.io.IOUtils; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.GroupEntity; +import org.onap.policy.rest.jpa.PdpEntity; +import org.onap.policy.xacml.std.pap.StdEngine; + +public class HandleIncomingNotificationsTest { + private static PolicyDBDao dbd; + private static Path repository; + private static StdEngine stdEngine = null; + private static SessionFactory sessionFactory = null; + private static HandleIncomingNotifications handleIncomingNotifications; + private static GroupEntity groupEntity; + + /** + * Sets the up before class. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); + try { + sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("testHandleIncoming"); + handleIncomingNotifications = new HandleIncomingNotifications(sessionFactory); + } catch (Exception e) { + Assert.fail(); + } + + PolicyDBDao.setJunit(true); + dbd = PolicyDBDao.getPolicyDBDaoInstance(); + PolicyDBDao.setJunit(true); + repository = Paths.get("src/test/resources/pdps"); + stdEngine = new StdEngine(repository); + dbd.setPapEngine(stdEngine); + populateDb(); + } + + + @Test + public void testHandleIncomingHttpNotification() { + handleIncomingNotifications.handleIncomingHttpNotification(null, "1", "group", null, null); + handleIncomingNotifications.handleIncomingHttpNotification(null, "1", "group", null, null); + handleIncomingNotifications.handleIncomingHttpNotification(null, "1", "policy", null, null); + handleIncomingNotifications.handleIncomingHttpNotification(null, "1", "pdp", null, null); + populatePdpEntityDb("2", groupEntity); + handleIncomingNotifications.handleIncomingHttpNotification(null, "2", "pdp", null, null); + } + + private static void populateDb() { + groupEntity = new GroupEntity(); + groupEntity.setCreatedBy("API"); + groupEntity.setDefaultGroup(false); + groupEntity.setDeleted(false); + groupEntity.setDescription("a test group"); + groupEntity.setGroupId("1"); + groupEntity.setGroupName("1"); + groupEntity.prePersist(); + Session session = sessionFactory.openSession(); + session.getTransaction().begin(); + session.persist(groupEntity); + session.getTransaction().commit(); + session.close(); + populatePdpEntityDb("1", groupEntity); + populatePolicyInDb(); + } + + private static void populatePdpEntityDb(String pdpId, GroupEntity groupEntity) { + PdpEntity pdpEntity = new PdpEntity(); + pdpEntity.setCreatedBy("API"); + pdpEntity.setDeleted(false); + pdpEntity.setDescription("test pdp"); + pdpEntity.setGroup(groupEntity); + pdpEntity.setJmxPort(9993); + pdpEntity.setModifiedBy("API"); + pdpEntity.setPdpId(pdpId); + pdpEntity.setPdpName("grouptest"); + pdpEntity.prePersist(); + + Session session = sessionFactory.openSession(); + session.getTransaction().begin(); + session.persist(pdpEntity); + session.getTransaction().commit(); + session.close(); + } + + private static void populatePolicyInDb() { + Policy policyObject = new ConfigPolicy(); + policyObject.policyAdapter = new PolicyRestAdapter(); + policyObject.policyAdapter.setConfigName("testpolicyhandle"); + policyObject.policyAdapter.setPolicyDescription("my description"); + policyObject.policyAdapter.setConfigBodyData("this is my test config file"); + policyObject.policyAdapter.setPolicyName("SampleTest1206"); + policyObject.policyAdapter.setConfigType(ConfigPolicy.OTHER_CONFIG); + policyObject.policyAdapter.setPolicyType("Config"); + policyObject.policyAdapter.setDomainDir("com"); + policyObject.policyAdapter.setVersion("1"); + policyObject.policyAdapter.setHighestVersion(1); + PolicyType policyTypeObject = new PolicyType(); + policyObject.policyAdapter.setPolicyData(policyTypeObject); + ClassLoader classLoader = HandleIncomingNotificationsTest.class.getClassLoader(); + PolicyType policyConfig = new PolicyType(); + policyConfig.setVersion("1"); + policyConfig.setPolicyId(""); + policyConfig.setTarget(new TargetType()); + policyObject.policyAdapter.setData(policyConfig); + try { + policyObject.policyAdapter + .setParentPath(IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"))); + } catch (Exception e2) { + fail(); + } + + PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); + try { + transaction.createPolicy(policyObject, "testuser1"); + transaction.commitTransaction(); + } catch (Exception e) { + transaction.rollbackTransaction(); + Assert.fail(); + } + } +} |