aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST/src
diff options
context:
space:
mode:
authorKrishnajinka <kris.jinka@samsung.com>2018-08-03 10:36:19 +0900
committerKrishnajinka <kris.jinka@samsung.com>2018-08-03 10:36:35 +0900
commit4068da123ee33b532b4b52f15545c76a978f977e (patch)
tree2f0e6393d1e204b6d0b32e58c4d9a1625c2d6ad4 /ONAP-PAP-REST/src
parentf0fec2a861ea0a92b27b40882ea38f9422cde0c6 (diff)
Modify ONAP PAP REST classes basic checkstyle
Modify tabs to space for checkstyle issue fix in ONAP PAP REST module. It helps future reviews and refactoring. Remaining classes Issue-ID: POLICY-1014 Change-Id: I677eadac9e8364b388be922024528c27fd1e2545 Signed-off-by: Krishnajinka <kris.jinka@samsung.com>
Diffstat (limited to 'ONAP-PAP-REST/src')
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java52
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java346
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java22
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java5516
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java802
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java550
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java148
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java760
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java1178
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java748
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java56
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java116
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java836
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java66
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java594
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java156
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java222
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java130
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java972
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java858
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java362
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java118
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java122
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java314
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java168
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java78
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java56
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java256
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java120
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java800
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java118
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java398
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java84
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java14
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java78
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java58
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java24
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java174
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java64
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java186
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java180
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java126
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java114
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java1054
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java220
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java388
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java786
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java434
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java236
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java342
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java184
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java1226
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java1342
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java198
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java664
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java138
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java308
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java62
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java208
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java32
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java310
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java84
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java20
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java128
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java78
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java608
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java28
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java16
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java22
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java44
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java160
71 files changed, 13730 insertions, 13730 deletions
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 38e2c96f5..ce9cad408 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
@@ -27,31 +27,31 @@ package org.onap.policy.pap.xacml.rest;
*
*/
public enum DictionaryNames {
-
- Attribute,
- ActionPolicyDictionary,
- OnapName,
- MSPolicyDictionary,
- OptimizationPolicyDictionary,
- VNFType,
- VSCLAction,
- ClosedLoopService,
- ClosedLoopSite,
- PEPOptions,
- VarbindDictionary,
- BRMSParamDictionary,
- BRMSControllerDictionary,
- BRMSDependencyDictionary,
- Settings,
- PrefixList,
- SecurityZone,
- Zone,
- ServiceList,
- ServiceGroup,
- AddressGroup,
- ProtocolList,
- ActionList,
- TermList,
- SearchCriteria
+
+ Attribute,
+ ActionPolicyDictionary,
+ OnapName,
+ MSPolicyDictionary,
+ OptimizationPolicyDictionary,
+ VNFType,
+ VSCLAction,
+ ClosedLoopService,
+ ClosedLoopSite,
+ PEPOptions,
+ VarbindDictionary,
+ BRMSParamDictionary,
+ BRMSControllerDictionary,
+ BRMSDependencyDictionary,
+ Settings,
+ PrefixList,
+ SecurityZone,
+ Zone,
+ ServiceList,
+ ServiceGroup,
+ AddressGroup,
+ ProtocolList,
+ ActionList,
+ TermList,
+ SearchCriteria
}
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 c1891b352..bd000381b 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
@@ -64,177 +64,177 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
public class UpdateOthersPAPS {
-
- private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class);
-
- 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";
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- UpdateOthersPAPS.commonClassDao = commonClassDao;
- }
-
- @Autowired
- private UpdateOthersPAPS(CommonClassDao commonClassDao){
- UpdateOthersPAPS.commonClassDao = commonClassDao;
- }
-
- public UpdateOthersPAPS() {
- //Empty Constructor
- }
-
- @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();
- body.setAction(request.getParameter("action"));
- 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 userName = papId.getUsername();
- String password = papId.getPassword();
- Base64.Encoder encoder = Base64.getEncoder();
- String txt;
- try{
- txt = new String(CryptoUtils.decryptTxt(password), StandardCharsets.UTF_8);
- } catch(Exception e){
- policyLogger.debug(e);
- //if we can't decrypt, might as well try it anyway
- txt = password;
- }
- String encoding = encoder.encodeToString((userName+":"+txt).getBytes(StandardCharsets.UTF_8));
- HttpHeaders headers = new HttpHeaders();
- headers.set("Authorization", "Basic " + encoding);
- headers.set("Content-Type", contentType);
-
- RestTemplate restTemplate = new RestTemplate();
- 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);
- exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
- if("409 Conflict".equals(e.getMessage())){
- policyLogger.error(e.getMessage());
- response.addHeader(error, e.getMessage());
- }
- }
- if(exception != null && exception.getStatusCode()!=null){
- String message;
- 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();
- policyLogger.error(message);
- }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();
- policyLogger.error(message);
- }
- model.put(papUrl, message);
- }else{
- model.put(papUrl, "Success");
- }
- }
- }
- JsonMessage msg;
- try {
- msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- policyLogger.error("Exception Occured"+e);
- }
- }
- }
-
- @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST)
- @ResponseBody
- 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)){
- File file;
- if(oldPolicyName.contains(configType)){
- file = new File(Policy.getConfigHome() + File.separator + oldPolicyName);
- }else{
- file = new File(Policy.getActionHome() + File.separator + oldPolicyName);
- }
- if(file.exists()){
- File renamefile;
- if(oldPolicyName.contains(configType)){
- renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName);
- }else{
- renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName);
- }
- if(file.renameTo(renamefile)){
- policyLogger.info("Policy has been renamed Successfully"+newPolicyName);
- response.addHeader("rename", "Success");
- }else{
- response.addHeader("rename", "Failure");
- }
- }
- }
- }else if("delete".equals(action)){
- if(oldPolicyName.contains(configType)){
- Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName));
- }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);
- saveConfigurationData(configEntiy, 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);
- }
- }
-
- 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);
- }
- }
-
- 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);
- }
- }
+
+ private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class);
+
+ 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";
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ UpdateOthersPAPS.commonClassDao = commonClassDao;
+ }
+
+ @Autowired
+ private UpdateOthersPAPS(CommonClassDao commonClassDao){
+ UpdateOthersPAPS.commonClassDao = commonClassDao;
+ }
+
+ public UpdateOthersPAPS() {
+ //Empty Constructor
+ }
+
+ @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();
+ body.setAction(request.getParameter("action"));
+ 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 userName = papId.getUsername();
+ String password = papId.getPassword();
+ Base64.Encoder encoder = Base64.getEncoder();
+ String txt;
+ try{
+ txt = new String(CryptoUtils.decryptTxt(password), StandardCharsets.UTF_8);
+ } catch(Exception e){
+ policyLogger.debug(e);
+ //if we can't decrypt, might as well try it anyway
+ txt = password;
+ }
+ String encoding = encoder.encodeToString((userName+":"+txt).getBytes(StandardCharsets.UTF_8));
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Authorization", "Basic " + encoding);
+ headers.set("Content-Type", contentType);
+
+ RestTemplate restTemplate = new RestTemplate();
+ 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);
+ exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
+ if("409 Conflict".equals(e.getMessage())){
+ policyLogger.error(e.getMessage());
+ response.addHeader(error, e.getMessage());
+ }
+ }
+ if(exception != null && exception.getStatusCode()!=null){
+ String message;
+ 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();
+ policyLogger.error(message);
+ }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();
+ policyLogger.error(message);
+ }
+ model.put(papUrl, message);
+ }else{
+ model.put(papUrl, "Success");
+ }
+ }
+ }
+ JsonMessage msg;
+ try {
+ msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+ }
+
+ @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST)
+ @ResponseBody
+ 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)){
+ File file;
+ if(oldPolicyName.contains(configType)){
+ file = new File(Policy.getConfigHome() + File.separator + oldPolicyName);
+ }else{
+ file = new File(Policy.getActionHome() + File.separator + oldPolicyName);
+ }
+ if(file.exists()){
+ File renamefile;
+ if(oldPolicyName.contains(configType)){
+ renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName);
+ }else{
+ renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName);
+ }
+ if(file.renameTo(renamefile)){
+ policyLogger.info("Policy has been renamed Successfully"+newPolicyName);
+ response.addHeader("rename", "Success");
+ }else{
+ response.addHeader("rename", "Failure");
+ }
+ }
+ }
+ }else if("delete".equals(action)){
+ if(oldPolicyName.contains(configType)){
+ Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName));
+ }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);
+ saveConfigurationData(configEntiy, 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);
+ }
+ }
+
+ 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);
+ }
+ }
+
+ 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);
+ }
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java
index 89ab8bc8a..88ad91b5f 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java
@@ -28,16 +28,16 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
import org.springframework.web.servlet.DispatcherServlet;
public class WebConfig implements WebApplicationInitializer {
-
- @Override
- public void onStartup(ServletContext container) {
- AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
- ctx.register(PAPRestConfig.class);
- ctx.setServletContext(container);
- ctx.refresh();
- ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(ctx));
- dispatcher.setLoadOnStartup(1);
- dispatcher.addMapping("/onap/*");
- }
+
+ @Override
+ public void onStartup(ServletContext container) {
+ AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
+ ctx.register(PAPRestConfig.class);
+ ctx.setServletContext(container);
+ ctx.refresh();
+ ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(ctx));
+ dispatcher.setLoadOnStartup(1);
+ dispatcher.addMapping("/onap/*");
+ }
}
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 1acec1bd9..4406ad3da 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
@@ -107,191 +107,191 @@ 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.")
- })
+ 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);
- // audit (transaction) LOGGER
- private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
- //Persistence Unit for JPA
- private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
- private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
- // Client Headers.
- private static final String ENVIRONMENT_HEADER = "Environment";
- private static final String ADD_GROUP_ERROR = "addGroupError";
- private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
-
- private static final String REGEX = "[0-9a-zA-Z._ ]*";
-
- /*
- * List of Admin Console URLs.
- * Used to send notifications when configuration changes.
- *
- * 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 String configHome;
- private static String actionHome;
- /*
- * This PAP instance's own URL.
- * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
- */
- private static String papURL = null;
- // The heartbeat thread.
- private static Heartbeat heartbeat = null;
- private static Thread heartbeatThread = null;
- //The entity manager factory for JPA access
- private static EntityManagerFactory emf;
- private static PolicyDBDao policyDBDao;
- /*
- * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
- */
- private static PAPPolicyEngine papEngine = null;
- /*
- * These are the parameters needed for DB access from the PAP
- */
- private static int papIntegrityAuditPeriodSeconds = -1;
- private static String papDbDriver = null;
- private static String papDbUrl = null;
- private static String papDbUser = null;
- private static String papDbPassword = null;
- private static String papResourceName = null;
- private static String[] papDependencyGroupsFlatArray = null;
- private static String environment = null;
- private static String pdpFile = null;
-
- private transient IntegrityMonitor im;
- private transient IntegrityAudit ia;
-
- //MicroService Model Properties
- private static String msOnapName;
- private static String msPolicyName;
- /*
- * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
- * this servlet starts. Its configurable by the admin.
- */
- private static transient Thread initiateThread = null;
- private transient ONAPLoggingContext baseLoggingContext = null;
-
- /**
- * @see HttpServlet#HttpServlet()
- */
- public XACMLPapServlet() {
- super();
- }
-
- /**
- * @see Servlet#init(ServletConfig)
- */
- public void init(ServletConfig config) throws ServletException {
- try {
- // Logging
- baseLoggingContext = new ONAPLoggingContext();
- // fixed data that will be the same in all logging output goes here
- try {
- String hostname = InetAddress.getLocalHost().getCanonicalHostName();
- baseLoggingContext.setServer(hostname);
- } catch (UnknownHostException e) {
- LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
- }
- // Initialize
- XACMLRest.xacmlInit(config);
- // Load the properties
- XACMLRest.loadXacmlProperties(null, null);
- /*
- * Retrieve the property values
- */
- setCommonProperties();
- String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
- if(papSiteName == null){
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
- throw new PAPException("papSiteName is null");
- }
- String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
- if(papNodeType == null){
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " 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));
- //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);
- 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**************************************");
- // Pull custom persistence settings
- Properties properties;
- try {
- properties = XACMLProperties.getProperties();
- 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()");
- throw new ServletException(e.getMessage(), e.getCause());
- }
- // Create an IntegrityMonitor
- if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
- properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
- }
- im = IntegrityMonitor.getInstance(papResourceName,properties);
- // Create an IntegrityAudit
- ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
- ia.startAuditThread();
- // Create the entity manager factory
- setEMF(properties);
- // 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));
- //Create the policyDBDao
- setPolicyDBDao();
- // Load our PAP engine, first create a factory
- ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
- // The factory knows how to go about creating a PAP Engine
- setPAPEngine((PAPPolicyEngine) factory.newEngine());
- PolicyDBDaoTransaction addNewGroup = null;
+ private static final long serialVersionUID = 1L;
+ private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
+ // audit (transaction) LOGGER
+ private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
+ //Persistence Unit for JPA
+ private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
+ private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
+ // Client Headers.
+ private static final String ENVIRONMENT_HEADER = "Environment";
+ private static final String ADD_GROUP_ERROR = "addGroupError";
+ private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
+
+ private static final String REGEX = "[0-9a-zA-Z._ ]*";
+
+ /*
+ * List of Admin Console URLs.
+ * Used to send notifications when configuration changes.
+ *
+ * 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 String configHome;
+ private static String actionHome;
+ /*
+ * This PAP instance's own URL.
+ * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
+ */
+ private static String papURL = null;
+ // The heartbeat thread.
+ private static Heartbeat heartbeat = null;
+ private static Thread heartbeatThread = null;
+ //The entity manager factory for JPA access
+ private static EntityManagerFactory emf;
+ private static PolicyDBDao policyDBDao;
+ /*
+ * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
+ */
+ private static PAPPolicyEngine papEngine = null;
+ /*
+ * These are the parameters needed for DB access from the PAP
+ */
+ private static int papIntegrityAuditPeriodSeconds = -1;
+ private static String papDbDriver = null;
+ private static String papDbUrl = null;
+ private static String papDbUser = null;
+ private static String papDbPassword = null;
+ private static String papResourceName = null;
+ private static String[] papDependencyGroupsFlatArray = null;
+ private static String environment = null;
+ private static String pdpFile = null;
+
+ private transient IntegrityMonitor im;
+ private transient IntegrityAudit ia;
+
+ //MicroService Model Properties
+ private static String msOnapName;
+ private static String msPolicyName;
+ /*
+ * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
+ * this servlet starts. Its configurable by the admin.
+ */
+ private static transient Thread initiateThread = null;
+ private transient ONAPLoggingContext baseLoggingContext = null;
+
+ /**
+ * @see HttpServlet#HttpServlet()
+ */
+ public XACMLPapServlet() {
+ super();
+ }
+
+ /**
+ * @see Servlet#init(ServletConfig)
+ */
+ public void init(ServletConfig config) throws ServletException {
+ try {
+ // Logging
+ baseLoggingContext = new ONAPLoggingContext();
+ // fixed data that will be the same in all logging output goes here
+ try {
+ String hostname = InetAddress.getLocalHost().getCanonicalHostName();
+ baseLoggingContext.setServer(hostname);
+ } catch (UnknownHostException e) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
+ }
+ // Initialize
+ XACMLRest.xacmlInit(config);
+ // Load the properties
+ XACMLRest.loadXacmlProperties(null, null);
+ /*
+ * Retrieve the property values
+ */
+ setCommonProperties();
+ String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
+ if(papSiteName == null){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
+ throw new PAPException("papSiteName is null");
+ }
+ String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
+ if(papNodeType == null){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " 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));
+ //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);
+ 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**************************************");
+ // Pull custom persistence settings
+ Properties properties;
+ try {
+ properties = XACMLProperties.getProperties();
+ 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()");
+ throw new ServletException(e.getMessage(), e.getCause());
+ }
+ // Create an IntegrityMonitor
+ if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
+ properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
+ }
+ im = IntegrityMonitor.getInstance(papResourceName,properties);
+ // Create an IntegrityAudit
+ ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
+ ia.startAuditThread();
+ // Create the entity manager factory
+ setEMF(properties);
+ // 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));
+ //Create the policyDBDao
+ setPolicyDBDao();
+ // Load our PAP engine, first create a factory
+ ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
+ // The factory knows how to go about creating a PAP Engine
+ setPAPEngine((PAPPolicyEngine) factory.newEngine());
+ PolicyDBDaoTransaction addNewGroup = null;
if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
try {
addNewGroup = policyDBDao.getNewTransaction();
@@ -310,52 +310,52 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
}
}
- policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
- 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();
-
- LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
+ policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
+ 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();
+
+ LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
- //get the current filesystem group and update from the database if needed
+ //get the current filesystem group and update from the database if needed
StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
if(updatedGroup!=null) {
- papEngine.updateGroup(updatedGroup);
+ papEngine.updateGroup(updatedGroup);
}
LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
- //release the transaction lock
- auditTrans.close();
- }
-
- // Sanity check for URL.
- if (XACMLPapServlet.papURL == null) {
- throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
- }
- // 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))) {
- startInitiateThreadService(new Thread(this));
- }
- // After startup, the PAP does Heartbeat's to each of the PDPs periodically
- startHeartBeatService(new Heartbeat((PAPPolicyEngine) 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);
- } 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);
- }
- }
-
- private static void startInitiateThreadService(Thread thread) {
- initiateThread = thread;
+ //release the transaction lock
+ auditTrans.close();
+ }
+
+ // Sanity check for URL.
+ if (XACMLPapServlet.papURL == null) {
+ throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
+ }
+ // 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))) {
+ startInitiateThreadService(new Thread(this));
+ }
+ // After startup, the PAP does Heartbeat's to each of the PDPs periodically
+ startHeartBeatService(new Heartbeat((PAPPolicyEngine) 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);
+ } 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);
+ }
+ }
+
+ private static void startInitiateThreadService(Thread thread) {
+ initiateThread = thread;
initiateThread.start();
}
@@ -368,13 +368,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
private static void startHeartBeatService(Heartbeat heartbeat) {
- XACMLPapServlet.heartbeat = heartbeat;
+ XACMLPapServlet.heartbeat = heartbeat;
XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
XACMLPapServlet.heartbeatThread.start();
}
private static void setPolicyDBDao() throws ServletException {
- try {
+ try {
policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
} catch (Exception e) {
throw new ServletException("Unable to Create Policy DBDao Instance",e);
@@ -382,7 +382,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
private static void setEMF(Properties properties) throws ServletException {
- emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
+ emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
if (emf == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
+ PERSISTENCE_UNIT);
@@ -391,15 +391,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
private static void setPAPURL(String papURL) {
- XACMLPapServlet.papURL = papURL;
+ XACMLPapServlet.papURL = papURL;
}
private static void setPAPEngine(PAPPolicyEngine newEngine) {
- XACMLPapServlet.papEngine = newEngine;
+ XACMLPapServlet.papEngine = newEngine;
}
private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
- try{
+ try{
//Now we have flattened the array into a simple comma-separated list
papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
//clean up the entries
@@ -423,7 +423,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
private static void setCommonProperties() throws PAPException {
- setConfigHome();
+ setConfigHome();
setActionHome();
papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
if(papDbDriver == null){
@@ -470,1686 +470,1686 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
/**
- * Thread used only during PAP startup to initiate change messages to all known PDPs.
- * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
- */
- @Override
- public void run() {
- // send the current configuration to all the PDPs that we know about
- changed();
- }
-
- /**
- * @see Servlet#destroy()
- *
- * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
- * For now we assume that we do care.
- */
- @Override
- public void destroy() {
- // Make sure our threads are destroyed
- if (XACMLPapServlet.heartbeatThread != null) {
- // stop the heartbeat
- try {
- if (XACMLPapServlet.heartbeat != null) {
- XACMLPapServlet.heartbeat.terminate();
- }
- XACMLPapServlet.heartbeatThread.interrupt();
- XACMLPapServlet.heartbeatThread.join();
- } catch (InterruptedException e) {
- XACMLPapServlet.heartbeatThread.interrupt();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
- }
- }
- if (initiateThread != null) {
- try {
- initiateThread.interrupt();
- initiateThread.join();
- } catch (InterruptedException e) {
- initiateThread.interrupt();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
- }
- }
- }
-
- /**
- * Called by:
- * - PDP nodes to register themselves with the PAP, and
- * - Admin Console to make changes in the PDP Groups.
- *
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
- loggingContext.transactionStarted();
- loggingContext.setServiceName("PAP.post");
- if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
- UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
- PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
- } else {
- PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
- }
- PolicyDBDaoTransaction pdpTransaction = null;
- loggingContext.metricStarted();
- try {
- 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;
- LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }catch (StandbyStatusException se) {
- String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
- + " of " + im.getStateManager().getStandbyStatus()
- + "\n Exception Message: " + se.getMessage();
- LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- } catch (IntegrityMonitorException e) {
- String message = "POST interface called for PAP " + papResourceName + " but an exception occurred"
- + "\n Exception Message: " + e.getMessage();
- LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }
- try {
- loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
- // since getParameter reads the content string, explicitly get the content before doing that.
- // Simply getting the inputStream seems to protect it against being consumed by getParameter.
- request.getInputStream();
- String groupId = request.getParameter("groupId");
- String apiflag = request.getParameter("apiflag");
- if(groupId != null) {
- // Is this from the Admin Console or API?
- if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
- // this is from the API so we need to check the client credentials before processing the request
- if(!authorizeRequest(request)){
- String message = "PEP not Authorized for making this Request!!";
- PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
- im.endTransaction();
- return;
- }
- }
- loggingContext.metricStarted();
- doACPost(request, response, groupId, loggingContext);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- // Request is from a PDP asking for its config.
- loggingContext.setServiceName("PDP:PAP.register");
- // Get the PDP's ID
- String id = this.getPDPID(request);
- String jmxport = this.getPDPJMX(request);
- LOGGER.info("Request(doPost) from PDP coming up: " + id);
- // Get the PDP Object
- OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
- // Is it known?
- if (pdp == null) {
- LOGGER.info("Unknown PDP: " + id);
- // Check PDP ID
- 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.rollbackTransaction();
- String message = "Failed to create new PDP for id: " + id;
- 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());
- im.endTransaction();
- return;
- }
- // get the PDP we just created
- try{
- pdp = XACMLPapServlet.papEngine.getPDP(id);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- if (pdp == null) {
- if(pdpTransaction != null){
- pdpTransaction.rollbackTransaction();
- }
- String message = "Failed to create new PDP for id: " + id;
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- im.endTransaction();
- return;
- }
- } else {
- String message = "PDP is Unauthorized to Connect to PAP: "+ id;
- 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.");
- PolicyLogger.audit("Transaction Failed - See Error.log");
- im.endTransaction();
- return;
- }
- try{
- loggingContext.metricStarted();
- pdpTransaction.commitTransaction();
- loggingContext.metricEnded();
- 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");
- }
- }
- if (jmxport != null && jmxport != ""){
- try{
- ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
- }catch(NumberFormatException e){
- LOGGER.error(e);
- }
- }
- // Get the PDP's Group
- OnapPDPGroup group =null;
- try{
- group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- if (group == null) {
- 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");
- im.endTransaction();
- return;
- }
- // Determine what group the PDP node is in and get
- // its policy/pip properties.
- Properties policies = group.getPolicyProperties();
- Properties pipconfig = group.getPipConfigProperties();
- // Get the current policy/pip configuration that the PDP has
- Properties pdpProperties = new Properties();
- try{
- pdpProperties.load(request.getInputStream());
- }catch(IOException e){
- LOGGER.error(e);
- }
- LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
- LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
- LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
- // Validate the node's properties
- boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
- // Send back current configuration
- if (isCurrent == false) {
- // Tell the PDP we are sending back the current policies/pip config
- LOGGER.info("PDP configuration NOT current.");
- if (policies != null) {
- // Put URL's into the properties in case the PDP needs to
- // retrieve them.
- this.populatePolicyURL(request.getRequestURL(), policies);
- // Copy the properties to the output stream
- try{
- policies.store(response.getOutputStream(), "");
- }catch(IOException e){
- LOGGER.error(e);
- }
- }
- if (pipconfig != null) {
- // Copy the properties to the output stream
- try{
- pipconfig.store(response.getOutputStream(), "");
- }catch(IOException e){
- LOGGER.error(e);
- }
- }
- // We are good - and we are sending them information
- response.setStatus(HttpServletResponse.SC_OK);
- try{
- setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- } else {
- // Tell them they are good
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- try{
- setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- }
- // tell the AC that something changed
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- } catch (PAPException | IOException | NumberFormatException e) {
- if(pdpTransaction != null){
- pdpTransaction.rollbackTransaction();
- }
- 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());
- im.endTransaction();
- return;
- }
- //Catch anything that fell through
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended");
- im.endTransaction();
- }
-
- private void setResponseError(HttpServletResponse response,int responseCode, String message) {
- try {
- if(message != null && !message.isEmpty()){
- response.sendError(responseCode, message);
- }
+ * Thread used only during PAP startup to initiate change messages to all known PDPs.
+ * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
+ */
+ @Override
+ public void run() {
+ // send the current configuration to all the PDPs that we know about
+ changed();
+ }
+
+ /**
+ * @see Servlet#destroy()
+ *
+ * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
+ * For now we assume that we do care.
+ */
+ @Override
+ public void destroy() {
+ // Make sure our threads are destroyed
+ if (XACMLPapServlet.heartbeatThread != null) {
+ // stop the heartbeat
+ try {
+ if (XACMLPapServlet.heartbeat != null) {
+ XACMLPapServlet.heartbeat.terminate();
+ }
+ XACMLPapServlet.heartbeatThread.interrupt();
+ XACMLPapServlet.heartbeatThread.join();
+ } catch (InterruptedException e) {
+ XACMLPapServlet.heartbeatThread.interrupt();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
+ }
+ }
+ if (initiateThread != null) {
+ try {
+ initiateThread.interrupt();
+ initiateThread.join();
+ } catch (InterruptedException e) {
+ initiateThread.interrupt();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
+ }
+ }
+ }
+
+ /**
+ * Called by:
+ * - PDP nodes to register themselves with the PAP, and
+ * - Admin Console to make changes in the PDP Groups.
+ *
+ * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
+ */
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ loggingContext.transactionStarted();
+ loggingContext.setServiceName("PAP.post");
+ if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
+ UUID requestID = UUID.randomUUID();
+ loggingContext.setRequestID(requestID.toString());
+ PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
+ } else {
+ PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
+ }
+ PolicyDBDaoTransaction pdpTransaction = null;
+ loggingContext.metricStarted();
+ try {
+ 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;
+ LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }catch (StandbyStatusException se) {
+ String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
+ + " of " + im.getStateManager().getStandbyStatus()
+ + "\n Exception Message: " + se.getMessage();
+ LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ } catch (IntegrityMonitorException e) {
+ String message = "POST interface called for PAP " + papResourceName + " but an exception occurred"
+ + "\n Exception Message: " + e.getMessage();
+ LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }
+ try {
+ loggingContext.metricStarted();
+ XACMLRest.dumpRequest(request);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
+ // since getParameter reads the content string, explicitly get the content before doing that.
+ // Simply getting the inputStream seems to protect it against being consumed by getParameter.
+ request.getInputStream();
+ String groupId = request.getParameter("groupId");
+ String apiflag = request.getParameter("apiflag");
+ if(groupId != null) {
+ // Is this from the Admin Console or API?
+ if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
+ // this is from the API so we need to check the client credentials before processing the request
+ if(!authorizeRequest(request)){
+ String message = "PEP not Authorized for making this Request!!";
+ PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
+ im.endTransaction();
+ return;
+ }
+ }
+ loggingContext.metricStarted();
+ doACPost(request, response, groupId, loggingContext);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ // Request is from a PDP asking for its config.
+ loggingContext.setServiceName("PDP:PAP.register");
+ // Get the PDP's ID
+ String id = this.getPDPID(request);
+ String jmxport = this.getPDPJMX(request);
+ LOGGER.info("Request(doPost) from PDP coming up: " + id);
+ // Get the PDP Object
+ OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
+ // Is it known?
+ if (pdp == null) {
+ LOGGER.info("Unknown PDP: " + id);
+ // Check PDP ID
+ 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.rollbackTransaction();
+ String message = "Failed to create new PDP for id: " + id;
+ 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());
+ im.endTransaction();
+ return;
+ }
+ // get the PDP we just created
+ try{
+ pdp = XACMLPapServlet.papEngine.getPDP(id);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ if (pdp == null) {
+ if(pdpTransaction != null){
+ pdpTransaction.rollbackTransaction();
+ }
+ String message = "Failed to create new PDP for id: " + id;
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ im.endTransaction();
+ return;
+ }
+ } else {
+ String message = "PDP is Unauthorized to Connect to PAP: "+ id;
+ 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.");
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ im.endTransaction();
+ return;
+ }
+ try{
+ loggingContext.metricStarted();
+ pdpTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ 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");
+ }
+ }
+ if (jmxport != null && jmxport != ""){
+ try{
+ ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
+ }catch(NumberFormatException e){
+ LOGGER.error(e);
+ }
+ }
+ // Get the PDP's Group
+ OnapPDPGroup group =null;
+ try{
+ group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ if (group == null) {
+ 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");
+ im.endTransaction();
+ return;
+ }
+ // Determine what group the PDP node is in and get
+ // its policy/pip properties.
+ Properties policies = group.getPolicyProperties();
+ Properties pipconfig = group.getPipConfigProperties();
+ // Get the current policy/pip configuration that the PDP has
+ Properties pdpProperties = new Properties();
+ try{
+ pdpProperties.load(request.getInputStream());
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
+ LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
+ LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
+ // Validate the node's properties
+ boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
+ // Send back current configuration
+ if (isCurrent == false) {
+ // Tell the PDP we are sending back the current policies/pip config
+ LOGGER.info("PDP configuration NOT current.");
+ if (policies != null) {
+ // Put URL's into the properties in case the PDP needs to
+ // retrieve them.
+ this.populatePolicyURL(request.getRequestURL(), policies);
+ // Copy the properties to the output stream
+ try{
+ policies.store(response.getOutputStream(), "");
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ }
+ if (pipconfig != null) {
+ // Copy the properties to the output stream
+ try{
+ pipconfig.store(response.getOutputStream(), "");
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ }
+ // We are good - and we are sending them information
+ response.setStatus(HttpServletResponse.SC_OK);
+ try{
+ setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ } else {
+ // Tell them they are good
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ try{
+ setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ }
+ // tell the AC that something changed
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ } catch (PAPException | IOException | NumberFormatException e) {
+ if(pdpTransaction != null){
+ pdpTransaction.rollbackTransaction();
+ }
+ 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());
+ im.endTransaction();
+ return;
+ }
+ //Catch anything that fell through
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended");
+ im.endTransaction();
+ }
+
+ private void setResponseError(HttpServletResponse response,int responseCode, String message) {
+ try {
+ if(message != null && !message.isEmpty()){
+ response.sendError(responseCode, message);
+ }
} catch (IOException e) {
LOGGER.error("Error setting Error response Header ", e);
}
- return;
+ return;
}
/**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
- loggingContext.transactionStarted();
- loggingContext.setServiceName("PAP.get");
- if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
- UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
- PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
- } else {
- PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
- }
- loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
- String pathInfo = request.getRequestURI();
- LOGGER.info("path info: " + pathInfo);
- if (pathInfo != null){
- //DO NOT do a im.startTransaction for the test request
- if (pathInfo.equals("/pap/test")) {
- try {
- testService(loggingContext, response);
- } catch (IOException e) {
- LOGGER.debug(e);
- }
- return;
- }
- }
- //This im.startTransaction() covers all other Get transactions
- try {
- loggingContext.metricStarted();
- im.startTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
- } catch (AdministrativeStateException ae){
- String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
- + " state of " + im.getStateManager().getAdminState()
- + "\n Exception Message: " + ae.getMessage();
- LOGGER.info(message, ae);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }catch (StandbyStatusException se) {
- String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
- + " of " + im.getStateManager().getStandbyStatus()
- + "\n Exception Message: " + se.getMessage();
- LOGGER.info(message, se);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- } catch (IntegrityMonitorException e) {
- String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
- + "\n Exception Message: " + e.getMessage();
- LOGGER.info(message, e);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }
- // Request from the API to get the gitPath
- String apiflag = request.getParameter("apiflag");
- if (apiflag!=null) {
- if(authorizeRequest(request)){
- APIRequestHandler apiRequestHandler = new APIRequestHandler();
- try{
- loggingContext.metricStarted();
- apiRequestHandler.doGet(request,response, apiflag);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
- }catch(IOException e){
- LOGGER.error(e);
- }
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- } else {
- String message = "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");
- setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
- im.endTransaction();
- return;
- }
- }
- // Is this from the Admin Console?
- String groupId = request.getParameter("groupId");
- if (groupId != null) {
- // this is from the Admin Console, so handle separately
- try{
- loggingContext.metricStarted();
- doACGet(request, response, groupId, loggingContext);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
- } catch(IOException e){
+ * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
+ */
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ loggingContext.transactionStarted();
+ loggingContext.setServiceName("PAP.get");
+ if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
+ UUID requestID = UUID.randomUUID();
+ loggingContext.setRequestID(requestID.toString());
+ PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
+ } else {
+ PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
+ }
+ loggingContext.metricStarted();
+ XACMLRest.dumpRequest(request);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
+ String pathInfo = request.getRequestURI();
+ LOGGER.info("path info: " + pathInfo);
+ if (pathInfo != null){
+ //DO NOT do a im.startTransaction for the test request
+ if (pathInfo.equals("/pap/test")) {
+ try {
+ testService(loggingContext, response);
+ } catch (IOException e) {
+ LOGGER.debug(e);
+ }
+ return;
+ }
+ }
+ //This im.startTransaction() covers all other Get transactions
+ try {
+ loggingContext.metricStarted();
+ im.startTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
+ } catch (AdministrativeStateException ae){
+ String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
+ + " state of " + im.getStateManager().getAdminState()
+ + "\n Exception Message: " + ae.getMessage();
+ LOGGER.info(message, ae);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }catch (StandbyStatusException se) {
+ String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
+ + " of " + im.getStateManager().getStandbyStatus()
+ + "\n Exception Message: " + se.getMessage();
+ LOGGER.info(message, se);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ } catch (IntegrityMonitorException e) {
+ String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
+ + "\n Exception Message: " + e.getMessage();
+ LOGGER.info(message, e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }
+ // Request from the API to get the gitPath
+ String apiflag = request.getParameter("apiflag");
+ if (apiflag!=null) {
+ if(authorizeRequest(request)){
+ APIRequestHandler apiRequestHandler = new APIRequestHandler();
+ try{
+ loggingContext.metricStarted();
+ apiRequestHandler.doGet(request,response, apiflag);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ } else {
+ String message = "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");
+ setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
+ im.endTransaction();
+ return;
+ }
+ }
+ // Is this from the Admin Console?
+ String groupId = request.getParameter("groupId");
+ if (groupId != null) {
+ // this is from the Admin Console, so handle separately
+ try{
+ loggingContext.metricStarted();
+ doACGet(request, response, groupId, loggingContext);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
+ } catch(IOException e){
LOGGER.error(e);
}
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- // Get the PDP's ID
- String id = this.getPDPID(request);
- LOGGER.info("doGet from: " + id);
- // Get the PDP Object
- OnapPDP pdp = null;
- try{
- pdp = XACMLPapServlet.papEngine.getPDP(id);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- // Is it known?
- if (pdp == null) {
- // Check if request came from localhost
- if (request.getRemoteHost().equals("localhost") ||
- request.getRemoteHost().equals(request.getLocalAddr())) {
- // Return status information - basically all the groups
- loggingContext.setServiceName("PAP.getGroups");
- Set<OnapPDPGroup> groups = null;
- try {
- groups = papEngine.getOnapPDPGroups();
- } catch(PAPException e) {
- LOGGER.debug(e);
- 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());
- im.endTransaction();
- return;
- }
- // convert response object to JSON and include in the response
- mapperWriteValue(new ObjectMapper(), response, groups);
- response.setHeader("content-type", "application/json");
- response.setStatus(HttpServletResponse.SC_OK);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- 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");
- setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
- im.endTransaction();
- return;
- }
- loggingContext.setServiceName("PAP.getPolicy");
- // Get the PDP's Group
- OnapPDPGroup group = null;
- try {
- group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
- } catch (PAPException e) {
- LOGGER.error(e);
- }
- if (group == null) {
- String message = "No group associated with pdp " + pdp.getId();
- LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
- im.endTransaction();
- return;
- }
- // Which policy do they want?
- String policyId = request.getParameter("id");
- if (policyId == null) {
- String message = "Did not specify an id for the policy";
- LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
- im.endTransaction();
- return;
- }
- PDPPolicy policy = group.getPolicy(policyId);
- if (policy == null) {
- String message = "Unknown policy: " + policyId;
- LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
- im.endTransaction();
- return;
- }
- try{
- 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()) {
- // Send the policy back
- IOUtils.copy(is, os);
- response.setStatus(HttpServletResponse.SC_OK);
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- } catch (IOException e) {
- String message = "Failed to open policy id " + policyId;
- LOGGER.debug(e);
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
- }
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended");
- im.endTransaction();
- }
-
- /**
- * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
- loggingContext.transactionStarted();
- loggingContext.setServiceName("PAP.put");
- if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
- UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
- PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
- } else {
- PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
- }
- try {
- loggingContext.metricStarted();
- im.startTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
- } catch (IntegrityMonitorException e) {
- String message = "PUT interface called for PAP " + papResourceName;
- if (e instanceof AdministrativeStateException) {
- message += " but it has an Administrative state of "
- + im.getStateManager().getAdminState();
- } else if (e instanceof StandbyStatusException) {
- message += " but it has a Standby Status of "
- + im.getStateManager().getStandbyStatus();
- } else {
- message += " but an exception occurred";
-
- }
- message += "\n Exception Message: " + e.getMessage();
-
- LOGGER.info(message, e);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }
-
- loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
- //need to check if request is from the API or Admin console
- String apiflag = request.getParameter("apiflag");
- //This would occur if a PolicyDBDao notification was received
- String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
- if(policyDBDaoRequestUrl != null){
- LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
- String policyDBDaoRequestEntityId = request.getParameter("entityid");
- String policyDBDaoRequestEntityType = request.getParameter("entitytype");
- String policyDBDaoRequestExtraData = request.getParameter("extradata");
- if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
- setResponseError(response,400, "entityid or entitytype not supplied");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- loggingContext.metricStarted();
- LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
- policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
- response.setStatus(200);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- /*
- * Request for ImportService
- */
- String importService = request.getParameter("importService");
- if (importService != null) {
- if(authorizeRequest(request)){
- APIRequestHandler apiRequestHandler = new APIRequestHandler();
- try{
- loggingContext.metricStarted();
- apiRequestHandler.doPut(request, response, importService);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
- }catch(IOException e){
- LOGGER.error(e);
- }
- im.endTransaction();
- return;
- } else {
- String message = "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");
- setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
- return;
- }
- }
- //
- // See if this is Admin Console registering itself with us
- //
- String acURLString = request.getParameter("adminConsoleURL");
- if (acURLString != null) {
- loggingContext.setServiceName("AC:PAP.register");
- // remember this Admin Console for future updates
- if ( ! adminConsoleURLStringList.contains(acURLString)) {
- adminConsoleURLStringList.add(acURLString);
- }
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Admin Console registering with URL: " + acURLString);
- }
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- /*
- * This is to update the PDP Group with the policy/policies being pushed
- * Part of a 2 step process to push policies to the PDP that can now be done
- * From both the Admin Console and the PolicyEngine API
- */
- String groupId = request.getParameter("groupId");
- if (groupId != null) {
- if(apiflag!=null){
- if(!authorizeRequest(request)){
- String message = "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");
- setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
- return;
- }
- if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
- try{
- updateGroupsFromAPI(request, response, groupId, loggingContext);
- }catch(IOException e){
- LOGGER.error(e);
- }
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- }
- // this is from the Admin Console, so handle separately
- try {
- loggingContext.metricEnded();
- doACPut(request, response, groupId, loggingContext);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
- } catch (IOException e) {
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ // Get the PDP's ID
+ String id = this.getPDPID(request);
+ LOGGER.info("doGet from: " + id);
+ // Get the PDP Object
+ OnapPDP pdp = null;
+ try{
+ pdp = XACMLPapServlet.papEngine.getPDP(id);
+ }catch(PAPException e){
LOGGER.error(e);
}
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- //
- // Request is for policy validation and creation
- //
- if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
- // this request is from the Admin Console
- SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
- try{
- loggingContext.metricStarted();
- savePolicyHandler.doPolicyAPIPut(request, response);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
- } catch (IOException e) {
+ // Is it known?
+ if (pdp == null) {
+ // Check if request came from localhost
+ if (request.getRemoteHost().equals("localhost") ||
+ request.getRemoteHost().equals(request.getLocalAddr())) {
+ // Return status information - basically all the groups
+ loggingContext.setServiceName("PAP.getGroups");
+ Set<OnapPDPGroup> groups = null;
+ try {
+ groups = papEngine.getOnapPDPGroups();
+ } catch(PAPException e) {
+ LOGGER.debug(e);
+ 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());
+ im.endTransaction();
+ return;
+ }
+ // convert response object to JSON and include in the response
+ mapperWriteValue(new ObjectMapper(), response, groups);
+ response.setHeader("content-type", "application/json");
+ response.setStatus(HttpServletResponse.SC_OK);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ 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");
+ setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
+ im.endTransaction();
+ return;
+ }
+ loggingContext.setServiceName("PAP.getPolicy");
+ // Get the PDP's Group
+ OnapPDPGroup group = null;
+ try {
+ group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
+ } catch (PAPException e) {
LOGGER.error(e);
}
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
- // this request is from the Policy Creation API
- if(authorizeRequest(request)){
- APIRequestHandler apiRequestHandler = new APIRequestHandler();
- try{
- loggingContext.metricStarted();
- apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
- } catch (IOException e) {
- LOGGER.error(e);
- }
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- } else {
- String message = "PEP not Authorized for making this Request!!";
- PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
- im.endTransaction();
- return;
- }
- }
- // 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");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See error.log");
- im.endTransaction();
- }
-
- /**
- * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
- loggingContext.transactionStarted();
- loggingContext.setServiceName("PAP.delete");
- if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
- UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
- PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
- } else {
- PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
- }
- try {
- loggingContext.metricStarted();
- im.startTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
- } catch (AdministrativeStateException ae){
- String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
- + " state of " + im.getStateManager().getAdminState()
- + "\n Exception Message: " + ae.getMessage();
- LOGGER.info(message, ae);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }catch (StandbyStatusException se) {
- String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
- + " of " + im.getStateManager().getStandbyStatus()
- + "\n Exception Message: " + se.getMessage();
- LOGGER.info(message, se);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- } catch (IntegrityMonitorException e) {
- String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
- + "\n Exception Message: " + e.getMessage();
- LOGGER.info(message, e);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }
- loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
- String groupId = request.getParameter("groupId");
- String apiflag = request.getParameter("apiflag");
- if (groupId != null) {
- // Is this from the Admin Console or API?
- if(apiflag!=null) {
- if(!authorizeRequest(request)){
- String message = "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");
- setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
- return;
- }
- APIRequestHandler apiRequestHandler = new APIRequestHandler();
- try {
- loggingContext.metricStarted();
- apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
- } catch (Exception e) {
- LOGGER.error("Exception Occured"+e);
- }
- if(apiRequestHandler.getNewGroup()!=null){
- groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
- }
- return;
- }
- // this is from the Admin Console, so handle separately
- try{
- loggingContext.metricStarted();
- doACDelete(request, response, groupId, loggingContext);
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
- } catch (IOException e) {
+ if (group == null) {
+ String message = "No group associated with pdp " + pdp.getId();
+ LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
+ im.endTransaction();
+ return;
+ }
+ // Which policy do they want?
+ String policyId = request.getParameter("id");
+ if (policyId == null) {
+ String message = "Did not specify an id for the policy";
+ LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
+ im.endTransaction();
+ return;
+ }
+ PDPPolicy policy = group.getPolicy(policyId);
+ if (policy == null) {
+ String message = "Unknown policy: " + policyId;
+ LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
+ im.endTransaction();
+ return;
+ }
+ try{
+ 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);
}
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended Successfully");
- im.endTransaction();
- return;
- }
- //Catch anything that fell through
- 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");
- im.endTransaction();
- }
-
- private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
- String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
- 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);
- return false;
- }
- // Compare the policies and pipconfig properties to the pdpProperties
- try {
- // the policy properties includes only xacml.rootPolicies and
- // xacml.referencedPolicies without any .url entries
- 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)) {
- // The PDP is current
- return true;
- }
- } catch (Exception e) {
- // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
- // or if there are policies that do not have a corresponding ".url" 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");
- }
- return false;
- }
-
- private 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);
- for (String list : lists) {
- if (list != null && list.isEmpty() == false) {
- for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
- String url = urlPath + "?id=" + id;
- LOGGER.info("Policy URL for " + id + ": " + url);
- policies.setProperty(id + ".url", url);
- }
- }
- }
- }
-
- protected String getPDPID(HttpServletRequest request) {
- 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");
- pdpURL = "";
- }
- return pdpURL;
- }
-
- protected String getPDPJMX(HttpServletRequest request) {
- 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");
- return null;
- }
- return pdpJMMX;
- }
-
- /**
- * Requests from the PolicyEngine API to update the PDP Group with pushed policy
- *
- * @param request
- * @param response
- * @param groupId
- * @param loggingContext
- * @throws ServletException
- * @throws IOException
- */
- public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
- PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
- PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
- try {
- // for PUT operations the group may or may not need to exist before the operation can be done
- StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
-
- // get the request input stream content into a String
- String json = null;
- java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
- scanner.useDelimiter("\\A");
- json = scanner.hasNext() ? scanner.next() : "";
- scanner.close();
-
- PolicyLogger.info("pushPolicy request from API: " + json);
-
- // convert Object sent as JSON into local object
- StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
-
- //Get the current policies from the Group and Add the new one
- Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
- currentPoliciesInGroup = group.getPolicies();
- //If the selected policy is in the group we must remove the old version of it
- LOGGER.info("Removing old version of the policy");
- for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
- if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
- group.removePolicy(existingPolicy);
- LOGGER.info("Removing policy: " + existingPolicy);
- break;
- }
- }
-
- // Assume that this is an update of an existing PDP Group
- loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
- try{
- acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
- +"group="+group.getId());
- throw new PAPException(e.getMessage());
- }
-
- LOGGER.info("Calling updatGroup() with new group");
- papEngine.updateGroup(group);
- String policyId = "empty";
- if(policy !=null && policy.getId() != null){
- policyId = policy.getId();
- }
- if(!policyId.matches(REGEX) ){
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error",ADD_GROUP_ERROR);
- response.addHeader("message", "Policy Id is not valid");
- return;
- }
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- response.addHeader("operation", "push");
- response.addHeader("policyId", policyId);
- response.addHeader("groupId", groupId);
-
- LOGGER.info("Group '" + group.getId() + "' updated");
-
- loggingContext.metricStarted();
- acPutTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
-
- // Group changed, which might include changing the policies
- groupChanged(group, loggingContext);
- loggingContext.transactionEnded();
- LOGGER.info("Success");
-
- 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.");
- }
- }
-
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- } catch (PAPException e) {
- acPutTransaction.rollbackTransaction();
- 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());
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error",ADD_GROUP_ERROR);
- response.addHeader("message", message);
- return;
- }
- }
-
- /**
- * Requests from the Admin Console for operations not on single specific objects
- *
- * @param request
- * @param response
- * @param groupId
- * @param loggingContext
- * @throws ServletException
- * @throws IOException
- */
- private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
- PolicyDBDaoTransaction doACPostTransaction = null;
- try {
- String groupName = request.getParameter("groupName");
- String groupDescription = request.getParameter("groupDescription");
- String apiflag = request.getParameter("apiflag");
- if (groupName != null && groupDescription != null) {
- // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
- loggingContext.setServiceName("AC:PAP.createGroup");
- String unescapedName = null;
- String unescapedDescription = null;
- try{
- unescapedName = URLDecoder.decode(groupName, "UTF-8");
- unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- LOGGER.error(e);
- }
- PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
- try {
- newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
- papEngine.newGroup(unescapedName, unescapedDescription);
- loggingContext.metricStarted();
- newGroupTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
- } catch (Exception e) {
- newGroupTransaction.rollbackTransaction();
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
- return;
- }
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("New Group '" + groupId + "' created");
- }
- // tell the Admin Consoles there is a change
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
- // new group by definition has no PDPs, so no need to notify them of changes
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- // for all remaining POST operations the group must exist before the operation can be done
- OnapPDPGroup group = null;
- try{
- group = papEngine.getGroup(groupId);
- } catch (PAPException e){
- LOGGER.error(e);
- }
- if (group == null) {
- String message = "Unknown groupId '" + groupId + "'";
- //for fixing Header Manipulation of Fortify issue
- if(!message.matches(REGEX)){
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error",ADD_GROUP_ERROR);
- response.addHeader("message", "GroupId Id is not valid");
- return;
- }
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- if (apiflag!=null){
- response.addHeader("error", "unknownGroupId");
- response.addHeader("operation", "push");
- response.addHeader("message", message);
- response.setStatus(HttpServletResponse.SC_NOT_FOUND);
- } else {
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
- }
- return;
- }
-
- // If the request contains a policyId then we know we are pushing the policy to PDP
- if (request.getParameter("policyId") != null) {
-
- if(apiflag!=null){
- loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
- LOGGER.info("PushPolicy Request From The API");
- } else {
- loggingContext.setServiceName("AC:PAP.postPolicy");
- LOGGER.info("PushPolicy Request From The AC");
- }
-
- String policyId = request.getParameter("policyId");
- PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
- StdPDPGroup updatedGroup = null;
- try {
- //Copying the policy to the file system and updating groups in database
- LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
- updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
- loggingContext.metricStarted();
- addPolicyToGroupTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
- LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
-
- } catch (Exception e) {
- addPolicyToGroupTransaction.rollbackTransaction();
- String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
- //for fixing Header Manipulation of Fortify issue
- if(!message.matches(REGEX)){
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error",ADD_GROUP_ERROR);
- response.addHeader("message", "Policy Id is not valid");
- return;
- }
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- if (apiflag!=null){
- response.addHeader("error", "policyCopyError");
- response.addHeader("message", message);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- } else {
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- }
- return;
- }
-
- if(apiflag != null){
- /*
- * 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()
- PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
- try {
- // get the request content into a String and read the inputStream into a buffer
- java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
- scanner.useDelimiter("\\A");
- String json = scanner.hasNext() ? scanner.next() : "";
- scanner.close();
-
- // convert Object sent as JSON into local object
- ObjectMapper mapper = new ObjectMapper();
- Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
- StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
-
- LOGGER.info("Request JSON Payload: " + json);
-
- // Assume that this is an update of an existing PDP Group
- loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
- try{
- acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
- + e);
- throw new PAPException(e.getMessage());
- }
-
- LOGGER.info("Calling updatGroup() with new group");
- papEngine.updateGroup(updatedGroup);
-
- LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
-
- // Commit transaction to send notification to other PAPs
- loggingContext.metricStarted();
- acPutTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
- loggingContext.metricStarted();
-
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
-
- // Group changed to send notification to PDPs, which might include changing the policies
- groupChanged(updatedGroup,loggingContext);
- loggingContext.transactionEnded();
- LOGGER.info("Success");
-
- if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
- PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
- if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
- LOGGER.debug("Precheck Successful.");
- }
- }
-
- //delete temporary policy file from the bin directory
- Files.deleteIfExists(Paths.get(policy.getId()));
-
- } catch (Exception e) {
- acPutTransaction.rollbackTransaction();
- 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 occurred when updating the group from API.";
- LOGGER.error(message);
- 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);
- return;
- }
- }
-
- // policy file copied ok and the Group was updated on the PDP
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- response.addHeader("operation", "push");
- response.addHeader("policyId", policyId);
- response.addHeader("groupId", groupId);
-
- LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- LOGGER.info("Transaction Ended Successfully");
-
- 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 the request.
- loggingContext.setServiceName("AC:PAP.setDefaultGroup");
- // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
- // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
- PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
- try {
- setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
- papEngine.setDefaultGroup(group);
- loggingContext.metricStarted();
- setDefaultGroupTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
- } catch (Exception e) {
- setDefaultGroupTransaction.rollbackTransaction();
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
- return;
- }
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Group '" + groupId + "' set to be default");
- }
- // Notify the Admin Consoles that something changed
- // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
- //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
- loggingContext.metricStarted();
- notifyAC();
- // This does not affect any PDPs in the existing groups, so no need to notify them of this change
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- LOGGER.info("Transaction Ended Successfully");
- return;
- } else if (request.getParameter("pdpId") != null) {
- doACPostTransaction = policyDBDao.getNewTransaction();
- // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
- loggingContext.setServiceName("AC:PAP.movePDP");
- String pdpId = request.getParameter("pdpId");
- OnapPDP pdp = papEngine.getPDP(pdpId);
- OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
- try{
- doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
- }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="+group.getId());
- throw new PAPException(e.getMessage());
- }
- papEngine.movePDP((OnapPDP) pdp, group);
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
- }
- // update the status of both the original group and the new one
- ((StdPDPGroup)originalGroup).resetStatus();
- ((StdPDPGroup)group).resetStatus();
- // Notify the Admin Consoles that something changed
- // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
- // Need to notify the PDP that it's config may have changed
- pdpChanged(pdp, loggingContext);
- loggingContext.metricStarted();
- doACPostTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- } catch (PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
- }
- }
-
- /**
- * Requests from the Admin Console to GET info about the Groups and PDPs
- *
- * @param request
- * @param response
- * @param groupId
- * @param loggingContext
- * @throws ServletException
- * @throws IOException
- */
- private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
- try {
- String parameterDefault = request.getParameter("default");
- String pdpId = request.getParameter("pdpId");
- String pdpGroup = request.getParameter("getPDPGroup");
- if ("".equals(groupId)) {
- // request IS from AC but does not identify a group by name
- if (parameterDefault != null) {
- // Request is for the Default group (whatever its id)
- loggingContext.setServiceName("AC:PAP.getDefaultGroup");
- OnapPDPGroup group = papEngine.getDefaultGroup();
- // convert response object to JSON and include in the response
- mapperWriteValue(new ObjectMapper(), response, group);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
- }
- response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
- try{
+ 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);
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ } catch (IOException e) {
+ String message = "Failed to open policy id " + policyId;
+ LOGGER.debug(e);
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended");
+ im.endTransaction();
+ }
+
+ /**
+ * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
+ */
+ protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ loggingContext.transactionStarted();
+ loggingContext.setServiceName("PAP.put");
+ if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
+ UUID requestID = UUID.randomUUID();
+ loggingContext.setRequestID(requestID.toString());
+ PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
+ } else {
+ PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
+ }
+ try {
+ loggingContext.metricStarted();
+ im.startTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
+ } catch (IntegrityMonitorException e) {
+ String message = "PUT interface called for PAP " + papResourceName;
+ if (e instanceof AdministrativeStateException) {
+ message += " but it has an Administrative state of "
+ + im.getStateManager().getAdminState();
+ } else if (e instanceof StandbyStatusException) {
+ message += " but it has a Standby Status of "
+ + im.getStateManager().getStandbyStatus();
+ } else {
+ message += " but an exception occurred";
+
+ }
+ message += "\n Exception Message: " + e.getMessage();
+
+ LOGGER.info(message, e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }
+
+ loggingContext.metricStarted();
+ XACMLRest.dumpRequest(request);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
+ //need to check if request is from the API or Admin console
+ String apiflag = request.getParameter("apiflag");
+ //This would occur if a PolicyDBDao notification was received
+ String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
+ if(policyDBDaoRequestUrl != null){
+ LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
+ String policyDBDaoRequestEntityId = request.getParameter("entityid");
+ String policyDBDaoRequestEntityType = request.getParameter("entitytype");
+ String policyDBDaoRequestExtraData = request.getParameter("extradata");
+ if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
+ setResponseError(response,400, "entityid or entitytype not supplied");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ loggingContext.metricStarted();
+ LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
+ policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
+ response.setStatus(200);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ /*
+ * Request for ImportService
+ */
+ String importService = request.getParameter("importService");
+ if (importService != null) {
+ if(authorizeRequest(request)){
+ APIRequestHandler apiRequestHandler = new APIRequestHandler();
+ try{
+ loggingContext.metricStarted();
+ apiRequestHandler.doPut(request, response, importService);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ im.endTransaction();
+ return;
+ } else {
+ String message = "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");
+ setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
+ return;
+ }
+ }
+ //
+ // See if this is Admin Console registering itself with us
+ //
+ String acURLString = request.getParameter("adminConsoleURL");
+ if (acURLString != null) {
+ loggingContext.setServiceName("AC:PAP.register");
+ // remember this Admin Console for future updates
+ if ( ! adminConsoleURLStringList.contains(acURLString)) {
+ adminConsoleURLStringList.add(acURLString);
+ }
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Admin Console registering with URL: " + acURLString);
+ }
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ /*
+ * This is to update the PDP Group with the policy/policies being pushed
+ * Part of a 2 step process to push policies to the PDP that can now be done
+ * From both the Admin Console and the PolicyEngine API
+ */
+ String groupId = request.getParameter("groupId");
+ if (groupId != null) {
+ if(apiflag!=null){
+ if(!authorizeRequest(request)){
+ String message = "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");
+ setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
+ return;
+ }
+ if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
+ try{
+ updateGroupsFromAPI(request, response, groupId, loggingContext);
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ }
+ // this is from the Admin Console, so handle separately
+ try {
+ loggingContext.metricEnded();
+ doACPut(request, response, groupId, loggingContext);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
+ } catch (IOException e) {
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ //
+ // Request is for policy validation and creation
+ //
+ if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
+ // this request is from the Admin Console
+ SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
+ try{
+ loggingContext.metricStarted();
+ savePolicyHandler.doPolicyAPIPut(request, response);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
+ } catch (IOException e) {
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
+ // this request is from the Policy Creation API
+ if(authorizeRequest(request)){
+ APIRequestHandler apiRequestHandler = new APIRequestHandler();
+ try{
+ loggingContext.metricStarted();
+ apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
+ } catch (IOException e) {
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ } else {
+ String message = "PEP not Authorized for making this Request!!";
+ PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
+ im.endTransaction();
+ return;
+ }
+ }
+ // 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");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See error.log");
+ im.endTransaction();
+ }
+
+ /**
+ * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
+ */
+ protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ loggingContext.transactionStarted();
+ loggingContext.setServiceName("PAP.delete");
+ if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
+ UUID requestID = UUID.randomUUID();
+ loggingContext.setRequestID(requestID.toString());
+ PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
+ } else {
+ PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
+ }
+ try {
+ loggingContext.metricStarted();
+ im.startTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
+ } catch (AdministrativeStateException ae){
+ String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
+ + " state of " + im.getStateManager().getAdminState()
+ + "\n Exception Message: " + ae.getMessage();
+ LOGGER.info(message, ae);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }catch (StandbyStatusException se) {
+ String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
+ + " of " + im.getStateManager().getStandbyStatus()
+ + "\n Exception Message: " + se.getMessage();
+ LOGGER.info(message, se);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ } catch (IntegrityMonitorException e) {
+ String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
+ + "\n Exception Message: " + e.getMessage();
+ LOGGER.info(message, e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }
+ loggingContext.metricStarted();
+ XACMLRest.dumpRequest(request);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
+ String groupId = request.getParameter("groupId");
+ String apiflag = request.getParameter("apiflag");
+ if (groupId != null) {
+ // Is this from the Admin Console or API?
+ if(apiflag!=null) {
+ if(!authorizeRequest(request)){
+ String message = "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");
+ setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
+ return;
+ }
+ APIRequestHandler apiRequestHandler = new APIRequestHandler();
+ try {
+ loggingContext.metricStarted();
+ apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured"+e);
+ }
+ if(apiRequestHandler.getNewGroup()!=null){
+ groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
+ }
+ return;
+ }
+ // this is from the Admin Console, so handle separately
+ try{
+ loggingContext.metricStarted();
+ doACDelete(request, response, groupId, loggingContext);
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
+ } catch (IOException e) {
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended Successfully");
+ im.endTransaction();
+ return;
+ }
+ //Catch anything that fell through
+ 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");
+ im.endTransaction();
+ }
+
+ private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
+ String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
+ 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);
+ return false;
+ }
+ // Compare the policies and pipconfig properties to the pdpProperties
+ try {
+ // the policy properties includes only xacml.rootPolicies and
+ // xacml.referencedPolicies without any .url entries
+ 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)) {
+ // The PDP is current
+ return true;
+ }
+ } catch (Exception e) {
+ // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
+ // or if there are policies that do not have a corresponding ".url" 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");
+ }
+ return false;
+ }
+
+ private 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);
+ for (String list : lists) {
+ if (list != null && list.isEmpty() == false) {
+ for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
+ String url = urlPath + "?id=" + id;
+ LOGGER.info("Policy URL for " + id + ": " + url);
+ policies.setProperty(id + ".url", url);
+ }
+ }
+ }
+ }
+
+ protected String getPDPID(HttpServletRequest request) {
+ 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");
+ pdpURL = "";
+ }
+ return pdpURL;
+ }
+
+ protected String getPDPJMX(HttpServletRequest request) {
+ 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");
+ return null;
+ }
+ return pdpJMMX;
+ }
+
+ /**
+ * Requests from the PolicyEngine API to update the PDP Group with pushed policy
+ *
+ * @param request
+ * @param response
+ * @param groupId
+ * @param loggingContext
+ * @throws ServletException
+ * @throws IOException
+ */
+ public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
+ PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
+ PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
+ try {
+ // for PUT operations the group may or may not need to exist before the operation can be done
+ StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
+
+ // get the request input stream content into a String
+ String json = null;
+ java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+
+ PolicyLogger.info("pushPolicy request from API: " + json);
+
+ // convert Object sent as JSON into local object
+ StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
+
+ //Get the current policies from the Group and Add the new one
+ Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
+ currentPoliciesInGroup = group.getPolicies();
+ //If the selected policy is in the group we must remove the old version of it
+ LOGGER.info("Removing old version of the policy");
+ for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
+ if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
+ group.removePolicy(existingPolicy);
+ LOGGER.info("Removing policy: " + existingPolicy);
+ break;
+ }
+ }
+
+ // Assume that this is an update of an existing PDP Group
+ loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
+ try{
+ acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
+ +"group="+group.getId());
+ throw new PAPException(e.getMessage());
+ }
+
+ LOGGER.info("Calling updatGroup() with new group");
+ papEngine.updateGroup(group);
+ String policyId = "empty";
+ if(policy !=null && policy.getId() != null){
+ policyId = policy.getId();
+ }
+ if(!policyId.matches(REGEX) ){
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error",ADD_GROUP_ERROR);
+ response.addHeader("message", "Policy Id is not valid");
+ return;
+ }
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ response.addHeader("operation", "push");
+ response.addHeader("policyId", policyId);
+ response.addHeader("groupId", groupId);
+
+ LOGGER.info("Group '" + group.getId() + "' updated");
+
+ loggingContext.metricStarted();
+ acPutTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
+
+ // Group changed, which might include changing the policies
+ groupChanged(group, loggingContext);
+ loggingContext.transactionEnded();
+ LOGGER.info("Success");
+
+ 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.");
+ }
+ }
+
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ } catch (PAPException e) {
+ acPutTransaction.rollbackTransaction();
+ 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());
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error",ADD_GROUP_ERROR);
+ response.addHeader("message", message);
+ return;
+ }
+ }
+
+ /**
+ * Requests from the Admin Console for operations not on single specific objects
+ *
+ * @param request
+ * @param response
+ * @param groupId
+ * @param loggingContext
+ * @throws ServletException
+ * @throws IOException
+ */
+ private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
+ PolicyDBDaoTransaction doACPostTransaction = null;
+ try {
+ String groupName = request.getParameter("groupName");
+ String groupDescription = request.getParameter("groupDescription");
+ String apiflag = request.getParameter("apiflag");
+ if (groupName != null && groupDescription != null) {
+ // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
+ loggingContext.setServiceName("AC:PAP.createGroup");
+ String unescapedName = null;
+ String unescapedDescription = null;
+ try{
+ unescapedName = URLDecoder.decode(groupName, "UTF-8");
+ unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ LOGGER.error(e);
+ }
+ PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
+ try {
+ newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
+ papEngine.newGroup(unescapedName, unescapedDescription);
+ loggingContext.metricStarted();
+ newGroupTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
+ } catch (Exception e) {
+ newGroupTransaction.rollbackTransaction();
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
+ return;
+ }
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("New Group '" + groupId + "' created");
+ }
+ // tell the Admin Consoles there is a change
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
+ // new group by definition has no PDPs, so no need to notify them of changes
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ // for all remaining POST operations the group must exist before the operation can be done
+ OnapPDPGroup group = null;
+ try{
+ group = papEngine.getGroup(groupId);
+ } catch (PAPException e){
+ LOGGER.error(e);
+ }
+ if (group == null) {
+ String message = "Unknown groupId '" + groupId + "'";
+ //for fixing Header Manipulation of Fortify issue
+ if(!message.matches(REGEX)){
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error",ADD_GROUP_ERROR);
+ response.addHeader("message", "GroupId Id is not valid");
+ return;
+ }
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ if (apiflag!=null){
+ response.addHeader("error", "unknownGroupId");
+ response.addHeader("operation", "push");
+ response.addHeader("message", message);
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ } else {
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
+ }
+ return;
+ }
+
+ // If the request contains a policyId then we know we are pushing the policy to PDP
+ if (request.getParameter("policyId") != null) {
+
+ if(apiflag!=null){
+ loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
+ LOGGER.info("PushPolicy Request From The API");
+ } else {
+ loggingContext.setServiceName("AC:PAP.postPolicy");
+ LOGGER.info("PushPolicy Request From The AC");
+ }
+
+ String policyId = request.getParameter("policyId");
+ PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
+ StdPDPGroup updatedGroup = null;
+ try {
+ //Copying the policy to the file system and updating groups in database
+ LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
+ updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
+ loggingContext.metricStarted();
+ addPolicyToGroupTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
+ LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
+
+ } catch (Exception e) {
+ addPolicyToGroupTransaction.rollbackTransaction();
+ String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
+ //for fixing Header Manipulation of Fortify issue
+ if(!message.matches(REGEX)){
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error",ADD_GROUP_ERROR);
+ response.addHeader("message", "Policy Id is not valid");
+ return;
+ }
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ if (apiflag!=null){
+ response.addHeader("error", "policyCopyError");
+ response.addHeader("message", message);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ } else {
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ }
+ return;
+ }
+
+ if(apiflag != null){
+ /*
+ * 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()
+ PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
+ try {
+ // get the request content into a String and read the inputStream into a buffer
+ java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ String json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+
+ // convert Object sent as JSON into local object
+ ObjectMapper mapper = new ObjectMapper();
+ Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
+ StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
+
+ LOGGER.info("Request JSON Payload: " + json);
+
+ // Assume that this is an update of an existing PDP Group
+ loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
+ try{
+ acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
+ + e);
+ throw new PAPException(e.getMessage());
+ }
+
+ LOGGER.info("Calling updatGroup() with new group");
+ papEngine.updateGroup(updatedGroup);
+
+ LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
+
+ // Commit transaction to send notification to other PAPs
+ loggingContext.metricStarted();
+ acPutTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
+ loggingContext.metricStarted();
+
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
+
+ // Group changed to send notification to PDPs, which might include changing the policies
+ groupChanged(updatedGroup,loggingContext);
+ loggingContext.transactionEnded();
+ LOGGER.info("Success");
+
+ if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
+ PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
+ if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
+ LOGGER.debug("Precheck Successful.");
+ }
+ }
+
+ //delete temporary policy file from the bin directory
+ Files.deleteIfExists(Paths.get(policy.getId()));
+
+ } catch (Exception e) {
+ acPutTransaction.rollbackTransaction();
+ 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 occurred when updating the group from API.";
+ LOGGER.error(message);
+ 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);
+ return;
+ }
+ }
+
+ // policy file copied ok and the Group was updated on the PDP
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ response.addHeader("operation", "push");
+ response.addHeader("policyId", policyId);
+ response.addHeader("groupId", groupId);
+
+ LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ LOGGER.info("Transaction Ended Successfully");
+
+ 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 the request.
+ loggingContext.setServiceName("AC:PAP.setDefaultGroup");
+ // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
+ // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
+ PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
+ try {
+ setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
+ papEngine.setDefaultGroup(group);
+ loggingContext.metricStarted();
+ setDefaultGroupTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
+ } catch (Exception e) {
+ setDefaultGroupTransaction.rollbackTransaction();
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
+ return;
+ }
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Group '" + groupId + "' set to be default");
+ }
+ // Notify the Admin Consoles that something changed
+ // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
+ //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
+ loggingContext.metricStarted();
+ notifyAC();
+ // This does not affect any PDPs in the existing groups, so no need to notify them of this change
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ LOGGER.info("Transaction Ended Successfully");
+ return;
+ } else if (request.getParameter("pdpId") != null) {
+ doACPostTransaction = policyDBDao.getNewTransaction();
+ // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
+ loggingContext.setServiceName("AC:PAP.movePDP");
+ String pdpId = request.getParameter("pdpId");
+ OnapPDP pdp = papEngine.getPDP(pdpId);
+ OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
+ try{
+ doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
+ }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="+group.getId());
+ throw new PAPException(e.getMessage());
+ }
+ papEngine.movePDP((OnapPDP) pdp, group);
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
+ }
+ // update the status of both the original group and the new one
+ ((StdPDPGroup)originalGroup).resetStatus();
+ ((StdPDPGroup)group).resetStatus();
+ // Notify the Admin Consoles that something changed
+ // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
+ // Need to notify the PDP that it's config may have changed
+ pdpChanged(pdp, loggingContext);
+ loggingContext.metricStarted();
+ doACPostTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ } catch (PAPException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+ return;
+ }
+ }
+
+ /**
+ * Requests from the Admin Console to GET info about the Groups and PDPs
+ *
+ * @param request
+ * @param response
+ * @param groupId
+ * @param loggingContext
+ * @throws ServletException
+ * @throws IOException
+ */
+ private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
+ try {
+ String parameterDefault = request.getParameter("default");
+ String pdpId = request.getParameter("pdpId");
+ String pdpGroup = request.getParameter("getPDPGroup");
+ if ("".equals(groupId)) {
+ // request IS from AC but does not identify a group by name
+ if (parameterDefault != null) {
+ // Request is for the Default group (whatever its id)
+ loggingContext.setServiceName("AC:PAP.getDefaultGroup");
+ OnapPDPGroup group = papEngine.getDefaultGroup();
+ // convert response object to JSON and include in the response
+ mapperWriteValue(new ObjectMapper(), response, group);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.setHeader("content-type", "application/json");
+ try{
response.getOutputStream().close();
} catch (IOException e){
LOGGER.error(e);
}
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- } else if (pdpId != null) {
- // Request is related to a PDP
- if (pdpGroup == null) {
- // Request is for the (unspecified) group containing a given PDP
- loggingContext.setServiceName("AC:PAP.getPDP");
- OnapPDP pdp = null;
- try{
- pdp = papEngine.getPDP(pdpId);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- // convert response object to JSON and include in the response
- mapperWriteValue(new ObjectMapper(), response, pdp);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
- }
- response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
- try{
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ } else if (pdpId != null) {
+ // Request is related to a PDP
+ if (pdpGroup == null) {
+ // Request is for the (unspecified) group containing a given PDP
+ loggingContext.setServiceName("AC:PAP.getPDP");
+ OnapPDP pdp = null;
+ try{
+ pdp = papEngine.getPDP(pdpId);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ // convert response object to JSON and include in the response
+ mapperWriteValue(new ObjectMapper(), response, pdp);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.setHeader("content-type", "application/json");
+ try{
+ response.getOutputStream().close();
+ } catch (IOException e){
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ } else {
+ // Request is for the group containing a given PDP
+ loggingContext.setServiceName("AC:PAP.getGroupForPDP");
+ OnapPDPGroup group =null;
+ try{
+ OnapPDP pdp = papEngine.getPDP(pdpId);
+ group = papEngine.getPDPGroup((OnapPDP) pdp);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ // convert response object to JSON and include in the response
+ mapperWriteValue(new ObjectMapper(), response, group);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.setHeader("content-type", "application/json");
+ try{
response.getOutputStream().close();
} catch (IOException e){
LOGGER.error(e);
}
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- } else {
- // Request is for the group containing a given PDP
- loggingContext.setServiceName("AC:PAP.getGroupForPDP");
- OnapPDPGroup group =null;
- try{
- OnapPDP pdp = papEngine.getPDP(pdpId);
- group = papEngine.getPDPGroup((OnapPDP) pdp);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- // convert response object to JSON and include in the response
- mapperWriteValue(new ObjectMapper(), response, group);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
- }
- response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
- try{
- response.getOutputStream().close();
- } catch (IOException e){
- LOGGER.error(e);
- }
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- } else {
- // request is for top-level properties about all groups
- loggingContext.setServiceName("AC:PAP.getAllGroups");
- Set<OnapPDPGroup> groups = null;
- try {
- groups = papEngine.getOnapPDPGroups();
- } catch(PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
- }
- // convert response object to JSON and include in the response
- mapperWriteValue(new ObjectMapper(), response, groups);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("GET All groups req");
- }
- response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
- try{
- response.getOutputStream().close();
- } catch (IOException e){
- LOGGER.error(e);
- }
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- }
- // for all other GET operations the group must exist before the operation can be done
- OnapPDPGroup group = null;
- try{
- group = papEngine.getGroup(groupId);
- } catch(PAPException e){
- LOGGER.error(e);
- }
- if (group == null) {
- String message = "Unknown groupId '" + groupId + "'";
- //for fixing Header Manipulation of Fortify issue
- if(!message.matches(REGEX)){
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error",ADD_GROUP_ERROR);
- response.addHeader("message", "Group Id is not valid");
- return;
- }
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
- return;
- }
- // Figure out which request this is based on the parameters
- String policyId = request.getParameter("policyId");
- if (policyId != null) {
- // retrieve a policy
- loggingContext.setServiceName("AC:PAP.getPolicy");
- // convert response object to JSON and include in the response
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
- } else {
- // No other parameters, so return the identified Group
- loggingContext.setServiceName("AC:PAP.getGroup");
- // convert response object to JSON and include in the response
- mapperWriteValue(new ObjectMapper(), response, group);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
- }
- response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
- try{
- response.getOutputStream().close();
- } catch (IOException e){
- LOGGER.error(e);
- }
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- // Currently there are no other GET calls from the AC.
- // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP.
- // Other GETs that could be called:
- // Specific Group (groupId=<groupId>)
- // A Policy (groupId=<groupId> policyId=<policyId>)
- // A PDP (groupId=<groupId> pdpId=<pdpId>)
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- 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("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
- }
- }
-
- /**
- * Requests from the Admin Console to create new items or update existing ones
- *
- * @param request
- * @param response
- * @param groupId
- * @param loggingContext
- * @throws ServletException
- * @throws IOException
- */
- private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
- PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
- try {
- // for PUT operations the group may or may not need to exist before the operation can be done
- OnapPDPGroup group = papEngine.getGroup(groupId);
- // determine the operation needed based on the parameters in the request
- // for remaining operations the group must exist before the operation can be done
- if (group == null) {
- String message = "Unknown groupId '" + groupId + "'";
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
- return;
- }
- if (request.getParameter("policy") != null) {
- // group=<groupId> policy=<policyId> contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties)
- loggingContext.setServiceName("AC:PAP.putPolicy");
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- } else if (request.getParameter("pdpId") != null) {
- // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
- String pdpId = request.getParameter("pdpId");
- if (papEngine.getPDP(pdpId) == null) {
- loggingContext.setServiceName("AC:PAP.createPDP");
- } else {
- loggingContext.setServiceName("AC:PAP.updatePDP");
- }
- // get the request content into a String
- String json = null;
- // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
- try{
- Scanner scanner = new Scanner(request.getInputStream());
- scanner.useDelimiter("\\A");
- json = scanner.hasNext() ? scanner.next() : "";
- scanner.close();
- }catch(IOException e){
- LOGGER.error(e);
- }
- LOGGER.info("JSON request from AC: " + json);
- // convert Object sent as JSON into local object
- ObjectMapper mapper = new ObjectMapper();
- Object objectFromJSON = null;
- try {
- objectFromJSON = mapper.readValue(json, StdPDP.class);
- } catch(Exception e) {
- LOGGER.error(e);
- }
- if (pdpId == null ||
- objectFromJSON == null ||
- ! (objectFromJSON instanceof StdPDP) ||
- ((StdPDP)objectFromJSON).getId() == null ||
- ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
- }
- StdPDP pdp = (StdPDP) objectFromJSON;
- if(pdp != null){
- OnapPDP oPDP = null;
- try{
- oPDP = papEngine.getPDP(pdpId);
- }catch (PAPException e){
- LOGGER.error(e);
- }
- if (oPDP == null) {
- // 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");
- } 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());
- throw new PAPException(e.getMessage());
- }
- try{
- papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
- }catch(PAPException e){
- LOGGER.error(e);
- }
- } else {
- try{
- acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
- +"pdp="+ pdp.getId());
- throw new PAPException(e.getMessage());
- }
- // this is a request to update the pdp
- try{
- papEngine.updatePDP(pdp);
- }catch(PAPException e){
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ } else {
+ // request is for top-level properties about all groups
+ loggingContext.setServiceName("AC:PAP.getAllGroups");
+ Set<OnapPDPGroup> groups = null;
+ try {
+ groups = papEngine.getOnapPDPGroups();
+ } catch(PAPException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+ return;
+ }
+ // convert response object to JSON and include in the response
+ mapperWriteValue(new ObjectMapper(), response, groups);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("GET All groups req");
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.setHeader("content-type", "application/json");
+ try{
+ response.getOutputStream().close();
+ } catch (IOException e){
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ }
+ // for all other GET operations the group must exist before the operation can be done
+ OnapPDPGroup group = null;
+ try{
+ group = papEngine.getGroup(groupId);
+ } catch(PAPException e){
+ LOGGER.error(e);
+ }
+ if (group == null) {
+ String message = "Unknown groupId '" + groupId + "'";
+ //for fixing Header Manipulation of Fortify issue
+ if(!message.matches(REGEX)){
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error",ADD_GROUP_ERROR);
+ response.addHeader("message", "Group Id is not valid");
+ return;
+ }
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
+ return;
+ }
+ // Figure out which request this is based on the parameters
+ String policyId = request.getParameter("policyId");
+ if (policyId != null) {
+ // retrieve a policy
+ loggingContext.setServiceName("AC:PAP.getPolicy");
+ // convert response object to JSON and include in the response
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
+ } else {
+ // No other parameters, so return the identified Group
+ loggingContext.setServiceName("AC:PAP.getGroup");
+ // convert response object to JSON and include in the response
+ mapperWriteValue(new ObjectMapper(), response, group);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.setHeader("content-type", "application/json");
+ try{
+ response.getOutputStream().close();
+ } catch (IOException e){
+ LOGGER.error(e);
+ }
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ // Currently there are no other GET calls from the AC.
+ // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP.
+ // Other GETs that could be called:
+ // Specific Group (groupId=<groupId>)
+ // A Policy (groupId=<groupId> policyId=<policyId>)
+ // A PDP (groupId=<groupId> pdpId=<pdpId>)
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ 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("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+ return;
+ }
+ }
+
+ /**
+ * Requests from the Admin Console to create new items or update existing ones
+ *
+ * @param request
+ * @param response
+ * @param groupId
+ * @param loggingContext
+ * @throws ServletException
+ * @throws IOException
+ */
+ private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
+ PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
+ try {
+ // for PUT operations the group may or may not need to exist before the operation can be done
+ OnapPDPGroup group = papEngine.getGroup(groupId);
+ // determine the operation needed based on the parameters in the request
+ // for remaining operations the group must exist before the operation can be done
+ if (group == null) {
+ String message = "Unknown groupId '" + groupId + "'";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
+ return;
+ }
+ if (request.getParameter("policy") != null) {
+ // group=<groupId> policy=<policyId> contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties)
+ loggingContext.setServiceName("AC:PAP.putPolicy");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ } else if (request.getParameter("pdpId") != null) {
+ // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
+ String pdpId = request.getParameter("pdpId");
+ if (papEngine.getPDP(pdpId) == null) {
+ loggingContext.setServiceName("AC:PAP.createPDP");
+ } else {
+ loggingContext.setServiceName("AC:PAP.updatePDP");
+ }
+ // get the request content into a String
+ String json = null;
+ // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
+ try{
+ Scanner scanner = new Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+ }catch(IOException e){
+ LOGGER.error(e);
+ }
+ LOGGER.info("JSON request from AC: " + json);
+ // convert Object sent as JSON into local object
+ ObjectMapper mapper = new ObjectMapper();
+ Object objectFromJSON = null;
+ try {
+ objectFromJSON = mapper.readValue(json, StdPDP.class);
+ } catch(Exception e) {
+ LOGGER.error(e);
+ }
+ if (pdpId == null ||
+ objectFromJSON == null ||
+ ! (objectFromJSON instanceof StdPDP) ||
+ ((StdPDP)objectFromJSON).getId() == null ||
+ ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
+ }
+ StdPDP pdp = (StdPDP) objectFromJSON;
+ if(pdp != null){
+ OnapPDP oPDP = null;
+ try{
+ oPDP = papEngine.getPDP(pdpId);
+ }catch (PAPException e){
+ LOGGER.error(e);
+ }
+ if (oPDP == null) {
+ // 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");
+ } 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());
+ throw new PAPException(e.getMessage());
+ }
+ try{
+ papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ } else {
+ try{
+ acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
+ +"pdp="+ pdp.getId());
+ throw new PAPException(e.getMessage());
+ }
+ // this is a request to update the pdp
+ try{
+ papEngine.updatePDP(pdp);
+ }catch(PAPException e){
LOGGER.error(e);
}
- }
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("PDP '" + pdpId + "' created/updated");
- }
- // adjust the group's state including the new PDP
- ((StdPDPGroup)group).resetStatus();
- // tell the Admin Consoles there is a change
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
- // this might affect the PDP, so notify it of the change
- pdpChanged(pdp, loggingContext);
- loggingContext.metricStarted();
- acPutTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }else{
- try{
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
- +"pdp=null" + ",to group="+group.getId());
- throw new PAPException("PDP is null");
- } catch(Exception e){
- throw new PAPException("PDP is null" + e.getMessage() +e);
- }
- }
- } else if (request.getParameter("pipId") != null) {
- // group=<groupId> pipId=<pipEngineId> contents=pip properties <= 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");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
- return;
- } else {
- // Assume that this is an update of an existing PDP Group
- // ARGS: group=<groupId> <= Update an Existing Group
- loggingContext.setServiceName("AC:PAP.updateGroup");
- // get the request content into a String
- String json = null;
- // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
+ }
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("PDP '" + pdpId + "' created/updated");
+ }
+ // adjust the group's state including the new PDP
+ ((StdPDPGroup)group).resetStatus();
+ // tell the Admin Consoles there is a change
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
+ // this might affect the PDP, so notify it of the change
+ pdpChanged(pdp, loggingContext);
+ loggingContext.metricStarted();
+ acPutTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }else{
+ try{
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
+ +"pdp=null" + ",to group="+group.getId());
+ throw new PAPException("PDP is null");
+ } catch(Exception e){
+ throw new PAPException("PDP is null" + e.getMessage() +e);
+ }
+ }
+ } else if (request.getParameter("pipId") != null) {
+ // group=<groupId> pipId=<pipEngineId> contents=pip properties <= 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");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ return;
+ } else {
+ // Assume that this is an update of an existing PDP Group
+ // ARGS: group=<groupId> <= Update an Existing Group
+ loggingContext.setServiceName("AC:PAP.updateGroup");
+ // get the request content into a String
+ String json = null;
+ // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
try{
Scanner scanner = new Scanner(request.getInputStream());
scanner.useDelimiter("\\A");
@@ -2158,880 +2158,880 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}catch(IOException e){
LOGGER.error(e);
}
- LOGGER.info("JSON request from AC: " + json);
- // convert Object sent as JSON into local object
- ObjectMapper mapper = new ObjectMapper();
- Object objectFromJSON = null;
- try {
- objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
- } catch(Exception e) {
- LOGGER.error(e);
- }
- if (objectFromJSON == null || ! (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);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
- }
- // The Path on the PAP side is not carried on the RESTful interface with the AC
- // (because it is local to the PAP)
- // so we need to fill that in before submitting the group for update
- if(objectFromJSON != null){
- ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
- }
- try{
- if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
- acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
- } else {
- acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
- }
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
- +"group="+group.getId());
- LOGGER.error(e);
- throw new PAPException(e.getMessage());
- }
-
- PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
- OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
- if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
- LOGGER.debug("Precheck Successful.");
- }
- try{
- papEngine.updateGroup((StdPDPGroup)objectFromJSON);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Group '" + group.getId() + "' updated");
- }
- loggingContext.metricStarted();
- acPutTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
- // tell the Admin Consoles there is a change
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
- // Group changed, which might include changing the policies
- groupChanged(group, loggingContext);
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- } catch (PAPException e) {
- LOGGER.debug(e);
- acPutTransaction.rollbackTransaction();
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
- }
- }
-
- /**
- * Requests from the Admin Console to delete/remove items
- *
- * @param request
- * @param response
- * @param groupId
- * @param loggingContext
- * @throws ServletException
- * @throws IOException
- */
- private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
- PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.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 + "'";
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
- return;
- }
- // determine the operation needed based on the parameters in the request
- if (request.getParameter("policy") != null) {
- // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
- loggingContext.setServiceName("AC:PAP.deletePolicy");
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
- return;
- } else if (request.getParameter("pdpId") != null) {
- // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
- String pdpId = request.getParameter("pdpId");
- OnapPDP pdp = papEngine.getPDP(pdpId);
- try{
- removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
- } catch(Exception e){
- throw new PAPException(e);
- }
- try{
- papEngine.removePDP((OnapPDP) pdp);
- }catch(PAPException e){
+ LOGGER.info("JSON request from AC: " + json);
+ // convert Object sent as JSON into local object
+ ObjectMapper mapper = new ObjectMapper();
+ Object objectFromJSON = null;
+ try {
+ objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
+ } catch(Exception e) {
+ LOGGER.error(e);
+ }
+ if (objectFromJSON == null || ! (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);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
+ }
+ // The Path on the PAP side is not carried on the RESTful interface with the AC
+ // (because it is local to the PAP)
+ // so we need to fill that in before submitting the group for update
+ if(objectFromJSON != null){
+ ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
+ }
+ try{
+ if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
+ acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
+ } else {
+ acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
+ }
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
+ +"group="+group.getId());
+ LOGGER.error(e);
+ throw new PAPException(e.getMessage());
+ }
+
+ PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
+ OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
+ if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
+ LOGGER.debug("Precheck Successful.");
+ }
+ try{
+ papEngine.updateGroup((StdPDPGroup)objectFromJSON);
+ }catch(PAPException e){
LOGGER.error(e);
}
- // adjust the status of the group, which may have changed when we removed this PDP
- ((StdPDPGroup)group).resetStatus();
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
- // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
- pdpChanged(pdp, loggingContext);
- loggingContext.metricStarted();
- removePdpOrGroupTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- 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");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
- return;
- } else {
- // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
- String moveToGroupId = request.getParameter("movePDPsToGroupId");
- OnapPDPGroup moveToGroup = null;
- if (moveToGroupId != null) {
- try{
- moveToGroup = papEngine.getGroup(moveToGroupId);
- }catch(PAPException e){
- LOGGER.error(e);
- }
- }
- // get list of PDPs in the group being deleted so we can notify them that they got changed
- Set<OnapPDP> movedPDPs = new HashSet<>();
- movedPDPs.addAll(group.getOnapPdps());
- // do the move/remove
- try{
- removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
- throw new PAPException(e.getMessage());
- }
- try{
- papEngine.removeGroup(group, moveToGroup);
- }catch(PAPException e){
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Group '" + group.getId() + "' updated");
+ }
+ loggingContext.metricStarted();
+ acPutTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ // tell the Admin Consoles there is a change
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
+ // Group changed, which might include changing the policies
+ groupChanged(group, loggingContext);
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ } catch (PAPException e) {
+ LOGGER.debug(e);
+ acPutTransaction.rollbackTransaction();
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+ return;
+ }
+ }
+
+ /**
+ * Requests from the Admin Console to delete/remove items
+ *
+ * @param request
+ * @param response
+ * @param groupId
+ * @param loggingContext
+ * @throws ServletException
+ * @throws IOException
+ */
+ private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
+ PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.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 + "'";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
+ return;
+ }
+ // determine the operation needed based on the parameters in the request
+ if (request.getParameter("policy") != null) {
+ // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
+ loggingContext.setServiceName("AC:PAP.deletePolicy");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ return;
+ } else if (request.getParameter("pdpId") != null) {
+ // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
+ String pdpId = request.getParameter("pdpId");
+ OnapPDP pdp = papEngine.getPDP(pdpId);
+ try{
+ removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
+ } catch(Exception e){
+ throw new PAPException(e);
+ }
+ try{
+ papEngine.removePDP((OnapPDP) pdp);
+ }catch(PAPException e){
LOGGER.error(e);
}
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);
- loggingContext.metricStarted();
- notifyAC();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
- // notify any PDPs in the removed set that their config may have changed
- for (OnapPDP pdp : movedPDPs) {
- pdpChanged(pdp, loggingContext);
- }
- loggingContext.metricStarted();
- removePdpOrGroupTransaction.commitTransaction();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
- loggingContext.transactionEnded();
- auditLogger.info("Success");
- PolicyLogger.audit("Transaction Ended Successfully");
- return;
- }
- } catch (PAPException e) {
- removePdpOrGroupTransaction.rollbackTransaction();
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
- }
- }
-
- /**
- * Heartbeat thread - periodically check on PDPs' status
- *
- * Heartbeat with all known PDPs.
- *
- * Implementation note:
- *
- * The PDPs are contacted Sequentially, not in Parallel.
- *
- * If we did this in parallel using multiple threads we would simultaneously use
- * - 1 thread and
- * - 1 connection
- * for EACH PDP.
- * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
- * when user changes occur.
- * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
- *
- * The Sequential operation does a heartbeat request to each PDP one at a time.
- * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
- * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
- * it could take a long time to cycle through all of the PDPs.
- * That means that this may not notice a PDP being down in a predictable time.
- */
- private class Heartbeat implements Runnable {
- private PAPPolicyEngine papEngine;
- private Set<OnapPDP> pdps = new HashSet<>();
- private int heartbeatInterval;
- private int heartbeatTimeout;
-
- public volatile boolean isRunning = false;
-
- public synchronized boolean isRunning() {
- return this.isRunning;
- }
-
- public synchronized void terminate() {
- this.isRunning = false;
- }
-
- public Heartbeat(PAPPolicyEngine papEngine2) {
- papEngine = papEngine2;
- this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
- this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
- }
-
- @Override
- public void run() {
- // Set ourselves as running
- synchronized(this) {
- this.isRunning = true;
- }
- HashMap<String, URL> idToURLMap = new HashMap<>();
- try {
- while (this.isRunning()) {
- // Wait the given time
- Thread.sleep(heartbeatInterval);
- // get the list of PDPs (may have changed since last time)
- pdps.clear();
- synchronized(papEngine) {
- try {
- for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
- for (OnapPDP p : g.getOnapPdps()) {
- pdps.add(p);
- }
- }
- } catch (PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
- }
- }
- // Check for shutdown
- if (this.isRunning() == false) {
- LOGGER.info("isRunning is false, getting out of loop.");
- break;
- }
- // try to get the summary status from each PDP
- boolean changeSeen = false;
- for (OnapPDP pdp : pdps) {
- // Check for shutdown
- if (this.isRunning() == false) {
- LOGGER.info("isRunning is false, getting out of loop.");
- break;
- }
- // the id of the PDP is its url (though we add a query parameter)
- URL pdpURL = idToURLMap.get(pdp.getId());
- if (pdpURL == null) {
- // haven't seen this PDP before
- String fullURLString = null;
- try {
- // Check PDP ID
- if(CheckPDP.validateID(pdp.getId())){
- fullURLString = pdp.getId() + "?type=hb";
- pdpURL = new URL(fullURLString);
- idToURLMap.put(pdp.getId(), pdpURL);
- }
- } catch (MalformedURLException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
- continue;
- }
- }
- // Do a GET with type HeartBeat
- String newStatus = "";
- HttpURLConnection connection = null;
- try {
- // Open up the connection
- if(pdpURL != null){
- connection = (HttpURLConnection)pdpURL.openConnection();
- // Setup our method and headers
- connection.setRequestMethod("GET");
- connection.setConnectTimeout(heartbeatTimeout);
- // Authentication
- String encoding = CheckPDP.getEncoding(pdp.getId());
- if(encoding !=null){
- connection.setRequestProperty("Authorization", "Basic " + encoding);
- }
- // Do the connect
- connection.connect();
- if (connection.getResponseCode() == 204) {
- newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
- }
- } else {
- // 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());
- }
- }
- } catch (UnknownHostException e) {
- newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
- } catch (SocketTimeoutException e) {
- newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
- } catch (ConnectException e) {
- newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
- } catch (Exception e) {
- newStatus = PDPStatus.Status.UNKNOWN.toString();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
- } finally {
- // cleanup the connection
- if(connection != null)
- connection.disconnect();
- }
- if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
- }
- try {
- setPDPSummaryStatus(pdp, newStatus);
- } catch (PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
- }
- changeSeen = true;
- }
- }
- // Check for shutdown
- if (this.isRunning() == false) {
- LOGGER.info("isRunning is false, getting out of loop.");
- break;
- }
- // if any of the PDPs changed state, tell the ACs to update
- if (changeSeen) {
- notifyAC();
- }
- }
- } catch (InterruptedException e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
- this.terminate();
- Thread.currentThread().interrupt();
- }
- }
- }
-
- /*
- * HELPER to change Group status when PDP status is changed
- * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
- */
- private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
- setPDPSummaryStatus(pdp, newStatus.toString());
- }
-
- private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
- synchronized(papEngine) {
- StdPDPStatus status = new StdPDPStatus();
- status.setStatus(PDPStatus.Status.valueOf(newStatus));
- ((StdPDP)pdp).setStatus(status);
- // now adjust the group
- StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
- // if the PDP was just deleted it may transiently exist but not be in a group
- if (group != null) {
- group.resetStatus();
- }
- }
- }
-
- /*
- * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
- * in the PDP group directories
- */
- @Override
- public void changed() {
- // all PDPs in all groups need to be updated/sync'd
- Set<OnapPDPGroup> groups;
- 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);
- }
- for (OnapPDPGroup group : groups) {
- groupChanged(group);
- }
- }
-
- public void changed(ONAPLoggingContext loggingContext) {
- // all PDPs in all groups need to be updated/sync'd
- Set<OnapPDPGroup> groups;
- 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);
- }
- for (OnapPDPGroup group : groups) {
- groupChanged(group, loggingContext);
- }
- }
-
- @Override
- public void groupChanged(OnapPDPGroup group) {
- // all PDPs within one group need to be updated/sync'd
- for (OnapPDP pdp : group.getOnapPdps()) {
- pdpChanged(pdp);
- }
- }
-
- public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
- // all PDPs within one group need to be updated/sync'd
- for (OnapPDP pdp : group.getOnapPdps()) {
- pdpChanged(pdp, loggingContext);
- }
- }
-
- @Override
- public void pdpChanged(OnapPDP pdp) {
- // kick off a thread to do an event notification for each PDP.
- // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
- // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
- Thread t = new Thread(new UpdatePDPThread(pdp));
- if(CheckPDP.validateID(pdp.getId())){
- t.start();
- }
- }
-
- public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
- // kick off a thread to do an event notification for each PDP.
- // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
- // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
- Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
- if(CheckPDP.validateID(pdp.getId())){
- t.start();
- }
- }
-
- private class UpdatePDPThread implements Runnable {
- private OnapPDP pdp;
- private String requestId;
- private ONAPLoggingContext loggingContext;
-
- public UpdatePDPThread(OnapPDP pdp) {
- this.pdp = pdp;
- }
-
- public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
- this.pdp = pdp;
- if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
- this.requestId = loggingContext.getRequestID();
- }
- this.loggingContext = loggingContext;
- }
-
- public void run() {
- // send the current configuration to one PDP
- HttpURLConnection connection = null;
- // get a new logging context for the thread
- try {
- if (this.loggingContext == null) {
- loggingContext = new ONAPLoggingContext(baseLoggingContext);
- }
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
- // Since this is a server-side error, it probably does not reflect a problem on the client,
- // so do not change the PDP status.
- return;
- }
- try {
- loggingContext.setServiceName("PAP:PDP.putConfig");
- // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
- if ((requestId == null) || (requestId == "")) {
- UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
- PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
- } else {
- loggingContext.setRequestID(requestId);
- PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
- }
- loggingContext.transactionStarted();
- // the Id of the PDP is its URL
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("creating url for id '" + pdp.getId() + "'");
- }
- //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
- //TODO (need to change "cache=", implying getting some input saying which to change)
- URL url = new URL(pdp.getId() + "?cache=all");
- // Open up the connection
- connection = (HttpURLConnection)url.openConnection();
- // Setup our method and headers
- connection.setRequestMethod("PUT");
- // Authentication
- String encoding = CheckPDP.getEncoding(pdp.getId());
- if(encoding !=null){
- connection.setRequestProperty("Authorization", "Basic " + encoding);
- }
- connection.setRequestProperty("Content-Type", "text/x-java-properties");
- connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
- connection.setInstanceFollowRedirects(true);
- connection.setDoOutput(true);
- try (OutputStream os = connection.getOutputStream()) {
- OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
- // if the PDP was just deleted, there is no group, but we want to send an update anyway
- if (group == null) {
- // create blank properties files
- Properties policyProperties = new Properties();
- policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
- policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
- policyProperties.store(os, "");
- Properties pipProps = new Properties();
- pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
- pipProps.store(os, "");
- } else {
- // send properties from the current group
- group.getPolicyProperties().store(os, "");
- Properties policyLocations = new Properties();
- for (PDPPolicy policy : group.getPolicies()) {
- policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
- }
- policyLocations.store(os, "");
- group.getPipConfigProperties().store(os, "");
- }
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
- // Since this is a server-side error, it probably does not reflect a problem on the client,
- // so do not change the PDP status.
- return;
- }
- // Do the connect
- loggingContext.metricStarted();
- connection.connect();
- loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
- if (connection.getResponseCode() == 204) {
- LOGGER.info("Success. We are configured correctly.");
- loggingContext.transactionEnded();
- auditLogger.info("Success. PDP is configured correctly.");
- PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
- setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
- } else if (connection.getResponseCode() == 200) {
- LOGGER.info("Success. PDP needs to update its configuration.");
- loggingContext.transactionEnded();
- auditLogger.info("Success. PDP needs to update its configuration.");
- PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
- setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
- } else {
- LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- loggingContext.transactionEnded();
- auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
- }
- } catch (Exception e) {
- LOGGER.debug(e);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
- try {
- setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
- } catch (PAPException e1) {
- LOGGER.debug(e1);
- PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
- }
- } finally {
- // cleanup the connection
- if(connection != null){
- connection.disconnect();
- }
- // tell the AC to update it's status info
- notifyAC();
- }
- }
- }
-
- /*
- * RESTful Interface from PAP to ACs notifying them of changes
- */
- private void notifyAC() {
- // kick off a thread to do one event notification for all registered ACs
- // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
- // as part of processing this message on their end.
- Thread t = new Thread(new NotifyACThread());
- t.start();
- }
-
- private class NotifyACThread implements Runnable {
- public void run() {
- List<String> disconnectedACs = new ArrayList<>();
- // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
- // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
- for (String acURL : adminConsoleURLStringList) {
- HttpURLConnection connection = null;
- try {
- acURL += "?PAPNotification=true";
- //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
- //TODO - If so, put correct parameters into the Query string here
- acURL += "&objectType=all" + "&action=update";
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("creating url for id '" + acURL + "'");
- }
- //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
- //TODO (need to change "cache=", implying getting some input saying which to change)
- URL url = new URL(acURL );
- // Open up the connection
- connection = (HttpURLConnection)url.openConnection();
- // Setup our method and headers
- connection.setRequestMethod("PUT");
- connection.setRequestProperty("Content-Type", "text/x-java-properties");
- // Adding this in. It seems the HttpUrlConnection class does NOT
- // properly forward our headers for POST re-direction. It does so
- // for a GET re-direction.
- // So we need to handle this ourselves.
- //TODO - is this needed for a PUT? seems better to leave in for now?
- connection.setInstanceFollowRedirects(false);
- // Do not include any data in the PUT because this is just a
- // notification to the AC.
- // The AC will use GETs back to the PAP to get what it needs
- // to fill in the screens.
- // Do the connect
- connection.connect();
- if (connection.getResponseCode() == 204) {
- LOGGER.info("Success. We updated correctly.");
- } else {
- LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- }
-
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
- disconnectedACs.add(acURL);
- } finally {
- // cleanup the connection
- if(connection != null)
- connection.disconnect();
- }
- }
- // remove any ACs that are no longer connected
- if (!disconnectedACs.isEmpty()) {
- adminConsoleURLStringList.removeAll(disconnectedACs);
- }
- }
- }
-
- private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
- LOGGER.info("Test request received");
- try {
- im.evaluateSanity();
- //If we make it this far, all is well
- String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
- LOGGER.info(message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- response.setStatus(HttpServletResponse.SC_OK);
- return;
- }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
- String submsg;
- if (e instanceof ForwardProgressException) {
- submsg = " is not making forward progress.";
- } else if (e instanceof AdministrativeStateException) {
- submsg = " Administrative State is LOCKED.";
- } else {
- submsg = " Standby Status is NOT PROVIDING SERVICE.";
- }
-
- 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();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }catch (Exception e) {
- //A subsystem is not making progress, is locked, standby or is not responding
- String eMsg = e.getMessage();
- if(eMsg == null){
- eMsg = "No Exception Message";
- }
- 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();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- //Get the specific list of subsystems that failed
- String ssFailureList = null;
- for(String failedSS : papDependencyGroupsFlatArray){
- if(eMsg.contains(failedSS)){
- if(ssFailureList == null){
- ssFailureList = failedSS;
- }else{
- ssFailureList = ssFailureList.concat(","+failedSS);
- }
- }
- }
- if(ssFailureList == null){
- ssFailureList = "UnknownSubSystem";
- }
- response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
- return;
- }
- }
-
- /*
- * Authorizing the PEP Requests.
- */
- private boolean authorizeRequest(HttpServletRequest request) {
- String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
- // Check if the Client is Authorized.
- if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
- return true;
- }else{
- return false;
- }
- }
-
- private static void loadWebapps() throws PAPException{
- if(actionHome == null || configHome == null){
- 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);
- }
- Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
- Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
- if (Files.notExists(webappsPathConfig)) {
- try {
- Files.createDirectories(webappsPathConfig);
- } catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "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);
- }
- }
- actionHome = webappsPathAction.toString();
- configHome = webappsPathConfig.toString();
- }
- }
-
- public static String getConfigHome(){
- try {
- loadWebapps();
- } catch (PAPException e) {
- LOGGER.debug(e);
- return null;
- }
- return configHome;
- }
-
- private static void setConfigHome(){
- configHome = getConfigHome();
- }
-
- public static String getActionHome(){
- try {
- loadWebapps();
- } catch (PAPException e) {
- LOGGER.debug(e);
- return null;
- }
- return actionHome;
- }
-
- private static void setActionHome(){
- actionHome = getActionHome();
- }
-
- public static EntityManagerFactory getEmf() {
- return emf;
- }
-
- public IntegrityAudit getIa() {
- return ia;
- }
-
- public static String getPDPFile(){
- return XACMLPapServlet.pdpFile;
- }
-
- public static String getPersistenceUnit(){
- return PERSISTENCE_UNIT;
- }
-
- public static PAPPolicyEngine getPAPEngine(){
- return papEngine;
- }
-
- public static PolicyDBDaoTransaction getDbDaoTransaction(){
- return policyDBDao.getNewTransaction();
- }
- public static String getPapDbDriver() {
- return papDbDriver;
- }
-
- public static void setPapDbDriver(String papDbDriver) {
- XACMLPapServlet.papDbDriver = papDbDriver;
- }
-
- public static String getPapDbUrl() {
- return papDbUrl;
- }
-
- public static void setPapDbUrl(String papDbUrl) {
- XACMLPapServlet.papDbUrl = papDbUrl;
- }
-
- public static String getPapDbUser() {
- return papDbUser;
- }
-
- public static void setPapDbUser(String papDbUser) {
- XACMLPapServlet.papDbUser = papDbUser;
- }
-
- public static String getPapDbPassword() {
- return papDbPassword;
- }
-
- public static void setPapDbPassword(String papDbPassword) {
- XACMLPapServlet.papDbPassword = papDbPassword;
- }
-
- public static String getMsOnapName() {
- return msOnapName;
- }
-
- public static void setMsOnapName(String msOnapName) {
- XACMLPapServlet.msOnapName = msOnapName;
- }
-
- public static String getMsPolicyName() {
- return msPolicyName;
- }
-
- public static void setMsPolicyName(String msPolicyName) {
- XACMLPapServlet.msPolicyName = msPolicyName;
- }
+ // adjust the status of the group, which may have changed when we removed this PDP
+ ((StdPDPGroup)group).resetStatus();
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
+ // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
+ pdpChanged(pdp, loggingContext);
+ loggingContext.metricStarted();
+ removePdpOrGroupTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ 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");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ return;
+ } else {
+ // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
+ String moveToGroupId = request.getParameter("movePDPsToGroupId");
+ OnapPDPGroup moveToGroup = null;
+ if (moveToGroupId != null) {
+ try{
+ moveToGroup = papEngine.getGroup(moveToGroupId);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ }
+ // get list of PDPs in the group being deleted so we can notify them that they got changed
+ Set<OnapPDP> movedPDPs = new HashSet<>();
+ movedPDPs.addAll(group.getOnapPdps());
+ // do the move/remove
+ try{
+ removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
+ throw new PAPException(e.getMessage());
+ }
+ try{
+ papEngine.removeGroup(group, moveToGroup);
+ }catch(PAPException e){
+ LOGGER.error(e);
+ }
+ response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+ loggingContext.metricStarted();
+ notifyAC();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
+ // notify any PDPs in the removed set that their config may have changed
+ for (OnapPDP pdp : movedPDPs) {
+ pdpChanged(pdp, loggingContext);
+ }
+ loggingContext.metricStarted();
+ removePdpOrGroupTransaction.commitTransaction();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success");
+ PolicyLogger.audit("Transaction Ended Successfully");
+ return;
+ }
+ } catch (PAPException e) {
+ removePdpOrGroupTransaction.rollbackTransaction();
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+ return;
+ }
+ }
+
+ /**
+ * Heartbeat thread - periodically check on PDPs' status
+ *
+ * Heartbeat with all known PDPs.
+ *
+ * Implementation note:
+ *
+ * The PDPs are contacted Sequentially, not in Parallel.
+ *
+ * If we did this in parallel using multiple threads we would simultaneously use
+ * - 1 thread and
+ * - 1 connection
+ * for EACH PDP.
+ * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
+ * when user changes occur.
+ * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
+ *
+ * The Sequential operation does a heartbeat request to each PDP one at a time.
+ * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
+ * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
+ * it could take a long time to cycle through all of the PDPs.
+ * That means that this may not notice a PDP being down in a predictable time.
+ */
+ private class Heartbeat implements Runnable {
+ private PAPPolicyEngine papEngine;
+ private Set<OnapPDP> pdps = new HashSet<>();
+ private int heartbeatInterval;
+ private int heartbeatTimeout;
+
+ public volatile boolean isRunning = false;
+
+ public synchronized boolean isRunning() {
+ return this.isRunning;
+ }
+
+ public synchronized void terminate() {
+ this.isRunning = false;
+ }
+
+ public Heartbeat(PAPPolicyEngine papEngine2) {
+ papEngine = papEngine2;
+ this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
+ this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
+ }
+
+ @Override
+ public void run() {
+ // Set ourselves as running
+ synchronized(this) {
+ this.isRunning = true;
+ }
+ HashMap<String, URL> idToURLMap = new HashMap<>();
+ try {
+ while (this.isRunning()) {
+ // Wait the given time
+ Thread.sleep(heartbeatInterval);
+ // get the list of PDPs (may have changed since last time)
+ pdps.clear();
+ synchronized(papEngine) {
+ try {
+ for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
+ for (OnapPDP p : g.getOnapPdps()) {
+ pdps.add(p);
+ }
+ }
+ } catch (PAPException e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
+ }
+ }
+ // Check for shutdown
+ if (this.isRunning() == false) {
+ LOGGER.info("isRunning is false, getting out of loop.");
+ break;
+ }
+ // try to get the summary status from each PDP
+ boolean changeSeen = false;
+ for (OnapPDP pdp : pdps) {
+ // Check for shutdown
+ if (this.isRunning() == false) {
+ LOGGER.info("isRunning is false, getting out of loop.");
+ break;
+ }
+ // the id of the PDP is its url (though we add a query parameter)
+ URL pdpURL = idToURLMap.get(pdp.getId());
+ if (pdpURL == null) {
+ // haven't seen this PDP before
+ String fullURLString = null;
+ try {
+ // Check PDP ID
+ if(CheckPDP.validateID(pdp.getId())){
+ fullURLString = pdp.getId() + "?type=hb";
+ pdpURL = new URL(fullURLString);
+ idToURLMap.put(pdp.getId(), pdpURL);
+ }
+ } catch (MalformedURLException e) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
+ continue;
+ }
+ }
+ // Do a GET with type HeartBeat
+ String newStatus = "";
+ HttpURLConnection connection = null;
+ try {
+ // Open up the connection
+ if(pdpURL != null){
+ connection = (HttpURLConnection)pdpURL.openConnection();
+ // Setup our method and headers
+ connection.setRequestMethod("GET");
+ connection.setConnectTimeout(heartbeatTimeout);
+ // Authentication
+ String encoding = CheckPDP.getEncoding(pdp.getId());
+ if(encoding !=null){
+ connection.setRequestProperty("Authorization", "Basic " + encoding);
+ }
+ // Do the connect
+ connection.connect();
+ if (connection.getResponseCode() == 204) {
+ newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
+ }
+ } else {
+ // 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());
+ }
+ }
+ } catch (UnknownHostException e) {
+ newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
+ } catch (SocketTimeoutException e) {
+ newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
+ } catch (ConnectException e) {
+ newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
+ } catch (Exception e) {
+ newStatus = PDPStatus.Status.UNKNOWN.toString();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
+ } finally {
+ // cleanup the connection
+ if(connection != null)
+ connection.disconnect();
+ }
+ if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
+ }
+ try {
+ setPDPSummaryStatus(pdp, newStatus);
+ } catch (PAPException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
+ }
+ changeSeen = true;
+ }
+ }
+ // Check for shutdown
+ if (this.isRunning() == false) {
+ LOGGER.info("isRunning is false, getting out of loop.");
+ break;
+ }
+ // if any of the PDPs changed state, tell the ACs to update
+ if (changeSeen) {
+ notifyAC();
+ }
+ }
+ } catch (InterruptedException e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
+ this.terminate();
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ /*
+ * HELPER to change Group status when PDP status is changed
+ * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
+ */
+ private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
+ setPDPSummaryStatus(pdp, newStatus.toString());
+ }
+
+ private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
+ synchronized(papEngine) {
+ StdPDPStatus status = new StdPDPStatus();
+ status.setStatus(PDPStatus.Status.valueOf(newStatus));
+ ((StdPDP)pdp).setStatus(status);
+ // now adjust the group
+ StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
+ // if the PDP was just deleted it may transiently exist but not be in a group
+ if (group != null) {
+ group.resetStatus();
+ }
+ }
+ }
+
+ /*
+ * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
+ * in the PDP group directories
+ */
+ @Override
+ public void changed() {
+ // all PDPs in all groups need to be updated/sync'd
+ Set<OnapPDPGroup> groups;
+ 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);
+ }
+ for (OnapPDPGroup group : groups) {
+ groupChanged(group);
+ }
+ }
+
+ public void changed(ONAPLoggingContext loggingContext) {
+ // all PDPs in all groups need to be updated/sync'd
+ Set<OnapPDPGroup> groups;
+ 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);
+ }
+ for (OnapPDPGroup group : groups) {
+ groupChanged(group, loggingContext);
+ }
+ }
+
+ @Override
+ public void groupChanged(OnapPDPGroup group) {
+ // all PDPs within one group need to be updated/sync'd
+ for (OnapPDP pdp : group.getOnapPdps()) {
+ pdpChanged(pdp);
+ }
+ }
+
+ public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
+ // all PDPs within one group need to be updated/sync'd
+ for (OnapPDP pdp : group.getOnapPdps()) {
+ pdpChanged(pdp, loggingContext);
+ }
+ }
+
+ @Override
+ public void pdpChanged(OnapPDP pdp) {
+ // kick off a thread to do an event notification for each PDP.
+ // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
+ // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
+ Thread t = new Thread(new UpdatePDPThread(pdp));
+ if(CheckPDP.validateID(pdp.getId())){
+ t.start();
+ }
+ }
+
+ public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
+ // kick off a thread to do an event notification for each PDP.
+ // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
+ // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
+ Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
+ if(CheckPDP.validateID(pdp.getId())){
+ t.start();
+ }
+ }
+
+ private class UpdatePDPThread implements Runnable {
+ private OnapPDP pdp;
+ private String requestId;
+ private ONAPLoggingContext loggingContext;
+
+ public UpdatePDPThread(OnapPDP pdp) {
+ this.pdp = pdp;
+ }
+
+ public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
+ this.pdp = pdp;
+ if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
+ this.requestId = loggingContext.getRequestID();
+ }
+ this.loggingContext = loggingContext;
+ }
+
+ public void run() {
+ // send the current configuration to one PDP
+ HttpURLConnection connection = null;
+ // get a new logging context for the thread
+ try {
+ if (this.loggingContext == null) {
+ loggingContext = new ONAPLoggingContext(baseLoggingContext);
+ }
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
+ // Since this is a server-side error, it probably does not reflect a problem on the client,
+ // so do not change the PDP status.
+ return;
+ }
+ try {
+ loggingContext.setServiceName("PAP:PDP.putConfig");
+ // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
+ if ((requestId == null) || (requestId == "")) {
+ UUID requestID = UUID.randomUUID();
+ loggingContext.setRequestID(requestID.toString());
+ PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
+ } else {
+ loggingContext.setRequestID(requestId);
+ PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
+ }
+ loggingContext.transactionStarted();
+ // the Id of the PDP is its URL
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("creating url for id '" + pdp.getId() + "'");
+ }
+ //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
+ //TODO (need to change "cache=", implying getting some input saying which to change)
+ URL url = new URL(pdp.getId() + "?cache=all");
+ // Open up the connection
+ connection = (HttpURLConnection)url.openConnection();
+ // Setup our method and headers
+ connection.setRequestMethod("PUT");
+ // Authentication
+ String encoding = CheckPDP.getEncoding(pdp.getId());
+ if(encoding !=null){
+ connection.setRequestProperty("Authorization", "Basic " + encoding);
+ }
+ connection.setRequestProperty("Content-Type", "text/x-java-properties");
+ connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
+ connection.setInstanceFollowRedirects(true);
+ connection.setDoOutput(true);
+ try (OutputStream os = connection.getOutputStream()) {
+ OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
+ // if the PDP was just deleted, there is no group, but we want to send an update anyway
+ if (group == null) {
+ // create blank properties files
+ Properties policyProperties = new Properties();
+ policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
+ policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
+ policyProperties.store(os, "");
+ Properties pipProps = new Properties();
+ pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
+ pipProps.store(os, "");
+ } else {
+ // send properties from the current group
+ group.getPolicyProperties().store(os, "");
+ Properties policyLocations = new Properties();
+ for (PDPPolicy policy : group.getPolicies()) {
+ policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
+ }
+ policyLocations.store(os, "");
+ group.getPipConfigProperties().store(os, "");
+ }
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
+ // Since this is a server-side error, it probably does not reflect a problem on the client,
+ // so do not change the PDP status.
+ return;
+ }
+ // Do the connect
+ loggingContext.metricStarted();
+ connection.connect();
+ loggingContext.metricEnded();
+ PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
+ if (connection.getResponseCode() == 204) {
+ LOGGER.info("Success. We are configured correctly.");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success. PDP is configured correctly.");
+ PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
+ setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
+ } else if (connection.getResponseCode() == 200) {
+ LOGGER.info("Success. PDP needs to update its configuration.");
+ loggingContext.transactionEnded();
+ auditLogger.info("Success. PDP needs to update its configuration.");
+ PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
+ setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
+ } else {
+ LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
+ loggingContext.transactionEnded();
+ auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
+ PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
+ setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
+ }
+ } catch (Exception e) {
+ LOGGER.debug(e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
+ try {
+ setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
+ } catch (PAPException e1) {
+ LOGGER.debug(e1);
+ PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
+ }
+ } finally {
+ // cleanup the connection
+ if(connection != null){
+ connection.disconnect();
+ }
+ // tell the AC to update it's status info
+ notifyAC();
+ }
+ }
+ }
+
+ /*
+ * RESTful Interface from PAP to ACs notifying them of changes
+ */
+ private void notifyAC() {
+ // kick off a thread to do one event notification for all registered ACs
+ // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
+ // as part of processing this message on their end.
+ Thread t = new Thread(new NotifyACThread());
+ t.start();
+ }
+
+ private class NotifyACThread implements Runnable {
+ public void run() {
+ List<String> disconnectedACs = new ArrayList<>();
+ // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
+ // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
+ for (String acURL : adminConsoleURLStringList) {
+ HttpURLConnection connection = null;
+ try {
+ acURL += "?PAPNotification=true";
+ //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
+ //TODO - If so, put correct parameters into the Query string here
+ acURL += "&objectType=all" + "&action=update";
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("creating url for id '" + acURL + "'");
+ }
+ //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
+ //TODO (need to change "cache=", implying getting some input saying which to change)
+ URL url = new URL(acURL );
+ // Open up the connection
+ connection = (HttpURLConnection)url.openConnection();
+ // Setup our method and headers
+ connection.setRequestMethod("PUT");
+ connection.setRequestProperty("Content-Type", "text/x-java-properties");
+ // Adding this in. It seems the HttpUrlConnection class does NOT
+ // properly forward our headers for POST re-direction. It does so
+ // for a GET re-direction.
+ // So we need to handle this ourselves.
+ //TODO - is this needed for a PUT? seems better to leave in for now?
+ connection.setInstanceFollowRedirects(false);
+ // Do not include any data in the PUT because this is just a
+ // notification to the AC.
+ // The AC will use GETs back to the PAP to get what it needs
+ // to fill in the screens.
+ // Do the connect
+ connection.connect();
+ if (connection.getResponseCode() == 204) {
+ LOGGER.info("Success. We updated correctly.");
+ } else {
+ LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
+ }
+
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
+ disconnectedACs.add(acURL);
+ } finally {
+ // cleanup the connection
+ if(connection != null)
+ connection.disconnect();
+ }
+ }
+ // remove any ACs that are no longer connected
+ if (!disconnectedACs.isEmpty()) {
+ adminConsoleURLStringList.removeAll(disconnectedACs);
+ }
+ }
+ }
+
+ private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
+ LOGGER.info("Test request received");
+ try {
+ im.evaluateSanity();
+ //If we make it this far, all is well
+ String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
+ LOGGER.info(message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ response.setStatus(HttpServletResponse.SC_OK);
+ return;
+ }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
+ String submsg;
+ if (e instanceof ForwardProgressException) {
+ submsg = " is not making forward progress.";
+ } else if (e instanceof AdministrativeStateException) {
+ submsg = " Administrative State is LOCKED.";
+ } else {
+ submsg = " Standby Status is NOT PROVIDING SERVICE.";
+ }
+
+ 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();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }catch (Exception e) {
+ //A subsystem is not making progress, is locked, standby or is not responding
+ String eMsg = e.getMessage();
+ if(eMsg == null){
+ eMsg = "No Exception Message";
+ }
+ 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();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ //Get the specific list of subsystems that failed
+ String ssFailureList = null;
+ for(String failedSS : papDependencyGroupsFlatArray){
+ if(eMsg.contains(failedSS)){
+ if(ssFailureList == null){
+ ssFailureList = failedSS;
+ }else{
+ ssFailureList = ssFailureList.concat(","+failedSS);
+ }
+ }
+ }
+ if(ssFailureList == null){
+ ssFailureList = "UnknownSubSystem";
+ }
+ response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+ return;
+ }
+ }
+
+ /*
+ * Authorizing the PEP Requests.
+ */
+ private boolean authorizeRequest(HttpServletRequest request) {
+ String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
+ // Check if the Client is Authorized.
+ if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+ private static void loadWebapps() throws PAPException{
+ if(actionHome == null || configHome == null){
+ 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);
+ }
+ Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
+ Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
+ if (Files.notExists(webappsPathConfig)) {
+ try {
+ Files.createDirectories(webappsPathConfig);
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "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);
+ }
+ }
+ actionHome = webappsPathAction.toString();
+ configHome = webappsPathConfig.toString();
+ }
+ }
+
+ public static String getConfigHome(){
+ try {
+ loadWebapps();
+ } catch (PAPException e) {
+ LOGGER.debug(e);
+ return null;
+ }
+ return configHome;
+ }
+
+ private static void setConfigHome(){
+ configHome = getConfigHome();
+ }
+
+ public static String getActionHome(){
+ try {
+ loadWebapps();
+ } catch (PAPException e) {
+ LOGGER.debug(e);
+ return null;
+ }
+ return actionHome;
+ }
+
+ private static void setActionHome(){
+ actionHome = getActionHome();
+ }
+
+ public static EntityManagerFactory getEmf() {
+ return emf;
+ }
+
+ public IntegrityAudit getIa() {
+ return ia;
+ }
+
+ public static String getPDPFile(){
+ return XACMLPapServlet.pdpFile;
+ }
+
+ public static String getPersistenceUnit(){
+ return PERSISTENCE_UNIT;
+ }
+
+ public static PAPPolicyEngine getPAPEngine(){
+ return papEngine;
+ }
+
+ public static PolicyDBDaoTransaction getDbDaoTransaction(){
+ return policyDBDao.getNewTransaction();
+ }
+ public static String getPapDbDriver() {
+ return papDbDriver;
+ }
+
+ public static void setPapDbDriver(String papDbDriver) {
+ XACMLPapServlet.papDbDriver = papDbDriver;
+ }
+
+ public static String getPapDbUrl() {
+ return papDbUrl;
+ }
+
+ public static void setPapDbUrl(String papDbUrl) {
+ XACMLPapServlet.papDbUrl = papDbUrl;
+ }
+
+ public static String getPapDbUser() {
+ return papDbUser;
+ }
+
+ public static void setPapDbUser(String papDbUser) {
+ XACMLPapServlet.papDbUser = papDbUser;
+ }
+
+ public static String getPapDbPassword() {
+ return papDbPassword;
+ }
+
+ public static void setPapDbPassword(String papDbPassword) {
+ XACMLPapServlet.papDbPassword = papDbPassword;
+ }
+
+ public static String getMsOnapName() {
+ return msOnapName;
+ }
+
+ public static void setMsOnapName(String msOnapName) {
+ XACMLPapServlet.msOnapName = msOnapName;
+ }
+
+ public static String getMsPolicyName() {
+ return msPolicyName;
+ }
+
+ public static void setMsPolicyName(String msPolicyName) {
+ XACMLPapServlet.msPolicyName = msPolicyName;
+ }
} \ No newline at end of file
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 c8b8c6a05..e5b6915bd 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
@@ -51,410 +51,410 @@ import org.springframework.stereotype.Service;
@Primary
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;
- }
-
- public CommonClassDaoImpl(){
- //Default Constructor
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<Object> getData(Class className) {
- Session session = sessionFactory.openSession();
- List<Object> data = null;
- try{
- Criteria cr = session.createCriteria(className);
- data = cr.list();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);
- }finally{
- try{
- session.close();
- }catch(Exception 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) {
- Session session = sessionFactory.openSession();
- List<Object> data = null;
- try {
- Criteria cr = session.createCriteria(className);
- if(columnName.contains(":") && key.contains(":")){
- String[] columns = columnName.split(":");
- String[] keys = key.split(":");
- for(int i=0; i < columns.length; i++){
- cr.add(Restrictions.eq(columns[i], keys[i]));
- }
- }else{
- cr.add(Restrictions.eq(columnName, key));
- }
- data = cr.list();
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);
- }finally{
- try{
- session.close();
- }catch(Exception e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return data;
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<String> getDataByColumn(Class className, String columnName) {
- Session session = sessionFactory.openSession();
- List<String> data = null;
- try{
- Criteria cr = session.createCriteria(className);
- cr.setProjection(Projections.property(columnName));
- data = cr.list();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);
- }finally{
- try{
- session.close();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
- }
- }
- return data;
- }
-
- @Override
- public void save(Object entity) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- session.persist(entity);
- tx.commit();
- }catch(Exception 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);
- }
- }
-
- }
-
- @Override
- public void delete(Object entity) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- session.delete(entity);
- tx.commit();
- }catch(Exception 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);
- }
- }
-
- }
-
-
- @Override
- public void update(Object entity) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- session.update(entity);
- tx.commit();
- }catch(Exception 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);
- }
- }
-
- }
-
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> data = null;
-
- String[] columnNames = null;
- if(columnName != null && columnName.contains(":")){
- columnNames = columnName.split(":");
- }
- String[] values = null;
- if(value != null && value.contains(":")){
- values = value.split(":");
- }
- try {
- Criteria cr = session.createCriteria(className);
- if(columnNames != null && values != null && columnNames.length == values.length){
- for (int i = 0; i < columnNames.length; i++){
- cr.add(Restrictions.eq(columnNames[i],values[i]));
- }
- }else{
- cr.add(Restrictions.eq(columnName,value));
- }
-
- data = cr.list();
- tx.commit();
- } catch (Exception e) {
- 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);
- }
- }
- return data;
- }
-
-
- @SuppressWarnings("unchecked")
- @Override
- public List<Object> getDataByQuery(String query, SimpleBindings params) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> data = null;
- try {
- Query hbquery = session.createQuery(query);
- for (Map.Entry<String, Object> paramPair : params.entrySet()) {
- if(paramPair.getValue() instanceof java.lang.Long){
- hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
- }
- else{
- hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
- }
- }
- data = hbquery.list();
- tx.commit();
- } catch (Exception 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);
- }
- }
- return data;
- }
-
-
- @Override
- public void updateQuery(String query) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- Query hbquery = session.createQuery(query);
- hbquery.executeUpdate();
- tx.commit();
- } catch (Exception 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);
- }
- }
- }
-
-
- @SuppressWarnings("rawtypes")
- @Override
- public Object getEntityItem(Class className, String columnName, String key) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- Object data = null;
- try {
- Criteria cr = session.createCriteria(className);
- if(columnName.contains(":") && key.contains(":")){
- String[] columns = columnName.split(":");
- String[] keys = key.split(":");
- for(int i=0; i < columns.length; i++){
- cr.add(Restrictions.eq(columns[i], keys[i]));
- }
- }else{
- cr.add(Restrictions.eq(columnName, key));
- }
- data = cr.list().get(0);
- tx.commit();
- } catch (Exception 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);
- }
- }
- return data;
- }
-
-
- @SuppressWarnings("unchecked")
- @Override
- public List<PolicyRoles> getUserRoles() {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- List<PolicyRoles> rolesData = null;
- try {
- Criteria cr = session.createCriteria(PolicyRoles.class);
- Disjunction disjunction = Restrictions.disjunction();
- Conjunction conjunction1 = Restrictions.conjunction();
- conjunction1.add(Restrictions.eq("role", "admin"));
- Conjunction conjunction2 = Restrictions.conjunction();
- conjunction2.add(Restrictions.eq("role", "editor"));
- Conjunction conjunction3 = Restrictions.conjunction();
- conjunction3.add(Restrictions.eq("role", "guest"));
- disjunction.add(conjunction1);
- disjunction.add(conjunction2);
- disjunction.add(conjunction3);
- rolesData = cr.add(disjunction).list();
- tx.commit();
- } catch (Exception 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);
- }
- }
- return rolesData;
- }
-
-
- @SuppressWarnings("unchecked")
- @Override
- public void updateClAlarms(String clName, String alarms) {
- Session session = sessionFactory.openSession();
- List<ClosedLoops> closedloopsdata = null;
- Transaction tx = session.beginTransaction();
- try {
- Criteria cr = session.createCriteria(ClosedLoops.class);
- cr.add(Restrictions.eq("closedLoopControlName",clName));
+ private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class);
+
+
+ private static SessionFactory sessionFactory;
+
+
+ @Autowired
+ private CommonClassDaoImpl(SessionFactory sessionFactory){
+ CommonClassDaoImpl.sessionFactory = sessionFactory;
+ }
+
+ public CommonClassDaoImpl(){
+ //Default Constructor
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public List<Object> getData(Class className) {
+ Session session = sessionFactory.openSession();
+ List<Object> data = null;
+ try{
+ Criteria cr = session.createCriteria(className);
+ data = cr.list();
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);
+ }finally{
+ try{
+ session.close();
+ }catch(Exception 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) {
+ Session session = sessionFactory.openSession();
+ List<Object> data = null;
+ try {
+ Criteria cr = session.createCriteria(className);
+ if(columnName.contains(":") && key.contains(":")){
+ String[] columns = columnName.split(":");
+ String[] keys = key.split(":");
+ for(int i=0; i < columns.length; i++){
+ cr.add(Restrictions.eq(columns[i], keys[i]));
+ }
+ }else{
+ cr.add(Restrictions.eq(columnName, key));
+ }
+ data = cr.list();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);
+ }finally{
+ try{
+ session.close();
+ }catch(Exception e1){
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+ }
+ }
+ return data;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public List<String> getDataByColumn(Class className, String columnName) {
+ Session session = sessionFactory.openSession();
+ List<String> data = null;
+ try{
+ Criteria cr = session.createCriteria(className);
+ cr.setProjection(Projections.property(columnName));
+ data = cr.list();
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);
+ }finally{
+ try{
+ session.close();
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
+ }
+ }
+ return data;
+ }
+
+ @Override
+ public void save(Object entity) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ session.persist(entity);
+ tx.commit();
+ }catch(Exception 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);
+ }
+ }
+
+ }
+
+ @Override
+ public void delete(Object entity) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ session.delete(entity);
+ tx.commit();
+ }catch(Exception 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);
+ }
+ }
+
+ }
+
+
+ @Override
+ public void update(Object entity) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ session.update(entity);
+ tx.commit();
+ }catch(Exception 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);
+ }
+ }
+
+ }
+
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> data = null;
+
+ String[] columnNames = null;
+ if(columnName != null && columnName.contains(":")){
+ columnNames = columnName.split(":");
+ }
+ String[] values = null;
+ if(value != null && value.contains(":")){
+ values = value.split(":");
+ }
+ try {
+ Criteria cr = session.createCriteria(className);
+ if(columnNames != null && values != null && columnNames.length == values.length){
+ for (int i = 0; i < columnNames.length; i++){
+ cr.add(Restrictions.eq(columnNames[i],values[i]));
+ }
+ }else{
+ cr.add(Restrictions.eq(columnName,value));
+ }
+
+ data = cr.list();
+ tx.commit();
+ } catch (Exception e) {
+ 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);
+ }
+ }
+ return data;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Object> getDataByQuery(String query, SimpleBindings params) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> data = null;
+ try {
+ Query hbquery = session.createQuery(query);
+ for (Map.Entry<String, Object> paramPair : params.entrySet()) {
+ if(paramPair.getValue() instanceof java.lang.Long){
+ hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
+ }
+ else{
+ hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
+ }
+ }
+ data = hbquery.list();
+ tx.commit();
+ } catch (Exception 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);
+ }
+ }
+ return data;
+ }
+
+
+ @Override
+ public void updateQuery(String query) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ Query hbquery = session.createQuery(query);
+ hbquery.executeUpdate();
+ tx.commit();
+ } catch (Exception 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);
+ }
+ }
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object getEntityItem(Class className, String columnName, String key) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ Object data = null;
+ try {
+ Criteria cr = session.createCriteria(className);
+ if(columnName.contains(":") && key.contains(":")){
+ String[] columns = columnName.split(":");
+ String[] keys = key.split(":");
+ for(int i=0; i < columns.length; i++){
+ cr.add(Restrictions.eq(columns[i], keys[i]));
+ }
+ }else{
+ cr.add(Restrictions.eq(columnName, key));
+ }
+ data = cr.list().get(0);
+ tx.commit();
+ } catch (Exception 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);
+ }
+ }
+ return data;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<PolicyRoles> getUserRoles() {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<PolicyRoles> rolesData = null;
+ try {
+ Criteria cr = session.createCriteria(PolicyRoles.class);
+ Disjunction disjunction = Restrictions.disjunction();
+ Conjunction conjunction1 = Restrictions.conjunction();
+ conjunction1.add(Restrictions.eq("role", "admin"));
+ Conjunction conjunction2 = Restrictions.conjunction();
+ conjunction2.add(Restrictions.eq("role", "editor"));
+ Conjunction conjunction3 = Restrictions.conjunction();
+ conjunction3.add(Restrictions.eq("role", "guest"));
+ disjunction.add(conjunction1);
+ disjunction.add(conjunction2);
+ disjunction.add(conjunction3);
+ rolesData = cr.add(disjunction).list();
+ tx.commit();
+ } catch (Exception 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);
+ }
+ }
+ return rolesData;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void updateClAlarms(String clName, String alarms) {
+ Session session = sessionFactory.openSession();
+ List<ClosedLoops> closedloopsdata = null;
+ Transaction tx = session.beginTransaction();
+ try {
+ Criteria cr = session.createCriteria(ClosedLoops.class);
+ cr.add(Restrictions.eq("closedLoopControlName",clName));
+ closedloopsdata = cr.list();
+ ClosedLoops closedloop = closedloopsdata.get(0);
+ closedloop.setAlarmConditions(alarms);
+ session.update(closedloop);
+ tx.commit();
+ }catch(Exception 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) {
+ Session session = sessionFactory.openSession();
+ List<ClosedLoops> closedloopsdata = null;
+ Transaction tx = session.beginTransaction();
+ try {
+ Criteria cr = session.createCriteria(ClosedLoops.class);
+ cr.add(Restrictions.eq("closedLoopControlName",clName));
closedloopsdata = cr.list();
- ClosedLoops closedloop = closedloopsdata.get(0);
- closedloop.setAlarmConditions(alarms);
- session.update(closedloop);
- tx.commit();
- }catch(Exception 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) {
- Session session = sessionFactory.openSession();
+ ClosedLoops closedloop = closedloopsdata.get(0);
+ closedloop.setYaml(yaml);
+ session.update(closedloop);
+ tx.commit();
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e);
+ }finally{
+ session.close();
+ }
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void deleteAll() {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
List<ClosedLoops> closedloopsdata = null;
- Transaction tx = session.beginTransaction();
- try {
- Criteria cr = session.createCriteria(ClosedLoops.class);
- cr.add(Restrictions.eq("closedLoopControlName",clName));
+ try {
+ Criteria cr = session.createCriteria(ClosedLoops.class);
closedloopsdata = cr.list();
- ClosedLoops closedloop = closedloopsdata.get(0);
- closedloop.setYaml(yaml);
- session.update(closedloop);
- tx.commit();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e);
- }finally{
- session.close();
- }
- }
-
-
- @SuppressWarnings("unchecked")
- @Override
- public void deleteAll() {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- List<ClosedLoops> closedloopsdata = null;
- try {
- Criteria cr = session.createCriteria(ClosedLoops.class);
- closedloopsdata = cr.list();
-
- if(closedloopsdata!=null && !closedloopsdata.isEmpty()) {
- LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache().");
- for(int i=0; i < closedloopsdata.size(); i++) {
- ClosedLoops cl = closedloopsdata.get(i);
- session.delete(cl);
- }
- } else {
- LOGGER.info("No ClosedLoops exist in the database, no need to delete.");
- }
-
- tx.commit();
- }catch(Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e);
- }finally{
- session.close();
- }
- }
-
- @SuppressWarnings({ "unchecked"})
- @Override
- public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> data = null;
- try {
- Criteria cr = session.createCriteria(GroupPolicyScopeList.class);
- cr.add(Restrictions.eq("groupList",groupListValue));
- Criterion expression = Restrictions.eq("name", groupNameValue);
- cr.add(Restrictions.not(expression));
- data = cr.list();
- tx.commit();
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "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);
- }
- }
- return data;
- }
-
-
- @Override
- public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) {
- return null;
- }
+
+ if(closedloopsdata!=null && !closedloopsdata.isEmpty()) {
+ LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache().");
+ for(int i=0; i < closedloopsdata.size(); i++) {
+ ClosedLoops cl = closedloopsdata.get(i);
+ session.delete(cl);
+ }
+ } else {
+ LOGGER.info("No ClosedLoops exist in the database, no need to delete.");
+ }
+
+ tx.commit();
+ }catch(Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e);
+ }finally{
+ session.close();
+ }
+ }
+
+ @SuppressWarnings({ "unchecked"})
+ @Override
+ public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) {
+ Session session = sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> data = null;
+ try {
+ Criteria cr = session.createCriteria(GroupPolicyScopeList.class);
+ cr.add(Restrictions.eq("groupList",groupListValue));
+ Criterion expression = Restrictions.eq("name", groupNameValue);
+ cr.add(Restrictions.not(expression));
+ data = cr.list();
+ tx.commit();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "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);
+ }
+ }
+ return data;
+ }
+
+
+ @Override
+ public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) {
+ return null;
+ }
public static void setSessionfactory(SessionFactory sessionfactory) {
sessionFactory = sessionfactory;
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 dcabefcc8..79b07e2b9 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
@@ -71,280 +71,280 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
*
*/
public class ElasticSearchPolicyUpdate {
-
- private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class);
- protected final static JestClientFactory jestFactory = new JestClientFactory();
-
- public static void main(String[] args) {
-
- String elkURL = null;
- String databseUrl = null;
- String userName = null;
- String txt = null;
- String databaseDriver = null;
-
- String propertyFile = System.getProperty("PROPERTY_FILE");
- Properties config = new Properties();
- Path file = Paths.get(propertyFile);
- if(!file.toFile().exists()){
- LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString());
- }else{
- if(file.toString().endsWith(".properties")){
- try {
- InputStream in = new FileInputStream(file.toFile());
- config.load(in);
- elkURL = config.getProperty("policy.elk.url");
- databseUrl = config.getProperty("policy.database.url");
- userName = config.getProperty("policy.database.username");
- txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password"));
- databaseDriver = config.getProperty("policy.database.driver");
- if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){
- LOGGER.error("please check the elk configuration");
- }
- } catch (Exception e) {
- LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
- }
- }
- }
-
- Builder bulk = null;
-
- HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build();
- jestFactory.setHttpClientConfig(httpClientConfig);
- JestHttpClient client = (JestHttpClient) jestFactory.getObject();
-
- Connection conn = null;
- Statement stmt = null;
- ResultSet result = null;
-
- List<Index> listIndex = new ArrayList<>();
-
- try {
- Class.forName(databaseDriver);
- conn = DriverManager.getConnection(databseUrl, userName, txt);
- stmt = conn.createStatement();
-
- String policyEntityQuery = "Select * from PolicyEntity";
- result = stmt.executeQuery(policyEntityQuery);
-
- 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+"\",");
- }
- String description = result.getString("description");
- if(description != null){
- policyDataString.append("\"policyDescription\":\""+description+"\",");
- }
- Object policyData = result.getString("policydata");
-
- 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_")){
- policyDataString.append("\"policyType\":\"Config\",");
- if(policyWithScopeName.contains(".Config_Fault_")){
- _type = "closedloop";
- policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\",");
- }else if(policyWithScopeName.contains(".Config_PM_")){
- _type = "closedloop";
- policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\",");
- }else{
- _type = "config";
- policyDataString.append("\"configPolicyType\":\"Base\",");
- }
- }else if(policyWithScopeName.contains(".Action_")){
- _type = "action";
- policyDataString.append("\"policyType\":\"Action\",");
- }else if(policyWithScopeName.contains(".Decision_")){
- _type = "decision";
- policyDataString.append("\"policyType\":\"Decision\",");
- }
-
- if(!"decision".equals(_type)){
- if(configurationdataid != null){
- updateConfigData(conn, configurationdataid, policyDataString);
- }
- if(actionbodyid != null){
- updateActionData(conn, actionbodyid, policyDataString);
- }
- }
-
- String _id = policyWithScopeName;
-
- String dataString = constructPolicyData(policyData, policyDataString);
- dataString = dataString.substring(0, dataString.length()-1);
- dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
- dataString = dataString.replace("null", "\"\"");
- dataString = dataString.replaceAll("\n", "");
-
- try{
- Gson gson = new Gson();
- gson.fromJson(dataString, Object.class);
- }catch(Exception e){
- LOGGER.error(e);
- continue;
- }
-
- if("config".equals(_type)){
- listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build());
- }else if("closedloop".equals(_type)){
- listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build());
- }else if("action".equals(_type)){
- listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build());
- }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++){
- bulk.addAction(listIndex.get(i));
- }
- BulkResult searchResult = client.execute(bulk.build());
- if(searchResult.isSucceeded()){
- LOGGER.debug("Success");
- }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);
- }
- }
- if(stmt != null){
- try {
- stmt.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the statement"+e);
- }
- }
- if(conn != null){
- try {
- conn.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the connection"+e);
- }
- }
- }
- }
-
- 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){
- PolicyType policy = (PolicyType) policyData;
- TargetType target = policy.getTarget();
- if (target != null) {
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attribute value and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- policyDataString.append("\"onapName\":\""+value+"\",");
- }
- if ("RiskType".equals(attributeId)){
- policyDataString.append("\"riskType\":\""+value+"\",");
- }
- if ("RiskLevel".equals(attributeId)){
- policyDataString.append("\"riskLevel\":\""+value+"\",");
- }
- if ("guard".equals(attributeId)){
- policyDataString.append("\"guard\":\""+value+"\",");
- }
- if ("ConfigName".equals(attributeId)){
- policyDataString.append("\"configName\":\""+value+"\",");
- }
- }
- }
- }
- }
- }
- }
- }
- }
- 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+"\",");
- }
- }
- } 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);
- }
- }
- }
- }
-
- private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class);
+ protected final static JestClientFactory jestFactory = new JestClientFactory();
+
+ public static void main(String[] args) {
+
+ String elkURL = null;
+ String databseUrl = null;
+ String userName = null;
+ String txt = null;
+ String databaseDriver = null;
+
+ String propertyFile = System.getProperty("PROPERTY_FILE");
+ Properties config = new Properties();
+ Path file = Paths.get(propertyFile);
+ if(!file.toFile().exists()){
+ LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString());
+ }else{
+ if(file.toString().endsWith(".properties")){
+ try {
+ InputStream in = new FileInputStream(file.toFile());
+ config.load(in);
+ elkURL = config.getProperty("policy.elk.url");
+ databseUrl = config.getProperty("policy.database.url");
+ userName = config.getProperty("policy.database.username");
+ txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password"));
+ databaseDriver = config.getProperty("policy.database.driver");
+ if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){
+ LOGGER.error("please check the elk configuration");
+ }
+ } catch (Exception e) {
+ LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
+ }
+ }
+ }
+
+ Builder bulk = null;
+
+ HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build();
+ jestFactory.setHttpClientConfig(httpClientConfig);
+ JestHttpClient client = (JestHttpClient) jestFactory.getObject();
+
+ Connection conn = null;
+ Statement stmt = null;
+ ResultSet result = null;
+
+ List<Index> listIndex = new ArrayList<>();
+
+ try {
+ Class.forName(databaseDriver);
+ conn = DriverManager.getConnection(databseUrl, userName, txt);
+ stmt = conn.createStatement();
+
+ String policyEntityQuery = "Select * from PolicyEntity";
+ result = stmt.executeQuery(policyEntityQuery);
+
+ 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+"\",");
+ }
+ String description = result.getString("description");
+ if(description != null){
+ policyDataString.append("\"policyDescription\":\""+description+"\",");
+ }
+ Object policyData = result.getString("policydata");
+
+ 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_")){
+ policyDataString.append("\"policyType\":\"Config\",");
+ if(policyWithScopeName.contains(".Config_Fault_")){
+ _type = "closedloop";
+ policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\",");
+ }else if(policyWithScopeName.contains(".Config_PM_")){
+ _type = "closedloop";
+ policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\",");
+ }else{
+ _type = "config";
+ policyDataString.append("\"configPolicyType\":\"Base\",");
+ }
+ }else if(policyWithScopeName.contains(".Action_")){
+ _type = "action";
+ policyDataString.append("\"policyType\":\"Action\",");
+ }else if(policyWithScopeName.contains(".Decision_")){
+ _type = "decision";
+ policyDataString.append("\"policyType\":\"Decision\",");
+ }
+
+ if(!"decision".equals(_type)){
+ if(configurationdataid != null){
+ updateConfigData(conn, configurationdataid, policyDataString);
+ }
+ if(actionbodyid != null){
+ updateActionData(conn, actionbodyid, policyDataString);
+ }
+ }
+
+ String _id = policyWithScopeName;
+
+ String dataString = constructPolicyData(policyData, policyDataString);
+ dataString = dataString.substring(0, dataString.length()-1);
+ dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
+ dataString = dataString.replace("null", "\"\"");
+ dataString = dataString.replaceAll("\n", "");
+
+ try{
+ Gson gson = new Gson();
+ gson.fromJson(dataString, Object.class);
+ }catch(Exception e){
+ LOGGER.error(e);
+ continue;
+ }
+
+ if("config".equals(_type)){
+ listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build());
+ }else if("closedloop".equals(_type)){
+ listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build());
+ }else if("action".equals(_type)){
+ listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build());
+ }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++){
+ bulk.addAction(listIndex.get(i));
+ }
+ BulkResult searchResult = client.execute(bulk.build());
+ if(searchResult.isSucceeded()){
+ LOGGER.debug("Success");
+ }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);
+ }
+ }
+ if(stmt != null){
+ try {
+ stmt.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the statement"+e);
+ }
+ }
+ if(conn != null){
+ try {
+ conn.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the connection"+e);
+ }
+ }
+ }
+ }
+
+ 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){
+ PolicyType policy = (PolicyType) policyData;
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if ("ONAPName".equals(attributeId)) {
+ policyDataString.append("\"onapName\":\""+value+"\",");
+ }
+ if ("RiskType".equals(attributeId)){
+ policyDataString.append("\"riskType\":\""+value+"\",");
+ }
+ if ("RiskLevel".equals(attributeId)){
+ policyDataString.append("\"riskLevel\":\""+value+"\",");
+ }
+ if ("guard".equals(attributeId)){
+ policyDataString.append("\"guard\":\""+value+"\",");
+ }
+ if ("ConfigName".equals(attributeId)){
+ policyDataString.append("\"configName\":\""+value+"\",");
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ 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+"\",");
+ }
+ }
+ } 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);
+ }
+ }
+ }
+ }
+
+ private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception {
PreparedStatement pstmt = null;
ResultSet actionResult = null;
@@ -378,5 +378,5 @@ public class ElasticSearchPolicyUpdate {
}
}
}
- }
+ }
} \ No newline at end of file
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 83d5c3ff9..e895b6336 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
@@ -27,78 +27,78 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter;
import io.searchbox.client.JestResult;
public interface ElkConnector {
-
- public static final String ELK_URL = "http://localhost:9200";
- public static final String ELK_INDEX_POLICY = "policy";
-
- public enum PolicyIndexType {
- config,
- action,
- decision,
- closedloop,
- all,
- }
-
- public enum PolicyType {
- Config,
- Action,
- Decision,
- Config_Fault,
- Config_PM,
- Config_FW,
- Config_MS,
- Config_OOF,
- none,
- }
-
- public enum PolicyBodyType {
- json,
- xml,
- properties,
- txt,
- none,
- }
-
- public boolean delete(PolicyRestAdapter policyData)
- throws IllegalStateException;
-
- public JestResult search(PolicyIndexType type, String text)
- throws IllegalStateException, IllegalArgumentException;
-
- public JestResult search(PolicyIndexType type, String text,
- Map<String, String> searchKeyValue)
- throws IllegalStateException, IllegalArgumentException;
-
- public boolean update(PolicyRestAdapter policyData) throws IllegalStateException;
-
- public ElkConnector singleton = new ElkConnectorImpl();
-
- public static PolicyIndexType toPolicyIndexType(String policyName)
- throws IllegalArgumentException {
- if (policyName == null)
- throw new IllegalArgumentException("Unsupported NULL policy name conversion");
-
- if (policyName.startsWith("Config_Fault")) {
- return PolicyIndexType.closedloop;
- } else if (policyName.startsWith("Config_PM")) {
- return PolicyIndexType.closedloop;
- } else if (policyName.startsWith("Config_FW")) {
- return PolicyIndexType.config;
- } else if (policyName.startsWith("Config_MS")) {
- return PolicyIndexType.config;
- } else if (policyName.startsWith("Config_OOF")) {
- return PolicyIndexType.config;
- }else if (policyName.startsWith("Action")) {
- return PolicyIndexType.action;
- } else if (policyName.startsWith("Decision")) {
- return PolicyIndexType.decision;
- } else if (policyName.startsWith("Config")) {
- return PolicyIndexType.config;
- } else {
- throw new IllegalArgumentException
- ("Unsupported policy name conversion to index: " +
- policyName);
- }
- }
-
+
+ public static final String ELK_URL = "http://localhost:9200";
+ public static final String ELK_INDEX_POLICY = "policy";
+
+ public enum PolicyIndexType {
+ config,
+ action,
+ decision,
+ closedloop,
+ all,
+ }
+
+ public enum PolicyType {
+ Config,
+ Action,
+ Decision,
+ Config_Fault,
+ Config_PM,
+ Config_FW,
+ Config_MS,
+ Config_OOF,
+ none,
+ }
+
+ public enum PolicyBodyType {
+ json,
+ xml,
+ properties,
+ txt,
+ none,
+ }
+
+ public boolean delete(PolicyRestAdapter policyData)
+ throws IllegalStateException;
+
+ public JestResult search(PolicyIndexType type, String text)
+ throws IllegalStateException, IllegalArgumentException;
+
+ public JestResult search(PolicyIndexType type, String text,
+ Map<String, String> searchKeyValue)
+ throws IllegalStateException, IllegalArgumentException;
+
+ public boolean update(PolicyRestAdapter policyData) throws IllegalStateException;
+
+ public ElkConnector singleton = new ElkConnectorImpl();
+
+ public static PolicyIndexType toPolicyIndexType(String policyName)
+ throws IllegalArgumentException {
+ if (policyName == null)
+ throw new IllegalArgumentException("Unsupported NULL policy name conversion");
+
+ if (policyName.startsWith("Config_Fault")) {
+ return PolicyIndexType.closedloop;
+ } else if (policyName.startsWith("Config_PM")) {
+ return PolicyIndexType.closedloop;
+ } else if (policyName.startsWith("Config_FW")) {
+ return PolicyIndexType.config;
+ } else if (policyName.startsWith("Config_MS")) {
+ return PolicyIndexType.config;
+ } else if (policyName.startsWith("Config_OOF")) {
+ return PolicyIndexType.config;
+ }else if (policyName.startsWith("Action")) {
+ return PolicyIndexType.action;
+ } else if (policyName.startsWith("Decision")) {
+ return PolicyIndexType.decision;
+ } else if (policyName.startsWith("Config")) {
+ return PolicyIndexType.config;
+ } else {
+ 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 d87e75f71..19a7ed294 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
@@ -47,384 +47,384 @@ import io.searchbox.params.Parameters;
public class ElkConnectorImpl implements ElkConnector{
- private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class);
-
- protected final JestClientFactory jestFactory = new JestClientFactory();
- protected final JestClient jestClient;
- protected static int QUERY_MAXRECORDS = 1000;
-
- public ElkConnectorImpl() {
- if (LOGGER.isDebugEnabled()){
- LOGGER.debug("ENTER: -");
- }
- HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build();
- jestFactory.setHttpClientConfig(jestClientConfig);
- jestClient = jestFactory.getObject();
- }
-
- protected boolean isType(PolicyIndexType type) throws IOException {
- if (LOGGER.isDebugEnabled()){
- LOGGER.debug("ENTER: -");
- }
-
- try {
- Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build();
- JestResult result = jestClient.execute(typeQuery);
-
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("JSON:" + result.getJsonString());
- LOGGER.info("ERROR:" + result.getErrorMessage());
- LOGGER.info("PATH:" + result.getPathToResult());
- LOGGER.info(result.getJsonObject());
- }
- return result.isSucceeded();
- } catch (IOException e) {
- LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e);
- throw e;
- }
- }
-
- protected boolean isIndex() throws IOException {
- try {
- Action<JestResult> indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build();
-
- JestResult result = jestClient.execute(indexQuery);
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("JSON:" + result.getJsonString());
- LOGGER.info("ERROR:" + result.getErrorMessage());
- LOGGER.info("PATH:" + result.getPathToResult());
- LOGGER.info(result.getJsonObject());
- }
- return result.isSucceeded();
- } catch (IOException e) {
- LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e);
- throw e;
- }
- }
- private boolean isAlphaNumeric(String query){
- return query.matches("[a-zA-Z_0-9]+");
- }
-
- @Override
- public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException {
- if (LOGGER.isTraceEnabled()){
- LOGGER.trace("ENTER: " + text);
- }
-
- if (text == null || text.isEmpty()) {
- throw new IllegalArgumentException("No search string provided");
- }
-
- if(!isAlphaNumeric(text)){
- throw new IllegalArgumentException("Search must be alpha numeric");
- }
-
- 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);
-
- if (type == null || type == PolicyIndexType.all) {
- for (PolicyIndexType pT: PolicyIndexType.values()) {
- if (pT != PolicyIndexType.all) {
- searchBuilder.addType(pT.toString());
- }
- }
- } else {
- searchBuilder.addType(type.toString());
- }
-
- Search search = searchBuilder.build();
- JestResult result;
- try {
- result = jestClient.execute(search);
- } catch (IOException 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());
- }
- } else {
- /* Unsuccessful search */
- if (LOGGER.isWarnEnabled()){
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" +
- result.getResponseCode() + ": " +
- search.getURI() + ":" +
- result.getPathToResult() + ":" +
- result.getJsonString() + ":" +
- result.getErrorMessage());
- }
-
- String errorMessage = result.getErrorMessage();
- if (errorMessage != null && !errorMessage.isEmpty()) {
- String xMessage;
- if (errorMessage.contains("TokenMgrError")) {
- int indexError = errorMessage.lastIndexOf("TokenMgrError");
- 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);
- } else if (errorMessage.contains("JsonParseException")) {
- int indexError = errorMessage.lastIndexOf("JsonParseException");
- 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);
- } else if (errorMessage.contains("SearchParseException")) {
- int indexError = errorMessage.lastIndexOf("SearchParseException");
- xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
- } else {
- xMessage = result.getErrorMessage();
- }
- throw new IllegalStateException(xMessage);
- }
- }
-
- return result;
- }
-
-
- @Override
- public JestResult search(PolicyIndexType type, String text,
- Map<String, String> filter_s)
- throws IllegalStateException, IllegalArgumentException {
- if (LOGGER.isTraceEnabled()){
- LOGGER.trace("ENTER: " + text);
- }
-
- if (filter_s == null || filter_s.size() == 0) {
- return search(type, text);
- }
-
- if(!isAlphaNumeric(text)){
- throw new IllegalArgumentException("Search must be alpha numeric");
- }
-
- String matches_s = "";
- matches_s = "{\n" +
- " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" +
- " \"query\": {\n" +
- " \"bool\" : {\n" +
- " \"must\" : [";
-
- String match_params = "";
- boolean first = true;
- for(Entry<String, String> entry : filter_s.entrySet()){
- String key = entry.getKey();
- String value = entry.getValue();
- if(first){
- match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},";
- first = false;
- }else{
- match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },";
- }
- }
- if(match_params.endsWith(",")){
- match_params = match_params.substring(0, match_params.length()-2);
- }
-
- matches_s = matches_s + "{\n" + match_params + "\n}" ;
-
- boolean query = false;
- String query_String = "";
- if(text != null){
- query = true;
- query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}";
- }
-
- if(query){
- matches_s = matches_s + "," + query_String + "]\n}\n}\n}";
- }else{
- matches_s = matches_s + "]\n}\n}\n}";
- }
-
- Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY);
-
- if (type == null || type == PolicyIndexType.all) {
- for (PolicyIndexType pT: PolicyIndexType.values()) {
- if (pT != PolicyIndexType.all) {
- searchBuilder.addType(pT.toString());
- }
- }
- } else {
- searchBuilder.addType(type.toString());
- }
-
- Search search = searchBuilder.build();
-
- JestResult result;
- try {
- result = jestClient.execute(search);
- } catch (IOException 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());
- }
- } else {
- /* Unsuccessful search */
- if (LOGGER.isWarnEnabled()){
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" +
- result.getResponseCode() + ": " +
- search.getURI() + ":" +
- result.getPathToResult() + ":" +
- result.getJsonString() + ":" +
- result.getErrorMessage());
- }
-
- String errorMessage = result.getErrorMessage();
- if (errorMessage != null && !errorMessage.isEmpty()) {
- String xMessage = errorMessage;
- if (errorMessage.contains("TokenMgrError")) {
- int indexError = errorMessage.lastIndexOf("TokenMgrError");
- 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);
- } else if (errorMessage.contains("JsonParseException")) {
- int indexError = errorMessage.lastIndexOf("JsonParseException");
- 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);
- } else if (errorMessage.contains("SearchParseException")) {
- int indexError = errorMessage.lastIndexOf("SearchParseException");
- xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
- } else {
- xMessage = result.getErrorMessage();
- }
- throw new IllegalStateException(xMessage);
- }
- }
-
- return result;
- }
-
- public boolean put(PolicyRestAdapter policyData)
- throws IOException, IllegalStateException {
- if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER");
-
- PolicyIndexType indexType;
- try {
- String policyName = policyData.getNewFileName();
- if(policyName.contains("Config_")){
- policyName = policyName.replace(".Config_", ":Config_");
- }else if(policyName.contains("Action_")){
- policyName = policyName.replace(".Action_", ":Action_");
- }else if(policyName.contains("Decision_")){
- policyName = policyName.replace(".Decision_", ":Decision_");
- }
-
- String[] splitPolicyName = policyName.split(":");
- indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]);
- } catch (IllegalArgumentException e) {
- LOGGER.error(e);
- throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage());
- }
- 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();
-
- 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() +
- result.getJsonString());
- } else {
- if (LOGGER.isWarnEnabled())
- LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " +
- "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
- result.getPathToResult() + "]" + System.lineSeparator() +
- result.getJsonString());
-
- }
-
- return result.isSucceeded();
- }
-
- @Override
- public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException {
- PolicyIndexType indexType = null;
- JestResult result;
- try {
- String policyName = policyData.getNewFileName();
- if(policyName.contains("Config_")){
- policyName = policyName.replace(".Config_", ":Config_");
- }else if(policyName.contains("Action_")){
- policyName = policyName.replace(".Action_", ":Action_");
- }else if(policyName.contains("Decision_")){
- policyName = policyName.replace(".Decision_", ":Decision_");
- }
-
- 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");
- }
- PolicyElasticData elasticData = new PolicyElasticData(policyData);
- 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);
- 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());
- } else {
- if (LOGGER.isWarnEnabled())
- LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " +
- "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
- result.getPathToResult() + "]" + System.lineSeparator() +
- result.getJsonString());
- }
-
- return result.isSucceeded();
- }
-
- @Override
- public boolean update(PolicyRestAdapter policyData) throws IllegalStateException {
- if (LOGGER.isDebugEnabled()){
- LOGGER.debug("ENTER");
- }
- try {
- boolean success = put(policyData);
- return success;
- } catch (Exception e) {
- LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e);
- throw new IllegalStateException(e);
- }
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class);
+
+ protected final JestClientFactory jestFactory = new JestClientFactory();
+ protected final JestClient jestClient;
+ protected static int QUERY_MAXRECORDS = 1000;
+
+ public ElkConnectorImpl() {
+ if (LOGGER.isDebugEnabled()){
+ LOGGER.debug("ENTER: -");
+ }
+ HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build();
+ jestFactory.setHttpClientConfig(jestClientConfig);
+ jestClient = jestFactory.getObject();
+ }
+
+ protected boolean isType(PolicyIndexType type) throws IOException {
+ if (LOGGER.isDebugEnabled()){
+ LOGGER.debug("ENTER: -");
+ }
+
+ try {
+ Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build();
+ JestResult result = jestClient.execute(typeQuery);
+
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.info("JSON:" + result.getJsonString());
+ LOGGER.info("ERROR:" + result.getErrorMessage());
+ LOGGER.info("PATH:" + result.getPathToResult());
+ LOGGER.info(result.getJsonObject());
+ }
+ return result.isSucceeded();
+ } catch (IOException e) {
+ LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e);
+ throw e;
+ }
+ }
+
+ protected boolean isIndex() throws IOException {
+ try {
+ Action<JestResult> indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build();
+
+ JestResult result = jestClient.execute(indexQuery);
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.info("JSON:" + result.getJsonString());
+ LOGGER.info("ERROR:" + result.getErrorMessage());
+ LOGGER.info("PATH:" + result.getPathToResult());
+ LOGGER.info(result.getJsonObject());
+ }
+ return result.isSucceeded();
+ } catch (IOException e) {
+ LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e);
+ throw e;
+ }
+ }
+ private boolean isAlphaNumeric(String query){
+ return query.matches("[a-zA-Z_0-9]+");
+ }
+
+ @Override
+ public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException {
+ if (LOGGER.isTraceEnabled()){
+ LOGGER.trace("ENTER: " + text);
+ }
+
+ if (text == null || text.isEmpty()) {
+ throw new IllegalArgumentException("No search string provided");
+ }
+
+ if(!isAlphaNumeric(text)){
+ throw new IllegalArgumentException("Search must be alpha numeric");
+ }
+
+ 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);
+
+ if (type == null || type == PolicyIndexType.all) {
+ for (PolicyIndexType pT: PolicyIndexType.values()) {
+ if (pT != PolicyIndexType.all) {
+ searchBuilder.addType(pT.toString());
+ }
+ }
+ } else {
+ searchBuilder.addType(type.toString());
+ }
+
+ Search search = searchBuilder.build();
+ JestResult result;
+ try {
+ result = jestClient.execute(search);
+ } catch (IOException 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());
+ }
+ } else {
+ /* Unsuccessful search */
+ if (LOGGER.isWarnEnabled()){
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" +
+ result.getResponseCode() + ": " +
+ search.getURI() + ":" +
+ result.getPathToResult() + ":" +
+ result.getJsonString() + ":" +
+ result.getErrorMessage());
+ }
+
+ String errorMessage = result.getErrorMessage();
+ if (errorMessage != null && !errorMessage.isEmpty()) {
+ String xMessage;
+ if (errorMessage.contains("TokenMgrError")) {
+ int indexError = errorMessage.lastIndexOf("TokenMgrError");
+ 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);
+ } else if (errorMessage.contains("JsonParseException")) {
+ int indexError = errorMessage.lastIndexOf("JsonParseException");
+ 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);
+ } else if (errorMessage.contains("SearchParseException")) {
+ int indexError = errorMessage.lastIndexOf("SearchParseException");
+ xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
+ } else {
+ xMessage = result.getErrorMessage();
+ }
+ throw new IllegalStateException(xMessage);
+ }
+ }
+
+ return result;
+ }
+
+
+ @Override
+ public JestResult search(PolicyIndexType type, String text,
+ Map<String, String> filter_s)
+ throws IllegalStateException, IllegalArgumentException {
+ if (LOGGER.isTraceEnabled()){
+ LOGGER.trace("ENTER: " + text);
+ }
+
+ if (filter_s == null || filter_s.size() == 0) {
+ return search(type, text);
+ }
+
+ if(!isAlphaNumeric(text)){
+ throw new IllegalArgumentException("Search must be alpha numeric");
+ }
+
+ String matches_s = "";
+ matches_s = "{\n" +
+ " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" +
+ " \"query\": {\n" +
+ " \"bool\" : {\n" +
+ " \"must\" : [";
+
+ String match_params = "";
+ boolean first = true;
+ for(Entry<String, String> entry : filter_s.entrySet()){
+ String key = entry.getKey();
+ String value = entry.getValue();
+ if(first){
+ match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},";
+ first = false;
+ }else{
+ match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },";
+ }
+ }
+ if(match_params.endsWith(",")){
+ match_params = match_params.substring(0, match_params.length()-2);
+ }
+
+ matches_s = matches_s + "{\n" + match_params + "\n}" ;
+
+ boolean query = false;
+ String query_String = "";
+ if(text != null){
+ query = true;
+ query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}";
+ }
+
+ if(query){
+ matches_s = matches_s + "," + query_String + "]\n}\n}\n}";
+ }else{
+ matches_s = matches_s + "]\n}\n}\n}";
+ }
+
+ Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY);
+
+ if (type == null || type == PolicyIndexType.all) {
+ for (PolicyIndexType pT: PolicyIndexType.values()) {
+ if (pT != PolicyIndexType.all) {
+ searchBuilder.addType(pT.toString());
+ }
+ }
+ } else {
+ searchBuilder.addType(type.toString());
+ }
+
+ Search search = searchBuilder.build();
+
+ JestResult result;
+ try {
+ result = jestClient.execute(search);
+ } catch (IOException 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());
+ }
+ } else {
+ /* Unsuccessful search */
+ if (LOGGER.isWarnEnabled()){
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" +
+ result.getResponseCode() + ": " +
+ search.getURI() + ":" +
+ result.getPathToResult() + ":" +
+ result.getJsonString() + ":" +
+ result.getErrorMessage());
+ }
+
+ String errorMessage = result.getErrorMessage();
+ if (errorMessage != null && !errorMessage.isEmpty()) {
+ String xMessage = errorMessage;
+ if (errorMessage.contains("TokenMgrError")) {
+ int indexError = errorMessage.lastIndexOf("TokenMgrError");
+ 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);
+ } else if (errorMessage.contains("JsonParseException")) {
+ int indexError = errorMessage.lastIndexOf("JsonParseException");
+ 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);
+ } else if (errorMessage.contains("SearchParseException")) {
+ int indexError = errorMessage.lastIndexOf("SearchParseException");
+ xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
+ } else {
+ xMessage = result.getErrorMessage();
+ }
+ throw new IllegalStateException(xMessage);
+ }
+ }
+
+ return result;
+ }
+
+ public boolean put(PolicyRestAdapter policyData)
+ throws IOException, IllegalStateException {
+ if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER");
+
+ PolicyIndexType indexType;
+ try {
+ String policyName = policyData.getNewFileName();
+ if(policyName.contains("Config_")){
+ policyName = policyName.replace(".Config_", ":Config_");
+ }else if(policyName.contains("Action_")){
+ policyName = policyName.replace(".Action_", ":Action_");
+ }else if(policyName.contains("Decision_")){
+ policyName = policyName.replace(".Decision_", ":Decision_");
+ }
+
+ String[] splitPolicyName = policyName.split(":");
+ indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]);
+ } catch (IllegalArgumentException e) {
+ LOGGER.error(e);
+ throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage());
+ }
+ 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();
+
+ 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() +
+ result.getJsonString());
+ } else {
+ if (LOGGER.isWarnEnabled())
+ LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " +
+ "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
+ result.getPathToResult() + "]" + System.lineSeparator() +
+ result.getJsonString());
+
+ }
+
+ return result.isSucceeded();
+ }
+
+ @Override
+ public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException {
+ PolicyIndexType indexType = null;
+ JestResult result;
+ try {
+ String policyName = policyData.getNewFileName();
+ if(policyName.contains("Config_")){
+ policyName = policyName.replace(".Config_", ":Config_");
+ }else if(policyName.contains("Action_")){
+ policyName = policyName.replace(".Action_", ":Action_");
+ }else if(policyName.contains("Decision_")){
+ policyName = policyName.replace(".Decision_", ":Decision_");
+ }
+
+ 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");
+ }
+ PolicyElasticData elasticData = new PolicyElasticData(policyData);
+ 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);
+ 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());
+ } else {
+ if (LOGGER.isWarnEnabled())
+ LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " +
+ "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
+ result.getPathToResult() + "]" + System.lineSeparator() +
+ result.getJsonString());
+ }
+
+ return result.isSucceeded();
+ }
+
+ @Override
+ public boolean update(PolicyRestAdapter policyData) throws IllegalStateException {
+ if (LOGGER.isDebugEnabled()){
+ LOGGER.debug("ENTER");
+ }
+ try {
+ boolean success = put(policyData);
+ return success;
+ } catch (Exception e) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e);
+ throw new IllegalStateException(e);
+ }
+ }
}
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 e56e82cbf..988640ca6 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
@@ -28,596 +28,596 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.adapter.YAMLParams;
public class PolicyElasticData {
-
- private String scope;
- private String policyType;
- private String configPolicyType;
- private String configBodyData;
- private String policyName;
- private String policyDescription;
- private String onapName;
- private String configName;
- private String configType;
- private String jsonBody;
- private Object jsonBodyData;
-
- private Map<?, ?> serviceTypePolicyName;
- private Map<?, ?> verticaMetrics;
+
+ private String scope;
+ private String policyType;
+ private String configPolicyType;
+ private String configBodyData;
+ private String policyName;
+ private String policyDescription;
+ private String onapName;
+ private String configName;
+ private String configType;
+ private String jsonBody;
+ private Object jsonBodyData;
+
+ private Map<?, ?> serviceTypePolicyName;
+ private Map<?, ?> verticaMetrics;
private Map<?, ?> description;
private Map<?, ?> attributeFields;
- //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 List<Object> triggerSignatures;
- private List<Object> symptomSignatures;
- private String logicalConnector;
- private String policyStatus;
- public String gocServerScope;
- private String supressionType;
-
- //MicroSerice
- private String serviceType;
- private String uuid;
- private String location;
- private String priority;
- private String msLocation;
-
- //BRMS Policies
- private String ruleName;
- private Map<String,String> brmsParamBody;
- private String brmsController;
- private List<String> brmsDependency;
- private LinkedHashMap<?, ?> ruleData;
- private LinkedHashMap<?,?> ruleListData;
- private Map<String,String> drlRuleAndUIParams;
-
- //ClosedLoop
- private String clearTimeOut;
- private String trapMaxAge;
- private String verificationclearTimeOut;
- public Map<String , String> dynamicLayoutMap;
-
- //FireWall
- private String fwPolicyType;
- private List<Object> fwattributes;
- private String parentForChild;
- private String securityZone;
-
- //Action & Decision
- private String ruleCombiningAlgId;
- 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;
- private List<String> dynamicRuleAlgorithmCombo;
- private List<String> dynamicRuleAlgorithmField1;
- private List<String> dynamicRuleAlgorithmField2;
- private List<Object> dynamicVariableList;
- private List<String> dataTypeList;
- private String actionAttributeValue;
- private String ruleProvider;
- private String actionBody;
- private String actionDictHeader;
- private String actionDictType;
- private String actionDictUrl;
- private String actionDictMethod;
- private YAMLParams yamlparams;
-
- public PolicyElasticData(PolicyRestAdapter policyData) {
- this.scope = policyData.getDomainDir();
- this.policyType = policyData.getPolicyType();
- this.configPolicyType = policyData.getConfigPolicyType();
- this.configBodyData = policyData.getConfigBodyData();
- 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")){
- this.jsonBodyData = jsonBody;
- }else{
- this.jsonBodyData = policyData.getJsonBodyData();
- }
-
- this.serviceTypePolicyName = policyData.getServiceTypePolicyName();
- this.verticaMetrics = policyData.getVerticaMetrics();
- this.description = policyData.getDescription();
- this.attributeFields = policyData.getAttributeFields();
-
- //Safe Policy
- this.policyScope = policyData.getPolicyScope();
- this.providerComboBox = policyData.getProviderComboBox();
- this.riskType = policyData.getRiskType();
- this.riskLevel = policyData.getRiskLevel();
- this.guard = policyData.getGuard();
- this.ttlDate = policyData.getTtlDate();
- this.matching = policyData.getMatching();
-
- this.triggerSignatures = policyData.getTriggerSignatures();
- this.symptomSignatures = policyData.getSymptomSignatures();
- this.logicalConnector = policyData.getLogicalConnector();
- this.policyStatus = policyData.getPolicyStatus();
- this.gocServerScope = policyData.getGocServerScope();
- this.supressionType = policyData.getSupressionType();
-
- //MicroSerice
- this.serviceType = policyData.getServiceType();
- this.uuid = policyData.getUuid();
- this.location = policyData.getLocation();
- this.priority = policyData.getPriority();
- this.msLocation = policyData.getMsLocation();
-
- //BRMS Policies
- this.ruleName = policyData.getRuleName();
- this.brmsParamBody = policyData.getBrmsParamBody();
- this.brmsController = policyData.getBrmsController();
- this.brmsDependency = policyData.getBrmsDependency();
- this.ruleData = policyData.getRuleData();
- this.ruleListData = policyData.getRuleListData();
- this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams();
-
- //ClosedLoop
- this.clearTimeOut = policyData.getClearTimeOut();
- this.trapMaxAge = policyData.getTrapMaxAge();
- this.verificationclearTimeOut = policyData.getVerificationclearTimeOut();
- this.dynamicLayoutMap = policyData.getDynamicLayoutMap();
-
- //FireWall
- this.fwPolicyType = policyData.getFwPolicyType();
- this.fwattributes = policyData.getFwattributes();
- this.parentForChild = policyData.getParentForChild();
- this.securityZone = policyData.getSecurityZone();
-
- //Action & Decision
- this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId();
- this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes();
- this.dynamicSettingsMap = policyData.getDynamicSettingsMap();
- this.dropDownMap = policyData.getDropDownMap();
- this.actionPerformer = policyData.getActionPerformer();
- this.actionAttribute = policyData.getActionAttribute();
- this.dynamicRuleAlgorithmLabels = policyData.getDynamicRuleAlgorithmLabels();
- this.dynamicRuleAlgorithmCombo = policyData.getDynamicRuleAlgorithmCombo();
- this.dynamicRuleAlgorithmField1 = policyData.getDynamicRuleAlgorithmField1();
- this.dynamicRuleAlgorithmField2 = policyData.getDynamicRuleAlgorithmField2();
- this.dynamicVariableList = policyData.getDynamicVariableList();
- this.dataTypeList = policyData.getDataTypeList();
- this.actionAttributeValue = policyData.getActionAttributeValue();
- this.ruleProvider = policyData.getRuleProvider();
- this.actionBody = policyData.getActionBody();
- this.actionDictHeader = policyData.getActionDictHeader();
- this.actionDictType = policyData.getActionDictType();
- this.actionDictUrl = policyData.getActionDictUrl();
- this.actionDictMethod = policyData.getActionDictMethod();
- this.yamlparams = policyData.getYamlparams();
- }
-
- 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;
- }
-
- 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;
- }
-
- public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) {
- this.serviceTypePolicyName = serviceTypePolicyName;
- }
-
- public Map<?, ?> getVerticaMetrics() {
- return verticaMetrics;
- }
-
- public void setVerticaMetrics(LinkedHashMap<?, ?> verticaMetrics) {
- this.verticaMetrics = verticaMetrics;
- }
-
- public Map<?, ?> getDescription() {
- return description;
- }
-
- public void setDescription(Map<?, ?> description) {
- this.description = description;
- }
-
- public Map<?, ?> getAttributeFields() {
- return attributeFields;
- }
-
- 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;
- }
-
- public void setYamlparams(YAMLParams yamlparams) {
- this.yamlparams = yamlparams;
- }
-
- public Object getJsonBodyData() {
- return jsonBodyData;
- }
-
- public void setJsonBodyData(Object jsonBodyData) {
- this.jsonBodyData = jsonBodyData;
- }
+ //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 List<Object> triggerSignatures;
+ private List<Object> symptomSignatures;
+ private String logicalConnector;
+ private String policyStatus;
+ public String gocServerScope;
+ private String supressionType;
+
+ //MicroSerice
+ private String serviceType;
+ private String uuid;
+ private String location;
+ private String priority;
+ private String msLocation;
+
+ //BRMS Policies
+ private String ruleName;
+ private Map<String,String> brmsParamBody;
+ private String brmsController;
+ private List<String> brmsDependency;
+ private LinkedHashMap<?, ?> ruleData;
+ private LinkedHashMap<?,?> ruleListData;
+ private Map<String,String> drlRuleAndUIParams;
+
+ //ClosedLoop
+ private String clearTimeOut;
+ private String trapMaxAge;
+ private String verificationclearTimeOut;
+ public Map<String , String> dynamicLayoutMap;
+
+ //FireWall
+ private String fwPolicyType;
+ private List<Object> fwattributes;
+ private String parentForChild;
+ private String securityZone;
+
+ //Action & Decision
+ private String ruleCombiningAlgId;
+ 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;
+ private List<String> dynamicRuleAlgorithmCombo;
+ private List<String> dynamicRuleAlgorithmField1;
+ private List<String> dynamicRuleAlgorithmField2;
+ private List<Object> dynamicVariableList;
+ private List<String> dataTypeList;
+ private String actionAttributeValue;
+ private String ruleProvider;
+ private String actionBody;
+ private String actionDictHeader;
+ private String actionDictType;
+ private String actionDictUrl;
+ private String actionDictMethod;
+ private YAMLParams yamlparams;
+
+ public PolicyElasticData(PolicyRestAdapter policyData) {
+ this.scope = policyData.getDomainDir();
+ this.policyType = policyData.getPolicyType();
+ this.configPolicyType = policyData.getConfigPolicyType();
+ this.configBodyData = policyData.getConfigBodyData();
+ 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")){
+ this.jsonBodyData = jsonBody;
+ }else{
+ this.jsonBodyData = policyData.getJsonBodyData();
+ }
+
+ this.serviceTypePolicyName = policyData.getServiceTypePolicyName();
+ this.verticaMetrics = policyData.getVerticaMetrics();
+ this.description = policyData.getDescription();
+ this.attributeFields = policyData.getAttributeFields();
+
+ //Safe Policy
+ this.policyScope = policyData.getPolicyScope();
+ this.providerComboBox = policyData.getProviderComboBox();
+ this.riskType = policyData.getRiskType();
+ this.riskLevel = policyData.getRiskLevel();
+ this.guard = policyData.getGuard();
+ this.ttlDate = policyData.getTtlDate();
+ this.matching = policyData.getMatching();
+
+ this.triggerSignatures = policyData.getTriggerSignatures();
+ this.symptomSignatures = policyData.getSymptomSignatures();
+ this.logicalConnector = policyData.getLogicalConnector();
+ this.policyStatus = policyData.getPolicyStatus();
+ this.gocServerScope = policyData.getGocServerScope();
+ this.supressionType = policyData.getSupressionType();
+
+ //MicroSerice
+ this.serviceType = policyData.getServiceType();
+ this.uuid = policyData.getUuid();
+ this.location = policyData.getLocation();
+ this.priority = policyData.getPriority();
+ this.msLocation = policyData.getMsLocation();
+
+ //BRMS Policies
+ this.ruleName = policyData.getRuleName();
+ this.brmsParamBody = policyData.getBrmsParamBody();
+ this.brmsController = policyData.getBrmsController();
+ this.brmsDependency = policyData.getBrmsDependency();
+ this.ruleData = policyData.getRuleData();
+ this.ruleListData = policyData.getRuleListData();
+ this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams();
+
+ //ClosedLoop
+ this.clearTimeOut = policyData.getClearTimeOut();
+ this.trapMaxAge = policyData.getTrapMaxAge();
+ this.verificationclearTimeOut = policyData.getVerificationclearTimeOut();
+ this.dynamicLayoutMap = policyData.getDynamicLayoutMap();
+
+ //FireWall
+ this.fwPolicyType = policyData.getFwPolicyType();
+ this.fwattributes = policyData.getFwattributes();
+ this.parentForChild = policyData.getParentForChild();
+ this.securityZone = policyData.getSecurityZone();
+
+ //Action & Decision
+ this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId();
+ this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes();
+ this.dynamicSettingsMap = policyData.getDynamicSettingsMap();
+ this.dropDownMap = policyData.getDropDownMap();
+ this.actionPerformer = policyData.getActionPerformer();
+ this.actionAttribute = policyData.getActionAttribute();
+ this.dynamicRuleAlgorithmLabels = policyData.getDynamicRuleAlgorithmLabels();
+ this.dynamicRuleAlgorithmCombo = policyData.getDynamicRuleAlgorithmCombo();
+ this.dynamicRuleAlgorithmField1 = policyData.getDynamicRuleAlgorithmField1();
+ this.dynamicRuleAlgorithmField2 = policyData.getDynamicRuleAlgorithmField2();
+ this.dynamicVariableList = policyData.getDynamicVariableList();
+ this.dataTypeList = policyData.getDataTypeList();
+ this.actionAttributeValue = policyData.getActionAttributeValue();
+ this.ruleProvider = policyData.getRuleProvider();
+ this.actionBody = policyData.getActionBody();
+ this.actionDictHeader = policyData.getActionDictHeader();
+ this.actionDictType = policyData.getActionDictType();
+ this.actionDictUrl = policyData.getActionDictUrl();
+ this.actionDictMethod = policyData.getActionDictMethod();
+ this.yamlparams = policyData.getYamlparams();
+ }
+
+ 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;
+ }
+
+ 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;
+ }
+
+ public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) {
+ this.serviceTypePolicyName = serviceTypePolicyName;
+ }
+
+ public Map<?, ?> getVerticaMetrics() {
+ return verticaMetrics;
+ }
+
+ public void setVerticaMetrics(LinkedHashMap<?, ?> verticaMetrics) {
+ this.verticaMetrics = verticaMetrics;
+ }
+
+ public Map<?, ?> getDescription() {
+ return description;
+ }
+
+ public void setDescription(Map<?, ?> description) {
+ this.description = description;
+ }
+
+ public Map<?, ?> getAttributeFields() {
+ return attributeFields;
+ }
+
+ 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;
+ }
+
+ public void setYamlparams(YAMLParams yamlparams) {
+ this.yamlparams = yamlparams;
+ }
+
+ public Object getJsonBodyData() {
+ return jsonBodyData;
+ }
+
+ public void setJsonBodyData(Object jsonBodyData) {
+ this.jsonBodyData = jsonBodyData;
+ }
}
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 a8320093e..50965bd2b 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
@@ -77,388 +77,388 @@ import io.searchbox.client.JestResult;
@RequestMapping({"/"})
public class PolicyElasticSearchController{
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class);
+ 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>() {
- private static final long serialVersionUID = 1L;
- };
-
- private static CommonClassDao commonClassDao;
- private static final String action = "action";
- private static final String config = "config";
- private static final String decision = "decision";
- private static final String pholder = "pholder";
- private static final String jsonBodyData = "jsonBodyData";
- private static final String success = "success";
+ protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
+ private static final long serialVersionUID = 1L;
+ };
- @Autowired
- public PolicyElasticSearchController(CommonClassDao commonClassDao) {
- PolicyElasticSearchController.commonClassDao = commonClassDao;
- }
+ private static CommonClassDao commonClassDao;
+ private static final String action = "action";
+ private static final String config = "config";
+ private static final String decision = "decision";
+ private static final String pholder = "pholder";
+ private static final String jsonBodyData = "jsonBodyData";
+ private static final String success = "success";
- public PolicyElasticSearchController() {
- super();
- }
+ @Autowired
+ public PolicyElasticSearchController(CommonClassDao commonClassDao) {
+ PolicyElasticSearchController.commonClassDao = commonClassDao;
+ }
- public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
- if (type == null || type.isEmpty()){
- return PolicyIndexType.all;
- }
- return PolicyIndexType.valueOf(type);
- }
+ public PolicyElasticSearchController() {
+ super();
+ }
- public boolean updateElk(PolicyRestAdapter policyData) {
- boolean success = true;
- try {
- success = ElkConnector.singleton.update(policyData);
- if (!success) {
- if (LOGGER.isWarnEnabled()) {
- LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
- }
- } else {
- if (LOGGER.isInfoEnabled()) {
- LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
- }
- }
- } catch (Exception e) {
- LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
- success = false;
- }
- return success;
- }
+ public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
+ if (type == null || type.isEmpty()){
+ return PolicyIndexType.all;
+ }
+ return PolicyIndexType.valueOf(type);
+ }
- public boolean deleteElk(PolicyRestAdapter policyData) {
- boolean success = true;
- try {
- success = ElkConnector.singleton.delete(policyData);
- if (!success) {
- if (LOGGER.isWarnEnabled()) {
- LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
- }
- } else {
- if (LOGGER.isInfoEnabled()) {
- LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
- }
- }
- } catch (Exception e) {
- LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
- success = false;
- }
- return success;
- }
+ public boolean updateElk(PolicyRestAdapter policyData) {
+ boolean success = true;
+ try {
+ success = ElkConnector.singleton.update(policyData);
+ if (!success) {
+ if (LOGGER.isWarnEnabled()) {
+ LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
+ }
+ } else {
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
+ success = false;
+ }
+ return success;
+ }
-
- @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
- public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
- try{
- String message="";
- boolean result = false;
- boolean policyResult = false;
- boolean validationCheck = true;
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- PolicyRestAdapter policyData = new PolicyRestAdapter();
- PolicyElasticSearchController controller = new PolicyElasticSearchController();
- Map<String, String> searchKeyValue = new HashMap<>();
- List<String> policyList = new ArrayList<>();
- if(request.getParameter("policyName") != null){
- String policyName = request.getParameter("policyName");
- policyData.setNewFileName(policyName);
- if("delete".equalsIgnoreCase(request.getParameter(action))){
- result = controller.deleteElk(policyData);
- }else{
- result = controller.updateElk(policyData);
- }
- }
- if("search".equalsIgnoreCase(request.getParameter(action))){
- try {
- JsonNode root = mapper.readTree(request.getReader());
- SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class);
+ public boolean deleteElk(PolicyRestAdapter policyData) {
+ boolean success = true;
+ try {
+ success = ElkConnector.singleton.delete(policyData);
+ if (!success) {
+ if (LOGGER.isWarnEnabled()) {
+ LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
+ }
+ } else {
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
+ success = false;
+ }
+ return success;
+ }
- String policyType = searchData.getPolicyType();
-
- 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){
- 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];
- validationCheck = false;
- }
- 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;
- validationCheck = false;
- }
-
- if(searchData.getClosedLooppolicyType() != null){
- String closedLoopType;
- if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){
- closedLoopType = "ClosedLoop_Fault";
- }else{
- closedLoopType = "ClosedLoop_PM";
- }
- searchKeyValue.put("configPolicyType", closedLoopType);
- }
- if(searchData.getOnapName() != null){
- searchKeyValue.put("onapName", searchData.getOnapName());
- }
- if(searchData.getD2Service() != null){
- String d2Service = searchData.getD2Service().trim();
- if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){
- d2Service = "trinity";
- }else if("vUSP".equalsIgnoreCase(d2Service)){
- d2Service = "vUSP";
- }else if("MCR".equalsIgnoreCase(d2Service)){
- d2Service = "mcr";
- }else if("Gamma".equalsIgnoreCase(d2Service)){
- d2Service = "gamma";
- }else if("vDNS".equalsIgnoreCase(d2Service)){
- d2Service = "vDNS";
- }
- searchKeyValue.put("jsonBodyData."+d2Service+"", "true");
- }
- if(searchData.getVnfType() != null){
- searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*");
- }
- if(searchData.getPolicyStatus() != null){
- searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*");
- }
- if(searchData.getVproAction() != null){
- searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*");
- }
- if(searchData.getServiceType() != null){
- searchKeyValue.put("serviceType", searchData.getServiceType());
- }
- if(searchData.getBindTextSearch() != null){
- searchKeyValue.put(searchData.getBindTextSearch(), searchText);
- searchText = null;
- }
- PolicyIndexType type = null;
- if(policyType != null){
- if(action.equalsIgnoreCase(policyType)){
- type = ElkConnector.PolicyIndexType.action;
- }else if(decision.equalsIgnoreCase(policyType)){
- type = ElkConnector.PolicyIndexType.decision;
- }else if(config.equalsIgnoreCase(policyType)){
- type = ElkConnector.PolicyIndexType.config;
- }else if("closedloop".equalsIgnoreCase(policyType)){
- type = ElkConnector.PolicyIndexType.closedloop;
- }else{
- type = ElkConnector.PolicyIndexType.all;
- }
- }else{
- type = ElkConnector.PolicyIndexType.all;
- }
- if(validationCheck){
- JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
- 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++){
- 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");
- }
- }
- }catch(Exception e){
- LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
- }
- }
- if(validationCheck){
- if(result){
- message = "Elastic Server Transaction is success";
- }else{
- message = "Elastic Server Transaction is failed, please check the logs";
- }
- }
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message));
- JSONObject j = new JSONObject(msg);
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader(success, success);
- if(policyResult){
- JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
- response.getWriter().write(k.toString());
- }else{
- response.getWriter().write(j.toString());
- }
- }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);
- }
- }
-
- @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;
- PolicyIndexType decision = PolicyIndexType.decision;
- PolicyIndexType all = PolicyIndexType.all;
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- String dictionaryType = root.get("type").textValue();
- 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:
- }
-
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader(success, success);
- JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
- response.getWriter().write(k.toString());
- }catch(Exception e){
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
- LOGGER.error(e);
- }
- return null;
- }
- //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)){
- 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++){
- 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");
- }
- return policyList;
- }
-
- public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) {
- return ElkConnector.singleton.search(type, text, searchKeyValue);
- }
-
+ @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
+ public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
+ try{
+ String message="";
+ boolean result = false;
+ boolean policyResult = false;
+ boolean validationCheck = true;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ PolicyElasticSearchController controller = new PolicyElasticSearchController();
+ Map<String, String> searchKeyValue = new HashMap<>();
+ List<String> policyList = new ArrayList<>();
+ if(request.getParameter("policyName") != null){
+ String policyName = request.getParameter("policyName");
+ policyData.setNewFileName(policyName);
+ if("delete".equalsIgnoreCase(request.getParameter(action))){
+ result = controller.deleteElk(policyData);
+ }else{
+ result = controller.updateElk(policyData);
+ }
+ }
+ if("search".equalsIgnoreCase(request.getParameter(action))){
+ try {
+ JsonNode root = mapper.readTree(request.getReader());
+ SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class);
+
+ String policyType = searchData.getPolicyType();
+
+ 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){
+ 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];
+ validationCheck = false;
+ }
+ 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;
+ validationCheck = false;
+ }
+
+ if(searchData.getClosedLooppolicyType() != null){
+ String closedLoopType;
+ if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){
+ closedLoopType = "ClosedLoop_Fault";
+ }else{
+ closedLoopType = "ClosedLoop_PM";
+ }
+ searchKeyValue.put("configPolicyType", closedLoopType);
+ }
+ if(searchData.getOnapName() != null){
+ searchKeyValue.put("onapName", searchData.getOnapName());
+ }
+ if(searchData.getD2Service() != null){
+ String d2Service = searchData.getD2Service().trim();
+ if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){
+ d2Service = "trinity";
+ }else if("vUSP".equalsIgnoreCase(d2Service)){
+ d2Service = "vUSP";
+ }else if("MCR".equalsIgnoreCase(d2Service)){
+ d2Service = "mcr";
+ }else if("Gamma".equalsIgnoreCase(d2Service)){
+ d2Service = "gamma";
+ }else if("vDNS".equalsIgnoreCase(d2Service)){
+ d2Service = "vDNS";
+ }
+ searchKeyValue.put("jsonBodyData."+d2Service+"", "true");
+ }
+ if(searchData.getVnfType() != null){
+ searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*");
+ }
+ if(searchData.getPolicyStatus() != null){
+ searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*");
+ }
+ if(searchData.getVproAction() != null){
+ searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*");
+ }
+ if(searchData.getServiceType() != null){
+ searchKeyValue.put("serviceType", searchData.getServiceType());
+ }
+ if(searchData.getBindTextSearch() != null){
+ searchKeyValue.put(searchData.getBindTextSearch(), searchText);
+ searchText = null;
+ }
+ PolicyIndexType type = null;
+ if(policyType != null){
+ if(action.equalsIgnoreCase(policyType)){
+ type = ElkConnector.PolicyIndexType.action;
+ }else if(decision.equalsIgnoreCase(policyType)){
+ type = ElkConnector.PolicyIndexType.decision;
+ }else if(config.equalsIgnoreCase(policyType)){
+ type = ElkConnector.PolicyIndexType.config;
+ }else if("closedloop".equalsIgnoreCase(policyType)){
+ type = ElkConnector.PolicyIndexType.closedloop;
+ }else{
+ type = ElkConnector.PolicyIndexType.all;
+ }
+ }else{
+ type = ElkConnector.PolicyIndexType.all;
+ }
+ if(validationCheck){
+ JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
+ 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++){
+ 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");
+ }
+ }
+ }catch(Exception e){
+ LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
+ }
+ }
+ if(validationCheck){
+ if(result){
+ message = "Elastic Server Transaction is success";
+ }else{
+ message = "Elastic Server Transaction is failed, please check the logs";
+ }
+ }
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message));
+ JSONObject j = new JSONObject(msg);
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader(success, success);
+ if(policyResult){
+ JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
+ response.getWriter().write(k.toString());
+ }else{
+ response.getWriter().write(j.toString());
+ }
+ }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);
+ }
+ }
+
+ @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;
+ PolicyIndexType decision = PolicyIndexType.decision;
+ PolicyIndexType all = PolicyIndexType.all;
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ String dictionaryType = root.get("type").textValue();
+ 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:
+ }
+
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader(success, success);
+ JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
+ response.getWriter().write(k.toString());
+ }catch(Exception e){
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(PolicyUtils.CATCH_EXCEPTION);
+ LOGGER.error(e);
+ }
+ return null;
+ }
+
+ //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)){
+ 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++){
+ 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");
+ }
+ return policyList;
+ }
+
+ public JestResult search(PolicyIndexType type, String text, Map<String, String> 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 58c89f781..9338cdbbd 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
@@ -20,32 +20,32 @@
package org.onap.policy.pap.xacml.rest.elk.client;
public class PolicyLocator {
- public final String policyType;
- public final String policyName;
- public final String owner;
- public final String scope;
- public final String policyId;
- public final String version;
-
- public PolicyLocator(String policyType, String policyName,
- String owner, String scope, String policyId,
- String version) {
- this.policyType = policyType;
- this.policyName= policyName;
- this.owner = owner;
- this.scope = scope;
- this.policyId = policyId;
- this.version = version;
- }
-
- public String toString() {
- return "[" +
- this.owner + "|" +
- this.scope + "|" +
- this.policyType + "|" +
- this.policyName + "|" +
- this.policyId + "|" +
- "v" + this.version + "|" + "]";
-
- }
+ public final String policyType;
+ public final String policyName;
+ public final String owner;
+ public final String scope;
+ public final String policyId;
+ public final String version;
+
+ public PolicyLocator(String policyType, String policyName,
+ String owner, String scope, String policyId,
+ String version) {
+ this.policyType = policyType;
+ this.policyName= policyName;
+ this.owner = owner;
+ this.scope = scope;
+ this.policyId = policyId;
+ this.version = version;
+ }
+
+ public String toString() {
+ 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 db7711039..cc9cc16a0 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
@@ -32,66 +32,66 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup;
public class APIRequestHandler {
- private OnapPDPGroup newGroup;
+ private OnapPDPGroup newGroup;
- public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{
- // Request from the API to get Dictionary Items
- if ("api".equalsIgnoreCase(apiflag)) {
- DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance();
- dictionaryHandler.doDictionaryAPIGet(request, response);
- return;
- }
- // Request from the API to get the ActiveVersion from the PolicyVersion table
- if ("version".equalsIgnoreCase(apiflag)){
- PushPolicyHandler pushHandler = new PushPolicyHandler();
- pushHandler.getActiveVersion(request, response);
- return;
- }
- // Request from the API to get the URI from the gitpath
- if ("uri".equalsIgnoreCase(apiflag)){
- PushPolicyHandler pushHandler = new PushPolicyHandler();
- pushHandler.getSelectedURI(request, response);
- return;
- }
- if ("getMetrics".equalsIgnoreCase(apiflag)){
- MetricService.doGetPolicyMetrics(response);
- return;
- }
- }
+ public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{
+ // Request from the API to get Dictionary Items
+ if ("api".equalsIgnoreCase(apiflag)) {
+ DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance();
+ dictionaryHandler.doDictionaryAPIGet(request, response);
+ return;
+ }
+ // Request from the API to get the ActiveVersion from the PolicyVersion table
+ if ("version".equalsIgnoreCase(apiflag)){
+ PushPolicyHandler pushHandler = new PushPolicyHandler();
+ pushHandler.getActiveVersion(request, response);
+ return;
+ }
+ // Request from the API to get the URI from the gitpath
+ if ("uri".equalsIgnoreCase(apiflag)){
+ PushPolicyHandler pushHandler = new PushPolicyHandler();
+ pushHandler.getSelectedURI(request, response);
+ return;
+ }
+ if ("getMetrics".equalsIgnoreCase(apiflag)){
+ MetricService.doGetPolicyMetrics(response);
+ return;
+ }
+ }
- public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException {
- if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service) || "OPTIMIZATION".equalsIgnoreCase(service)){
- ImportService importService = new ImportService();
- importService.doImportMicroServicePut(request, response);
- return;
- }
- if ("dictionaryItem".equalsIgnoreCase(service)) {
- DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance();
- dictionaryHandler.doDictionaryAPIPut(request, response);
- return;
- } else {
- SavePolicyHandler savePolicy = SavePolicyHandler.getInstance();
- savePolicy.doPolicyAPIPut(request, response);
- }
- }
+ public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException {
+ if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service) || "OPTIMIZATION".equalsIgnoreCase(service)){
+ ImportService importService = new ImportService();
+ importService.doImportMicroServicePut(request, response);
+ return;
+ }
+ if ("dictionaryItem".equalsIgnoreCase(service)) {
+ DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance();
+ dictionaryHandler.doDictionaryAPIPut(request, response);
+ return;
+ } else {
+ SavePolicyHandler savePolicy = SavePolicyHandler.getInstance();
+ savePolicy.doPolicyAPIPut(request, response);
+ }
+ }
- public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext, String apiflag) throws IOException, SQLException{
- DeleteHandler deleteHandler = DeleteHandler.getInstance();
- if ("deletePapApi".equalsIgnoreCase(apiflag)) {
- deleteHandler.doAPIDeleteFromPAP(request, response);
- return;
- } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) {
- deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext);
- setNewGroup(deleteHandler.getDeletedGroup());
- return;
- }
- }
-
- private void setNewGroup(OnapPDPGroup newGroup) {
- this.newGroup = newGroup;
- }
+ public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext, String apiflag) throws IOException, SQLException{
+ DeleteHandler deleteHandler = DeleteHandler.getInstance();
+ if ("deletePapApi".equalsIgnoreCase(apiflag)) {
+ deleteHandler.doAPIDeleteFromPAP(request, response);
+ return;
+ } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) {
+ deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext);
+ setNewGroup(deleteHandler.getDeletedGroup());
+ return;
+ }
+ }
- public OnapPDPGroup getNewGroup() {
- return newGroup;
- }
+ private void setNewGroup(OnapPDPGroup newGroup) {
+ this.newGroup = newGroup;
+ }
+
+ public OnapPDPGroup getNewGroup() {
+ return newGroup;
+ }
}
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 f3dda33fc..e2c348239 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
@@ -59,429 +59,429 @@ import com.att.research.xacml.util.XACMLProperties;
public class DeleteHandler {
- private OnapPDPGroup newgroup;
- private static Logger logger = FlexLogger.getLogger(DeleteHandler.class);
- public static final String POLICY_IN_PDP = "PolicyInPDP";
- public static final String ERROR = "error";
- public static final String UNKNOWN = "unknown";
- private static final String REGEX = "[0-9a-zA-Z._]*";
+ private OnapPDPGroup newgroup;
+ private static Logger logger = FlexLogger.getLogger(DeleteHandler.class);
+ public static final String POLICY_IN_PDP = "PolicyInPDP";
+ public static final String ERROR = "error";
+ public static final String UNKNOWN = "unknown";
+ private static final String REGEX = "[0-9a-zA-Z._]*";
- public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
- // get the request content into a String
- String json = null;
- java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
- scanner.useDelimiter("\\A");
- json = scanner.hasNext() ? scanner.next() : "";
- scanner.close();
- PolicyLogger.info("JSON request from API to Delete Policy from the PAP: " + json);
- // convert Object sent as JSON into local object
- StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
- String policyName = policy.getPolicyName();
- Boolean policyVersionDeleted = false;
- String removeXMLExtension;
- int currentVersion;
- String removeVersionExtension;
- String splitPolicyName = null;
- String[] split = null;
- String status = ERROR;
- PolicyEntity policyEntity = null;
- JPAUtils jpaUtils = null;
+ public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
+ // get the request content into a String
+ String json = null;
+ java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+ PolicyLogger.info("JSON request from API to Delete Policy from the PAP: " + json);
+ // convert Object sent as JSON into local object
+ StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
+ String policyName = policy.getPolicyName();
+ Boolean policyVersionDeleted = false;
+ String removeXMLExtension;
+ int currentVersion;
+ String removeVersionExtension;
+ String splitPolicyName = null;
+ String[] split = null;
+ String status = ERROR;
+ PolicyEntity policyEntity = null;
+ JPAUtils jpaUtils = null;
- String papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
- String papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
- String papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
- String papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
- Connection con = null;
-
- try {
- jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
- response.addHeader(ERROR, "jpautils");
- response.addHeader("operation", "delete");
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return;
- }
- if (jpaUtils.dbLockdownIgnoreErrors()) {
- PolicyLogger.warn("Policies are locked down");
- response.addHeader("operation", "delete");
- response.addHeader("lockdown", "true");
- response.setStatus(HttpServletResponse.SC_ACCEPTED);
- return;
- }
- EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
- Query policyEntityQuery = null;
- try{
- if(policyName.endsWith(".xml")){
- removeXMLExtension = policyName.replace(".xml", "");
- currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf('.')+1));
- removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf('.'));
- boolean queryCheck = true;
- if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
- if(policyName.contains("Config_")){
- splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_");
- }else if(policyName.contains("Action_")){
- splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_");
- }else if(policyName.contains("Decision_")){
- splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_");
- }
- if(splitPolicyName != null){
- split = splitPolicyName.split(":");
- }else{
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname.");
- response.addHeader(ERROR, UNKNOWN);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
- return;
- }
- policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope");
- }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
- if(policyName.contains("Config_")){
- splitPolicyName = policyName.replace(".Config_", ":Config_");
- }else if(policyName.contains("Action_")){
- splitPolicyName = policyName.replace(".Action_", ":Action_");
- }else if(policyName.contains("Decision_")){
- splitPolicyName = policyName.replace(".Decision_", ":Decision_");
- }
- split = splitPolicyName.split(":");
- queryCheck = false;
- policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope");
- }
-
- if(queryCheck){
- policyEntityQuery.setParameter("pName", "%"+split[1]+"%");
- }else{
- policyEntityQuery.setParameter("pName", split[1]);
- }
-
- policyEntityQuery.setParameter("pScope", split[0]);
- List<?> peResult = policyEntityQuery.getResultList();
- if(!peResult.isEmpty()){
- Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
- getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator));
- List<?> pvResult = getPolicyVersion.getResultList();
- PolicyVersion pVersion = (PolicyVersion) pvResult.get(0);
- int newVersion = 0;
- em.getTransaction().begin();
- Class.forName(papDbDriver);
- con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
-
- if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
- boolean groupCheck = checkPolicyGroupEntity(con, peResult);
- if(!groupCheck){
- for(Object peData : peResult){
- policyEntity = (PolicyEntity) peData;
- status = deletePolicyEntityData(em, policyEntity);
- }
- }else{
- status = POLICY_IN_PDP;
- }
- if(status.equals(ERROR)){
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
- response.addHeader(ERROR, UNKNOWN);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
- return;
- }else if(status.equals(POLICY_IN_PDP)){
- PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
- response.addHeader(ERROR, POLICY_IN_PDP);
- response.setStatus(HttpServletResponse.SC_CONFLICT);
- return;
- }else{
- try{
- policyVersionDeleted = true;
- em.remove(pVersion);
- }catch(Exception e){
- logger.error(e.getMessage(),e);
- policyVersionDeleted = false;
- }
- }
- }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){
- boolean groupCheck = checkPolicyGroupEntity(con, peResult);
- if(!groupCheck){
- policyEntity = (PolicyEntity) peResult.get(0);
- status = deletePolicyEntityData(em, policyEntity);
- }else{
- status = POLICY_IN_PDP;
- }
-
- if(ERROR.equals(status)){
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
- response.addHeader(ERROR, UNKNOWN);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
- return;
- }else if(POLICY_IN_PDP.equals(status)){
- PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
- response.addHeader(ERROR, POLICY_IN_PDP);
- response.setStatus(HttpServletResponse.SC_CONFLICT);
- return;
- }else{
- if(currentVersion > 1){
- if(!peResult.isEmpty()){
- for(Object object : peResult){
- policyEntity = (PolicyEntity) object;
- String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
- int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
- if(policyEntityVersion > newVersion){
- newVersion = policyEntityVersion-1;
- }
- }
- }
- pVersion.setActiveVersion(newVersion);
- pVersion.setHigherVersion(newVersion);
- try{
- policyVersionDeleted = true;
- em.persist(pVersion);
- }catch(Exception e){
- logger.error(e.getMessage(),e);
- policyVersionDeleted = false;
- }
- }else{
- try{
- policyVersionDeleted = true;
- em.remove(pVersion);
- }catch(Exception e){
- logger.error(e.getMessage(),e);
- policyVersionDeleted = false;
- }
- }
- }
- }
- }else{
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
- response.addHeader(ERROR, UNKNOWN);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
- return;
- }
- }
- em.getTransaction().commit();
- }catch(Exception e){
- em.getTransaction().rollback();
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
- response.addHeader(ERROR, "deleteDB");
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return;
- } finally {
- em.close();
- if(con != null){
- con.close();
- }
- }
+ String papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
+ String papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
+ String papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
+ String papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
+ Connection con = null;
- if (policyVersionDeleted) {
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", "success");
- response.addHeader("operation", "delete");
- return;
- } else {
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
- response.addHeader(ERROR, UNKNOWN);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
- return;
- }
- }
-
- public static String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity){
- PolicyElasticSearchController controller = new PolicyElasticSearchController();
- PolicyRestAdapter policyData = new PolicyRestAdapter();
- String policyName = policyEntity.getPolicyName();
- try{
- if(policyName.contains("Config_")){
- em.remove(policyEntity.getConfigurationData());
- }else if(policyName.contains("Action_")){
- em.remove(policyEntity.getActionBodyEntity());
- }
- String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
- policyData.setNewFileName(searchPolicyName);
- controller.deleteElk(policyData);
- em.remove(policyEntity);
- }catch(Exception e){
- logger.error(e.getMessage(),e);
- return ERROR;
- }
- return "success";
- }
-
- public static boolean checkPolicyGroupEntity(Connection con, List<?> peResult) throws SQLException{
- for(Object peData : peResult){
- PolicyEntity policyEntity = (PolicyEntity) peData;
- try(Statement st = con.createStatement();
- ResultSet rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'")){
- boolean gEntityList = rs.next();
- if(gEntityList){
- return true;
- }
- }
- }
- return false;
- }
+ try {
+ jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
+ response.addHeader(ERROR, "jpautils");
+ response.addHeader("operation", "delete");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ }
+ if (jpaUtils.dbLockdownIgnoreErrors()) {
+ PolicyLogger.warn("Policies are locked down");
+ response.addHeader("operation", "delete");
+ response.addHeader("lockdown", "true");
+ response.setStatus(HttpServletResponse.SC_ACCEPTED);
+ return;
+ }
+ EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
+ Query policyEntityQuery = null;
+ try{
+ if(policyName.endsWith(".xml")){
+ removeXMLExtension = policyName.replace(".xml", "");
+ currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf('.')+1));
+ removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf('.'));
+ boolean queryCheck = true;
+ if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
+ if(policyName.contains("Config_")){
+ splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_");
+ }else if(policyName.contains("Action_")){
+ splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_");
+ }else if(policyName.contains("Decision_")){
+ splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_");
+ }
+ if(splitPolicyName != null){
+ split = splitPolicyName.split(":");
+ }else{
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname.");
+ response.addHeader(ERROR, UNKNOWN);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope");
+ }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
+ if(policyName.contains("Config_")){
+ splitPolicyName = policyName.replace(".Config_", ":Config_");
+ }else if(policyName.contains("Action_")){
+ splitPolicyName = policyName.replace(".Action_", ":Action_");
+ }else if(policyName.contains("Decision_")){
+ splitPolicyName = policyName.replace(".Decision_", ":Decision_");
+ }
+ split = splitPolicyName.split(":");
+ queryCheck = false;
+ policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope");
+ }
- public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException {
-
- String policyName = request.getParameter("policyName");
- String groupId = request.getParameter("groupId");
- String responseString = null;
-
- if(groupId != null && !groupId.matches(REGEX) ){
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader("error",ERROR);
- response.addHeader("message", "Group Id is not valid");
- return;
- }
-
- PolicyLogger.info("JSON request from API to Delete Policy from the PDP: " + policyName);
+ if(queryCheck){
+ policyEntityQuery.setParameter("pName", "%"+split[1]+"%");
+ }else{
+ policyEntityQuery.setParameter("pName", split[1]);
+ }
- // for PUT operations the group may or may not need to exist before the operation can be done
- OnapPDPGroup group = null;
- try {
- group = XACMLPapServlet.getPAPEngine().getGroup(groupId);
- } catch (PAPException e) {
- PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e);
- }
- if (group == null) {
- String message = "Unknown groupId '" + groupId + "'.";
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- response.addHeader(ERROR, "UnknownGroup");
- response.addHeader("message", message);
- response.setStatus(HttpServletResponse.SC_NOT_FOUND);
- return;
- } else {
- loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
- if (policyName.contains("xml")) {
- PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue.");
- } else {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
- + "policyName must be the full name of the file to be deleted including version and extension";
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
- + "policyName must be the full name of the file to be deleted including version and extension");
- response.addHeader(ERROR, message);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- return;
- }
- RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
- PDPPolicy policy = group.getPolicy(policyName);
- if (policy != null) {
-
- if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
- if (preSafetyCheck(policy)) {
- PolicyLogger.debug("Precheck Successful.");
- }
- }
- PolicyLogger.info("Preparing to remove policy from group: " + group.getId());
- removePolicy.prepareToRemove(policy);
- OnapPDPGroup updatedGroup = removePolicy.getUpdatedObject();
- responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
- } else {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
- PolicyLogger.error(message);
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
- response.addHeader(ERROR, message);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- return;
- }
- }
- if (responseString.equals("success")) {
- loggingContext.transactionEnded();
- PolicyLogger.info("Policy successfully deleted!");
- PolicyLogger.audit("Policy successfully deleted!");
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", "success");
- response.addHeader("operation", "delete");
- return;
- } else if (responseString.equals("No Group")) {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader(ERROR, "groupUpdate");
- response.addHeader("message", message);
- return;
- } else if (responseString.equals("DB Error")) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader(ERROR, "deleteDB");
- return;
- } else {
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
- response.addHeader(ERROR, UNKNOWN);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
- return;
- }
- }
+ policyEntityQuery.setParameter("pScope", split[0]);
+ List<?> peResult = policyEntityQuery.getResultList();
+ if(!peResult.isEmpty()){
+ Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
+ getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator));
+ List<?> pvResult = getPolicyVersion.getResultList();
+ PolicyVersion pVersion = (PolicyVersion) pvResult.get(0);
+ int newVersion = 0;
+ em.getTransaction().begin();
+ Class.forName(papDbDriver);
+ con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
- private String deletePolicyFromPDPGroup (OnapPDPGroup group, ONAPLoggingContext loggingContext){
- PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
- String response = null;
- loggingContext.setServiceName("API:PAP.DeleteHandler");
- OnapPDPGroup existingGroup = null;
- try {
- existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId());
- } catch (PAPException e1) {
- PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1);
- }
- if (!(group instanceof StdPDPGroup) || existingGroup == null || !(group.getId().equals(existingGroup.getId()))) {
- String existingID = null;
- if(existingGroup != null){
- existingID = existingGroup.getId();
- }
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingID + " objectFromJSON="+group);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- response = "No Group";
- return response;
- }
- // The Path on the PAP side is not carried on the RESTful interface with the AC
- // (because it is local to the PAP)
- // so we need to fill that in before submitting the group for update
- ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
- try{
- acPutTransaction.updateGroup(group, "XACMLPapServlet.doDelete");
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
- +"group="+existingGroup.getId());
- response = "DB Error";
- return response;
- }
- try {
- XACMLPapServlet.getPAPEngine().updateGroup(group);
- } catch (PAPException e) {
- PolicyLogger.error("Exception occured While Updating PDP Groups"+e);
- response = "error in updateGroup method";
- }
- PolicyLogger.debug("Group '" + group.getId() + "' updated");
- acPutTransaction.commitTransaction();
- // Group changed, which might include changing the policies
- try {
- newgroup = existingGroup;
- } catch (Exception e) {
- PolicyLogger.error("Exception occured in Group Change Method"+e);
- response = "error in groupChanged method";
- }
- if (response==null){
- response = "success";
- loggingContext.transactionEnded();
- PolicyLogger.audit("Policy successfully deleted!");
- }
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Ended");
- return response;
- }
-
- public OnapPDPGroup getDeletedGroup(){
- return newgroup;
- }
-
- public boolean preSafetyCheck(PDPPolicy policy) {
- return true;
- }
-
- public static DeleteHandler getInstance() {
- try {
- Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName()));
- return (DeleteHandler) deleteHandler.newInstance();
- } catch (Exception e) {
- logger.error(e.getMessage(),e);
- }
- return null;
- }
+ if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
+ boolean groupCheck = checkPolicyGroupEntity(con, peResult);
+ if(!groupCheck){
+ for(Object peData : peResult){
+ policyEntity = (PolicyEntity) peData;
+ status = deletePolicyEntityData(em, policyEntity);
+ }
+ }else{
+ status = POLICY_IN_PDP;
+ }
+ if(status.equals(ERROR)){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
+ response.addHeader(ERROR, UNKNOWN);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }else if(status.equals(POLICY_IN_PDP)){
+ PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
+ response.addHeader(ERROR, POLICY_IN_PDP);
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ return;
+ }else{
+ try{
+ policyVersionDeleted = true;
+ em.remove(pVersion);
+ }catch(Exception e){
+ logger.error(e.getMessage(),e);
+ policyVersionDeleted = false;
+ }
+ }
+ }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){
+ boolean groupCheck = checkPolicyGroupEntity(con, peResult);
+ if(!groupCheck){
+ policyEntity = (PolicyEntity) peResult.get(0);
+ status = deletePolicyEntityData(em, policyEntity);
+ }else{
+ status = POLICY_IN_PDP;
+ }
+
+ if(ERROR.equals(status)){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
+ response.addHeader(ERROR, UNKNOWN);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }else if(POLICY_IN_PDP.equals(status)){
+ PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
+ response.addHeader(ERROR, POLICY_IN_PDP);
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ return;
+ }else{
+ if(currentVersion > 1){
+ if(!peResult.isEmpty()){
+ for(Object object : peResult){
+ policyEntity = (PolicyEntity) object;
+ String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
+ int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
+ if(policyEntityVersion > newVersion){
+ newVersion = policyEntityVersion-1;
+ }
+ }
+ }
+ pVersion.setActiveVersion(newVersion);
+ pVersion.setHigherVersion(newVersion);
+ try{
+ policyVersionDeleted = true;
+ em.persist(pVersion);
+ }catch(Exception e){
+ logger.error(e.getMessage(),e);
+ policyVersionDeleted = false;
+ }
+ }else{
+ try{
+ policyVersionDeleted = true;
+ em.remove(pVersion);
+ }catch(Exception e){
+ logger.error(e.getMessage(),e);
+ policyVersionDeleted = false;
+ }
+ }
+ }
+ }
+ }else{
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
+ response.addHeader(ERROR, UNKNOWN);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ }
+ em.getTransaction().commit();
+ }catch(Exception e){
+ em.getTransaction().rollback();
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
+ response.addHeader(ERROR, "deleteDB");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ } finally {
+ em.close();
+ if(con != null){
+ con.close();
+ }
+ }
+
+ if (policyVersionDeleted) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ response.addHeader("operation", "delete");
+ return;
+ } else {
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
+ response.addHeader(ERROR, UNKNOWN);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ }
+
+ public static String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity){
+ PolicyElasticSearchController controller = new PolicyElasticSearchController();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ String policyName = policyEntity.getPolicyName();
+ try{
+ if(policyName.contains("Config_")){
+ em.remove(policyEntity.getConfigurationData());
+ }else if(policyName.contains("Action_")){
+ em.remove(policyEntity.getActionBodyEntity());
+ }
+ String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
+ policyData.setNewFileName(searchPolicyName);
+ controller.deleteElk(policyData);
+ em.remove(policyEntity);
+ }catch(Exception e){
+ logger.error(e.getMessage(),e);
+ return ERROR;
+ }
+ return "success";
+ }
+
+ public static boolean checkPolicyGroupEntity(Connection con, List<?> peResult) throws SQLException{
+ for(Object peData : peResult){
+ PolicyEntity policyEntity = (PolicyEntity) peData;
+ try(Statement st = con.createStatement();
+ ResultSet rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'")){
+ boolean gEntityList = rs.next();
+ if(gEntityList){
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException {
+
+ String policyName = request.getParameter("policyName");
+ String groupId = request.getParameter("groupId");
+ String responseString = null;
+
+ if(groupId != null && !groupId.matches(REGEX) ){
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error",ERROR);
+ response.addHeader("message", "Group Id is not valid");
+ return;
+ }
+
+ PolicyLogger.info("JSON request from API to Delete Policy from the PDP: " + policyName);
+
+ // for PUT operations the group may or may not need to exist before the operation can be done
+ OnapPDPGroup group = null;
+ try {
+ group = XACMLPapServlet.getPAPEngine().getGroup(groupId);
+ } catch (PAPException e) {
+ PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e);
+ }
+ if (group == null) {
+ String message = "Unknown groupId '" + groupId + "'.";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ response.addHeader(ERROR, "UnknownGroup");
+ response.addHeader("message", message);
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ return;
+ } else {
+ loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
+ if (policyName.contains("xml")) {
+ PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue.");
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
+ + "policyName must be the full name of the file to be deleted including version and extension";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
+ + "policyName must be the full name of the file to be deleted including version and extension");
+ response.addHeader(ERROR, message);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
+ RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
+ PDPPolicy policy = group.getPolicy(policyName);
+ if (policy != null) {
+
+ if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
+ if (preSafetyCheck(policy)) {
+ PolicyLogger.debug("Precheck Successful.");
+ }
+ }
+ PolicyLogger.info("Preparing to remove policy from group: " + group.getId());
+ removePolicy.prepareToRemove(policy);
+ OnapPDPGroup updatedGroup = removePolicy.getUpdatedObject();
+ responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
+ PolicyLogger.error(message);
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
+ response.addHeader(ERROR, message);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
+ }
+ if (responseString.equals("success")) {
+ loggingContext.transactionEnded();
+ PolicyLogger.info("Policy successfully deleted!");
+ PolicyLogger.audit("Policy successfully deleted!");
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ response.addHeader("operation", "delete");
+ return;
+ } else if (responseString.equals("No Group")) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader(ERROR, "groupUpdate");
+ response.addHeader("message", message);
+ return;
+ } else if (responseString.equals("DB Error")) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader(ERROR, "deleteDB");
+ return;
+ } else {
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
+ response.addHeader(ERROR, UNKNOWN);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
+ return;
+ }
+ }
+
+ private String deletePolicyFromPDPGroup (OnapPDPGroup group, ONAPLoggingContext loggingContext){
+ PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
+ String response = null;
+ loggingContext.setServiceName("API:PAP.DeleteHandler");
+ OnapPDPGroup existingGroup = null;
+ try {
+ existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId());
+ } catch (PAPException e1) {
+ PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1);
+ }
+ if (!(group instanceof StdPDPGroup) || existingGroup == null || !(group.getId().equals(existingGroup.getId()))) {
+ String existingID = null;
+ if(existingGroup != null){
+ existingID = existingGroup.getId();
+ }
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingID + " objectFromJSON="+group);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ response = "No Group";
+ return response;
+ }
+ // The Path on the PAP side is not carried on the RESTful interface with the AC
+ // (because it is local to the PAP)
+ // so we need to fill that in before submitting the group for update
+ ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
+ try{
+ acPutTransaction.updateGroup(group, "XACMLPapServlet.doDelete");
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
+ +"group="+existingGroup.getId());
+ response = "DB Error";
+ return response;
+ }
+ try {
+ XACMLPapServlet.getPAPEngine().updateGroup(group);
+ } catch (PAPException e) {
+ PolicyLogger.error("Exception occured While Updating PDP Groups"+e);
+ response = "error in updateGroup method";
+ }
+ PolicyLogger.debug("Group '" + group.getId() + "' updated");
+ acPutTransaction.commitTransaction();
+ // Group changed, which might include changing the policies
+ try {
+ newgroup = existingGroup;
+ } catch (Exception e) {
+ PolicyLogger.error("Exception occured in Group Change Method"+e);
+ response = "error in groupChanged method";
+ }
+ if (response==null){
+ response = "success";
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Policy successfully deleted!");
+ }
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Ended");
+ return response;
+ }
+
+ public OnapPDPGroup getDeletedGroup(){
+ return newgroup;
+ }
+
+ public boolean preSafetyCheck(PDPPolicy policy) {
+ return true;
+ }
+
+ public static DeleteHandler getInstance() {
+ try {
+ Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName()));
+ return (DeleteHandler) deleteHandler.newInstance();
+ } catch (Exception e) {
+ logger.error(e.getMessage(),e);
+ }
+ return 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 6aec7a9bc..89ce18835 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
@@ -28,38 +28,38 @@ 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();
+ public static final Logger logger = FlexLogger.getLogger(DictionaryHandler.class);
+ String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName();
- /*
- * Get Instance
- */
- public static DictionaryHandler getInstance(){
- try {
- Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS));
- DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance();
- return instance;
- } catch (Exception e) {
- logger.error(e.getMessage(),e);
- }
- return null;
- }
-
- /*
- * Get Equivalent for Dictionary Services.
- */
- public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response);
- /*
- * Put Equivalent for Dictionary Services.
- */
- public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response);
-
- /**
- * Can be used to extend the services.
- *
- * getflag=true indicates Get Request.
- * getflag=false indicates Put Request.
- * @return
- */
- public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag);
+ /*
+ * Get Instance
+ */
+ public static DictionaryHandler getInstance(){
+ try {
+ Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS));
+ DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance();
+ return instance;
+ } catch (Exception e) {
+ logger.error(e.getMessage(),e);
+ }
+ return null;
+ }
+
+ /*
+ * Get Equivalent for Dictionary Services.
+ */
+ public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response);
+ /*
+ * Put Equivalent for Dictionary Services.
+ */
+ public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response);
+
+ /**
+ * Can be used to extend the services.
+ *
+ * getflag=true indicates Get Request.
+ * getflag=false indicates Put Request.
+ * @return
+ */
+ public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag);
}
diff --git a/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 d0cd985a3..b90592b02 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
@@ -28,302 +28,302 @@ import org.onap.policy.pap.xacml.rest.service.DictionaryService;
import org.onap.policy.xacml.api.XACMLErrorConstants;
public class DictionaryHandlerImpl implements DictionaryHandler{
- /*
- * Get Equivalent for Dictionary Services.
- */
- public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) {
- String dictionaryType = request.getParameter("dictionaryType");
- try {
- DictionaryService dictionary = new DictionaryService();
- switch (dictionaryType) {
- case "OnapName":
- dictionary.getOnapDictionary(response);
- break;
- case "Attribute":
- dictionary.getAttributeDictionary(response);
- break;
- case "Action":
- dictionary.getActionPolicyDictionary(response);
- break;
- case "BRMSParamTemplate":
- dictionary.getBRMSParamDictionary(response);
- break;
- case "VSCLAction":
- dictionary.getVSCLAction(response);
- break;
- case "VNFType":
- dictionary.getVnfType(response);
- break;
- case "PEPOptions":
- dictionary.getPEPOptions(response);
- break;
- case "Varbind":
- dictionary.getVarbind(response);
- break;
- case "Service":
- dictionary.getServiceType(response);
- break;
- case "Site":
- dictionary.getSiteType(response);
- break;
- case "Settings":
- dictionary.getSettingsDictionary(response);
- break;
- case "RainyDayTreatments":
- dictionary.getRainyDayDictionary(response);
- break;
- case "DescriptiveScope":
- dictionary.getDescriptiveDictionary(response);
- break;
- case "ActionList":
- dictionary.getActionListDictionary(response);
- break;
- case "ProtocolList":
- dictionary.getProtocolListDictionary(response);
- break;
- case "Zone":
- dictionary.getZoneDictionary(response);
- break;
- case "SecurityZone":
- dictionary.getSecurityZoneDictionary(response);
- break;
- case "PrefixList":
- dictionary.getPrefixListDictionary(response);
- break;
- case "AddressGroup":
- dictionary.getAddressGroupDictionary(response);
- break;
- case "ServiceGroup":
- dictionary.getServiceGroupDictionary(response);
- break;
- case "ServiceList":
- dictionary.getServiceListDictionary(response);
- break;
- case "TermList":
- case "RuleList":
- case "FirewallRuleList":
- case "Term":
- dictionary.getTermListDictionary(response);
- break;
- case "MicroServiceLocation":
- dictionary.getMicroServiceLocationDictionary(response);
- break;
- case "MicroServiceConfigName":
- dictionary.getMicroServiceConfigNameDictionary(response);
- break;
- case "DCAEUUID":
- dictionary.getDCAEUUIDDictionary(response);
- break;
- case "MicroServiceModels":
- dictionary.getMicroServiceModelsDictionary(response);
- break;
- case "MicroServiceDictionary":
- dictionary.getMicroServiceDictionary(response);
- break;
- case "OptimizationModels":
- dictionary.getOptimizationModelsDictionary(response);
- break;
- case "PolicyScopeService":
- dictionary.getPSServiceDictionary(response);
- break;
- case "PolicyScopeResource":
- dictionary.getPSResourceDictionary(response);
- break;
- case "PolicyScopeType":
- dictionary.getPSTypeDictionary(response);
- break;
- case "PolicyScopeClosedLoop":
- dictionary.getPSClosedLoopDictionary(response);
- break;
- case "GroupPolicyScopeList":
- dictionary.getPSGroupScopeDictionary(response);
- break;
- case "RiskType":
- dictionary.getRiskTypeDictionary(response);
- break;
- case "SafePolicyWarning":
- dictionary.getSafePolicyWarningDictionary(response);
- break;
- default:
- extendedOptions(dictionaryType, request, response, true);
- return;
- }
- } catch (Exception e) {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage();
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database.");
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader("error", "dictionaryDBQuery");
- response.addHeader("error", message);
- return;
- }
- }
-
- /**
- * Can be used to extend the services.
- *
- * getflag=true indicates Get Request.
- * getflag=false indicates Put Request.
- * @return
- */
- public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) {
- // Default code
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request.";
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request.");
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.setHeader("error", "dictionary");
- response.addHeader("error", message);
- return null;
- }
+ /*
+ * Get Equivalent for Dictionary Services.
+ */
+ public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) {
+ String dictionaryType = request.getParameter("dictionaryType");
+ try {
+ DictionaryService dictionary = new DictionaryService();
+ switch (dictionaryType) {
+ case "OnapName":
+ dictionary.getOnapDictionary(response);
+ break;
+ case "Attribute":
+ dictionary.getAttributeDictionary(response);
+ break;
+ case "Action":
+ dictionary.getActionPolicyDictionary(response);
+ break;
+ case "BRMSParamTemplate":
+ dictionary.getBRMSParamDictionary(response);
+ break;
+ case "VSCLAction":
+ dictionary.getVSCLAction(response);
+ break;
+ case "VNFType":
+ dictionary.getVnfType(response);
+ break;
+ case "PEPOptions":
+ dictionary.getPEPOptions(response);
+ break;
+ case "Varbind":
+ dictionary.getVarbind(response);
+ break;
+ case "Service":
+ dictionary.getServiceType(response);
+ break;
+ case "Site":
+ dictionary.getSiteType(response);
+ break;
+ case "Settings":
+ dictionary.getSettingsDictionary(response);
+ break;
+ case "RainyDayTreatments":
+ dictionary.getRainyDayDictionary(response);
+ break;
+ case "DescriptiveScope":
+ dictionary.getDescriptiveDictionary(response);
+ break;
+ case "ActionList":
+ dictionary.getActionListDictionary(response);
+ break;
+ case "ProtocolList":
+ dictionary.getProtocolListDictionary(response);
+ break;
+ case "Zone":
+ dictionary.getZoneDictionary(response);
+ break;
+ case "SecurityZone":
+ dictionary.getSecurityZoneDictionary(response);
+ break;
+ case "PrefixList":
+ dictionary.getPrefixListDictionary(response);
+ break;
+ case "AddressGroup":
+ dictionary.getAddressGroupDictionary(response);
+ break;
+ case "ServiceGroup":
+ dictionary.getServiceGroupDictionary(response);
+ break;
+ case "ServiceList":
+ dictionary.getServiceListDictionary(response);
+ break;
+ case "TermList":
+ case "RuleList":
+ case "FirewallRuleList":
+ case "Term":
+ dictionary.getTermListDictionary(response);
+ break;
+ case "MicroServiceLocation":
+ dictionary.getMicroServiceLocationDictionary(response);
+ break;
+ case "MicroServiceConfigName":
+ dictionary.getMicroServiceConfigNameDictionary(response);
+ break;
+ case "DCAEUUID":
+ dictionary.getDCAEUUIDDictionary(response);
+ break;
+ case "MicroServiceModels":
+ dictionary.getMicroServiceModelsDictionary(response);
+ break;
+ case "MicroServiceDictionary":
+ dictionary.getMicroServiceDictionary(response);
+ break;
+ case "OptimizationModels":
+ dictionary.getOptimizationModelsDictionary(response);
+ break;
+ case "PolicyScopeService":
+ dictionary.getPSServiceDictionary(response);
+ break;
+ case "PolicyScopeResource":
+ dictionary.getPSResourceDictionary(response);
+ break;
+ case "PolicyScopeType":
+ dictionary.getPSTypeDictionary(response);
+ break;
+ case "PolicyScopeClosedLoop":
+ dictionary.getPSClosedLoopDictionary(response);
+ break;
+ case "GroupPolicyScopeList":
+ dictionary.getPSGroupScopeDictionary(response);
+ break;
+ case "RiskType":
+ dictionary.getRiskTypeDictionary(response);
+ break;
+ case "SafePolicyWarning":
+ dictionary.getSafePolicyWarningDictionary(response);
+ break;
+ default:
+ extendedOptions(dictionaryType, request, response, true);
+ return;
+ }
+ } catch (Exception e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage();
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database.");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error", "dictionaryDBQuery");
+ response.addHeader("error", message);
+ return;
+ }
+ }
- public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) {
- String result = null;
- String dictionaryType = request.getParameter("dictionaryType");
- String operation = request.getParameter("operation");
- try {
- DictionaryService dictionary = new DictionaryService();
- switch (dictionaryType) {
- case "OnapName":
- result = dictionary.saveOnapDictionary(request, response);
- break;
- case "Attribute":
- result = dictionary.saveAttributeDictionary(request, response);
- break;
- case "Action":
- result = dictionary.saveActionPolicyDictionary(request, response);
- break;
- case "BRMSParamTemplate":
- result = dictionary.saveBRMSParamDictionary(request, response);
- break;
- case "VSCLAction":
- result = dictionary.saveVSCLAction(request, response);
- break;
- case "VNFType":
- result = dictionary.saveVnfType(request, response);
- break;
- case "PEPOptions":
- result = dictionary.savePEPOptions(request, response);
- break;
- case "Varbind":
- result = dictionary.saveVarbind(request, response);
- break;
- case "Service":
- result = dictionary.saveServiceType(request, response);
- break;
- case "Site":
- result = dictionary.saveSiteType(request, response);
- break;
- case "Settings":
- result = dictionary.saveSettingsDictionary(request, response);
- break;
- case "RainyDayTreatments":
- result = dictionary.saveRainyDayDictionary(request, response);
- break;
- case "DescriptiveScope":
- result = dictionary.saveDescriptiveDictionary(request, response);
- break;
- case "ActionList":
- result = dictionary.saveActionListDictionary(request, response);
- break;
- case "ProtocolList":
- result = dictionary.saveProtocolListDictionary(request, response);
- break;
- case "Zone":
- result = dictionary.saveZoneDictionary(request, response);
- break;
- case "SecurityZone":
- result = dictionary.saveSecurityZoneDictionary(request, response);
- break;
- case "PrefixList":
- result = dictionary.savePrefixListDictionary(request, response);
- break;
- case "AddressGroup":
- result = dictionary.saveAddressGroupDictionary(request, response);
- break;
- case "ServiceGroup":
- result = dictionary.saveServiceGroupDictionary(request, response);
- break;
- case "ServiceList":
- result = dictionary.saveServiceListDictionary(request, response);
- break;
- case "TermList":
- case "RuleList":
- case "FirewallRuleList":
- case "Term":
- result = dictionary.saveTermListDictionary(request, response);
- break;
- case "MicroServiceLocation":
- result = dictionary.saveMicroServiceLocationDictionary(request, response);
- break;
- case "MicroServiceConfigName":
- result = dictionary.saveMicroServiceConfigNameDictionary(request, response);
- break;
- case "DCAEUUID":
- result = dictionary.saveDCAEUUIDDictionary(request, response);
- break;
- case "MicroServiceModels":
- result = dictionary.saveMicroServiceModelsDictionary(request, response);
- break;
- case "MicroServiceDictionary":
- result = dictionary.saveMicroServiceDictionary(request, response);
- break;
- case "OptimizationModels":
- result = dictionary.saveOptimizationModelsDictionary(request, response);
- break;
- case "PolicyScopeService":
- result = dictionary.savePSServiceDictionary(request, response);
- break;
- case "PolicyScopeResource":
- result = dictionary.savePSResourceDictionary(request, response);
- break;
- case "PolicyScopeType":
- result = dictionary.savePSTypeDictionary(request, response);
- break;
- case "PolicyScopeClosedLoop":
- result = dictionary.savePSClosedLoopDictionary(request, response);
- break;
- case "GroupPolicyScopeList":
- result = dictionary.savePSGroupScopeDictionary(request, response);
- break;
- case "RiskType":
- result = dictionary.saveRiskTypeDictionary(request, response);
- break;
- case "SafePolicyWarning":
- result = dictionary.saveSafePolicyWarningDictionary(request, response);
- break;
- default:
- result = extendedOptions(dictionaryType, request, response, false);
- if(result==null){
- return;
- }else{
- break;
- }
- }
- } catch (Exception e) {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage();
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database.");
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader("error", message);
- return;
- }
- if (result.equalsIgnoreCase("Success")) {
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", "success");
- if (operation.equalsIgnoreCase("update")) {
- response.addHeader("operation", "updateDictionary");
- } else {
- response.addHeader("operation", "createDictionary");
- }
- } else if (result.equalsIgnoreCase("Duplicate")) {
- response.setStatus(HttpServletResponse.SC_CONFLICT);
- response.addHeader("error", "dictionaryItemExists");
- } else if (result.equalsIgnoreCase("DuplicateGroup")) {
- response.setStatus(HttpServletResponse.SC_CONFLICT);
- response.addHeader("error", "duplicateGroup");
- } else {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database.";
- PolicyLogger.error(message);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader("error", message);
- }
- }
+ /**
+ * Can be used to extend the services.
+ *
+ * getflag=true indicates Get Request.
+ * getflag=false indicates Put Request.
+ * @return
+ */
+ public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) {
+ // Default code
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request.";
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request.");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.setHeader("error", "dictionary");
+ response.addHeader("error", message);
+ return null;
+ }
+
+ public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) {
+ String result = null;
+ String dictionaryType = request.getParameter("dictionaryType");
+ String operation = request.getParameter("operation");
+ try {
+ DictionaryService dictionary = new DictionaryService();
+ switch (dictionaryType) {
+ case "OnapName":
+ result = dictionary.saveOnapDictionary(request, response);
+ break;
+ case "Attribute":
+ result = dictionary.saveAttributeDictionary(request, response);
+ break;
+ case "Action":
+ result = dictionary.saveActionPolicyDictionary(request, response);
+ break;
+ case "BRMSParamTemplate":
+ result = dictionary.saveBRMSParamDictionary(request, response);
+ break;
+ case "VSCLAction":
+ result = dictionary.saveVSCLAction(request, response);
+ break;
+ case "VNFType":
+ result = dictionary.saveVnfType(request, response);
+ break;
+ case "PEPOptions":
+ result = dictionary.savePEPOptions(request, response);
+ break;
+ case "Varbind":
+ result = dictionary.saveVarbind(request, response);
+ break;
+ case "Service":
+ result = dictionary.saveServiceType(request, response);
+ break;
+ case "Site":
+ result = dictionary.saveSiteType(request, response);
+ break;
+ case "Settings":
+ result = dictionary.saveSettingsDictionary(request, response);
+ break;
+ case "RainyDayTreatments":
+ result = dictionary.saveRainyDayDictionary(request, response);
+ break;
+ case "DescriptiveScope":
+ result = dictionary.saveDescriptiveDictionary(request, response);
+ break;
+ case "ActionList":
+ result = dictionary.saveActionListDictionary(request, response);
+ break;
+ case "ProtocolList":
+ result = dictionary.saveProtocolListDictionary(request, response);
+ break;
+ case "Zone":
+ result = dictionary.saveZoneDictionary(request, response);
+ break;
+ case "SecurityZone":
+ result = dictionary.saveSecurityZoneDictionary(request, response);
+ break;
+ case "PrefixList":
+ result = dictionary.savePrefixListDictionary(request, response);
+ break;
+ case "AddressGroup":
+ result = dictionary.saveAddressGroupDictionary(request, response);
+ break;
+ case "ServiceGroup":
+ result = dictionary.saveServiceGroupDictionary(request, response);
+ break;
+ case "ServiceList":
+ result = dictionary.saveServiceListDictionary(request, response);
+ break;
+ case "TermList":
+ case "RuleList":
+ case "FirewallRuleList":
+ case "Term":
+ result = dictionary.saveTermListDictionary(request, response);
+ break;
+ case "MicroServiceLocation":
+ result = dictionary.saveMicroServiceLocationDictionary(request, response);
+ break;
+ case "MicroServiceConfigName":
+ result = dictionary.saveMicroServiceConfigNameDictionary(request, response);
+ break;
+ case "DCAEUUID":
+ result = dictionary.saveDCAEUUIDDictionary(request, response);
+ break;
+ case "MicroServiceModels":
+ result = dictionary.saveMicroServiceModelsDictionary(request, response);
+ break;
+ case "MicroServiceDictionary":
+ result = dictionary.saveMicroServiceDictionary(request, response);
+ break;
+ case "OptimizationModels":
+ result = dictionary.saveOptimizationModelsDictionary(request, response);
+ break;
+ case "PolicyScopeService":
+ result = dictionary.savePSServiceDictionary(request, response);
+ break;
+ case "PolicyScopeResource":
+ result = dictionary.savePSResourceDictionary(request, response);
+ break;
+ case "PolicyScopeType":
+ result = dictionary.savePSTypeDictionary(request, response);
+ break;
+ case "PolicyScopeClosedLoop":
+ result = dictionary.savePSClosedLoopDictionary(request, response);
+ break;
+ case "GroupPolicyScopeList":
+ result = dictionary.savePSGroupScopeDictionary(request, response);
+ break;
+ case "RiskType":
+ result = dictionary.saveRiskTypeDictionary(request, response);
+ break;
+ case "SafePolicyWarning":
+ result = dictionary.saveSafePolicyWarningDictionary(request, response);
+ break;
+ default:
+ result = extendedOptions(dictionaryType, request, response, false);
+ if(result==null){
+ return;
+ }else{
+ break;
+ }
+ }
+ } catch (Exception e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage();
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database.");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error", message);
+ return;
+ }
+ if (result.equalsIgnoreCase("Success")) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ if (operation.equalsIgnoreCase("update")) {
+ response.addHeader("operation", "updateDictionary");
+ } else {
+ response.addHeader("operation", "createDictionary");
+ }
+ } else if (result.equalsIgnoreCase("Duplicate")) {
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ response.addHeader("error", "dictionaryItemExists");
+ } else if (result.equalsIgnoreCase("DuplicateGroup")) {
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ response.addHeader("error", "duplicateGroup");
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database.";
+ PolicyLogger.error(message);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader("error", message);
+ }
+ }
}
diff --git a/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 6e348fb1b..4dd87e22f 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
@@ -39,86 +39,86 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import com.att.research.xacml.util.XACMLProperties;
public class PushPolicyHandler {
- private static final Logger logger = FlexLogger.getLogger(PushPolicyHandler.class);
- /*
- * Get Active Version.
- */
- public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) {
- EntityManager em = null;
- if(XACMLPapServlet.getEmf()!=null){
- em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
- }
- if (em==null){
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit());
- return;
- }
- String policyScope = request.getParameter("policyScope");
- String filePrefix = request.getParameter("filePrefix");
- String policyName = request.getParameter("policyName");
+ private static final Logger logger = FlexLogger.getLogger(PushPolicyHandler.class);
+ /*
+ * Get Active Version.
+ */
+ public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) {
+ EntityManager em = null;
+ if(XACMLPapServlet.getEmf()!=null){
+ em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
+ }
+ if (em==null){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit());
+ return;
+ }
+ String policyScope = request.getParameter("policyScope");
+ String filePrefix = request.getParameter("filePrefix");
+ String policyName = request.getParameter("policyName");
- String pvName = policyScope + File.separator + filePrefix + policyName;
- int activeVersion = 0;
+ String pvName = policyScope + File.separator + filePrefix + policyName;
+ int activeVersion = 0;
- //Get the Active Version to use in the ID
- em.getTransaction().begin();
- Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
- query.setParameter("pname", pvName);
+ //Get the Active Version to use in the ID
+ em.getTransaction().begin();
+ Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
+ query.setParameter("pname", pvName);
- @SuppressWarnings("rawtypes")
- List result = query.getResultList();
- PolicyVersion versionEntity = null;
- if (!result.isEmpty()) {
- versionEntity = (PolicyVersion) result.get(0);
- em.persist(versionEntity);
- activeVersion = versionEntity.getActiveVersion();
- em.getTransaction().commit();
- } else {
- PolicyLogger.debug("No PolicyVersion using policyName found");
- }
+ @SuppressWarnings("rawtypes")
+ List result = query.getResultList();
+ PolicyVersion versionEntity = null;
+ if (!result.isEmpty()) {
+ versionEntity = (PolicyVersion) result.get(0);
+ em.persist(versionEntity);
+ activeVersion = versionEntity.getActiveVersion();
+ em.getTransaction().commit();
+ } else {
+ PolicyLogger.debug("No PolicyVersion using policyName found");
+ }
- //clean up connection
- em.close();
- if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) {
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("version", String.valueOf(activeVersion));
- } else {
- response.setStatus(HttpServletResponse.SC_NOT_FOUND);
- }
- }
-
- /*
- * Get Selected URI path.
- */
- public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) {
- String gitPath = request.getParameter("gitPath");
- File file = new File(gitPath);
- PolicyLogger.debug("The fileItem is : " + file.toString());
- URI selectedURI = file.toURI();
- String uri = selectedURI.toString();
- if (!uri.equalsIgnoreCase("")) {
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("selectedURI", uri);
- } else {
- response.setStatus(HttpServletResponse.SC_NOT_FOUND);
- }
- }
-
- public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){
- return true;
- }
-
- public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){
- return true;
- }
-
- public static PushPolicyHandler getInstance() {
- try {
- Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName()));
- PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance();
- return instance;
- } catch (Exception e) {
- logger.error(e.getMessage(),e);
- }
- return null;
- }
+ //clean up connection
+ em.close();
+ if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("version", String.valueOf(activeVersion));
+ } else {
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ }
+ }
+
+ /*
+ * Get Selected URI path.
+ */
+ public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) {
+ String gitPath = request.getParameter("gitPath");
+ File file = new File(gitPath);
+ PolicyLogger.debug("The fileItem is : " + file.toString());
+ URI selectedURI = file.toURI();
+ String uri = selectedURI.toString();
+ if (!uri.equalsIgnoreCase("")) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("selectedURI", uri);
+ } else {
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ }
+ }
+
+ public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){
+ return true;
+ }
+
+ public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){
+ return true;
+ }
+
+ public static PushPolicyHandler getInstance() {
+ try {
+ Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName()));
+ PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance();
+ return instance;
+ } catch (Exception e) {
+ 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 6606d383b..335434fd4 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
@@ -40,127 +40,127 @@ import org.xml.sax.SAXException;
import com.att.research.xacml.util.XACMLProperties;
public class SavePolicyHandler {
- private static final Logger logger = FlexLogger.getLogger(SavePolicyHandler.class);
- private HashMap<String, String> ErrorHeaders = null;
-
- public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
- String operation = request.getParameter("operation");
- String policyType = request.getParameter("policyType");
- String apiflag = request.getParameter("apiflag");
- PolicyCreation creation = new PolicyCreation();
+ private static final Logger logger = FlexLogger.getLogger(SavePolicyHandler.class);
+ private HashMap<String, String> ErrorHeaders = null;
+
+ public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ String operation = request.getParameter("operation");
+ String policyType = request.getParameter("policyType");
+ String apiflag = request.getParameter("apiflag");
+ PolicyCreation creation = new PolicyCreation();
if ( policyType != null ) {
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- if("update".equalsIgnoreCase(operation)){
- policyAdapter.setEditPolicy(true);
- }else{
- policyAdapter.setEditPolicy(false);
- }
-
- // get the request content into a String
- String json = null;
- // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
- java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
- scanner.useDelimiter("\\A");
- json = scanner.hasNext() ? scanner.next() : "";
- scanner.close();
-
- 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);
- }
-
- // convert Object sent as JSON into local object
- StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
- //Set policyAdapter values including parentPath (Common to all policy types)
- try {
- PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter");
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ if("update".equalsIgnoreCase(operation)){
+ policyAdapter.setEditPolicy(true);
+ }else{
+ policyAdapter.setEditPolicy(false);
+ }
+
+ // get the request content into a String
+ String json = null;
+ // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
+ java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ json = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+
+ 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);
+ }
+
+ // convert Object sent as JSON into local object
+ StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
+ //Set policyAdapter values including parentPath (Common to all policy types)
+ try {
+ PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter");
policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
if(!extendedPolicyOptions(policyAdapter, response)){
- creation.savePolicy(policyAdapter, response);
+ creation.savePolicy(policyAdapter, response);
}
if ("update".equalsIgnoreCase(operation)) {
- response.addHeader("operation", "update");
- } else {
- response.addHeader("operation", "create");
- }
- } catch (Exception e1) {
- logger.error("Could not set data to policy adapter "+e1.getMessage(),e1);
- }
+ response.addHeader("operation", "update");
+ } else {
+ response.addHeader("operation", "create");
+ }
+ } catch (Exception 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{
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- policyAdapter.setApiflag(apiflag);
- /*
- * set policy adapter values for Building JSON object containing policy data
- */
- //Common among policy types
- policyAdapter.setPolicyName(policy.getPolicyName());
- policyAdapter.setPolicyDescription(policy.getPolicyDescription());
- policyAdapter.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());
- policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf());
- //Config Specific
- policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall
- policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base
- policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base
- policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop
- policyAdapter.setConfigPolicyType(policy.getConfigPolicyType());
- policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault
- policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM
- policyAdapter.setUuid(policy.getUuid()); //Micro Service
- policyAdapter.setLocation(policy.getMsLocation()); //Micro Service
- policyAdapter.setPriority(policy.getPriority()); //Micro Service
- policyAdapter.setPolicyScope(policy.getDomainDir());
- policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes
- policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes
- policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes
- policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes
- policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
+ private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ policyAdapter.setApiflag(apiflag);
+ /*
+ * set policy adapter values for Building JSON object containing policy data
+ */
+ //Common among policy types
+ policyAdapter.setPolicyName(policy.getPolicyName());
+ policyAdapter.setPolicyDescription(policy.getPolicyDescription());
+ policyAdapter.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());
+ policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf());
+ //Config Specific
+ policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall
+ policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base
+ policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base
+ policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop
+ policyAdapter.setConfigPolicyType(policy.getConfigPolicyType());
+ policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault
+ policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM
+ policyAdapter.setUuid(policy.getUuid()); //Micro Service
+ policyAdapter.setLocation(policy.getMsLocation()); //Micro Service
+ policyAdapter.setPriority(policy.getPriority()); //Micro Service
+ policyAdapter.setPolicyScope(policy.getDomainDir());
+ policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes
+ policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes
+ policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes
+ policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes
+ policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies.
policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies.
- //Action Policy Specific
- policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue
- policyAdapter.setActionPerformer(policy.getActionPerformer());
- policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels());
- policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo());
- policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1());
- policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2());
- //Decision Policy Specific
- policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
- policyAdapter.setRuleProvider(policy.getProviderComboBox());
- policyAdapter.setDomainDir(policyAdapter.getPolicyScope());
- policyAdapter.setRainydayMap(policy.getTreatments());
+ //Action Policy Specific
+ policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue
+ policyAdapter.setActionPerformer(policy.getActionPerformer());
+ policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels());
+ policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo());
+ policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1());
+ policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2());
+ //Decision Policy Specific
+ policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
+ policyAdapter.setRuleProvider(policy.getProviderComboBox());
+ policyAdapter.setDomainDir(policyAdapter.getPolicyScope());
+ policyAdapter.setRainydayMap(policy.getTreatments());
+
+ return policyAdapter;
+ }
- return policyAdapter;
- }
-
- public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){
- return false;
- }
-
- public void addErrorHeader(String key, String value){
- if(ErrorHeaders==null){
- ErrorHeaders= new HashMap<>();
- }
- ErrorHeaders.put(key, value);
- }
+ public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){
+ return false;
+ }
- public static SavePolicyHandler getInstance() {
- try {
- Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName()));
- SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance();
- return instance;
- } catch (Exception e) {
- logger.error(e.getMessage(),e);
- }
- return null;
- }
+ 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()));
+ SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance();
+ return instance;
+ } catch (Exception 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 8c891bf69..2d98b820d 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
@@ -32,74 +32,74 @@ import com.att.research.xacml.api.pap.PDPPolicy;
public class RemoveGroupPolicy {
-
- //Container from where we are fetching the policies
- private static PDPPolicyContainer policyContainer;
-
- private RemoveGroupPolicy self = this;
- private StdPDPGroup updatedObject;
- private final StdPDPGroup group;
- private boolean isSaved = false;
-
- public RemoveGroupPolicy(StdPDPGroup group) {
-
- this.group = group;
-
- }
-
- public void prepareToRemove(PDPPolicy policy) {
-
- if (this.group == null) {
- return;
- }
- setRemoveGroupPolicy(new PDPPolicyContainer(group));
-
- RemoveGroupPolicy.policyContainer.removeItem(policy);
-
- self.doSave();
-
- self.isSaved = true;
-
- }
-
- private static void setRemoveGroupPolicy(PDPPolicyContainer pdpPolicyContainer) {
+
+ //Container from where we are fetching the policies
+ private static PDPPolicyContainer policyContainer;
+
+ private RemoveGroupPolicy self = this;
+ private StdPDPGroup updatedObject;
+ private final StdPDPGroup group;
+ private boolean isSaved = false;
+
+ public RemoveGroupPolicy(StdPDPGroup group) {
+
+ this.group = group;
+
+ }
+
+ public void prepareToRemove(PDPPolicy policy) {
+
+ if (this.group == null) {
+ return;
+ }
+ setRemoveGroupPolicy(new PDPPolicyContainer(group));
+
+ RemoveGroupPolicy.policyContainer.removeItem(policy);
+
+ self.doSave();
+
+ self.isSaved = true;
+
+ }
+
+ private static void setRemoveGroupPolicy(PDPPolicyContainer pdpPolicyContainer) {
RemoveGroupPolicy.policyContainer = pdpPolicyContainer;
}
@SuppressWarnings("unchecked")
- protected void doSave() {
- if (this.group == null) {
- return;
- }
-
- StdPDPGroup updatedGroupObject = new StdPDPGroup(
- group.getId(),
- group.isDefaultGroup(),
- group.getName(),
- group.getDescription(),
- null);
-
- // replace the original set of Policies with the set from the container (possibly modified by the user)
- Set<PDPPolicy> changedPolicies = new HashSet<>();
- changedPolicies.addAll((Collection<PDPPolicy>) RemoveGroupPolicy.policyContainer.getItemIds());
- updatedGroupObject.setPolicies(changedPolicies);
- updatedGroupObject.setOnapPdps(this.group.getOnapPdps());
-
- // replace the original set of PIP Configs with the set from the container
- updatedGroupObject.setPipConfigs(this.group.getPipConfigs());
-
- // copy those things that the user cannot change from the original to the new object
- updatedGroupObject.setStatus(this.group.getStatus());
-
- this.updatedObject = updatedGroupObject;
- }
-
- public boolean isRemoved() {
- return this.isSaved;
- }
-
- public OnapPDPGroup getUpdatedObject() {
- return this.updatedObject;
- }
+ protected void doSave() {
+ if (this.group == null) {
+ return;
+ }
+
+ StdPDPGroup updatedGroupObject = new StdPDPGroup(
+ group.getId(),
+ group.isDefaultGroup(),
+ group.getName(),
+ group.getDescription(),
+ null);
+
+ // replace the original set of Policies with the set from the container (possibly modified by the user)
+ Set<PDPPolicy> changedPolicies = new HashSet<>();
+ changedPolicies.addAll((Collection<PDPPolicy>) RemoveGroupPolicy.policyContainer.getItemIds());
+ updatedGroupObject.setPolicies(changedPolicies);
+ updatedGroupObject.setOnapPdps(this.group.getOnapPdps());
+
+ // replace the original set of PIP Configs with the set from the container
+ updatedGroupObject.setPipConfigs(this.group.getPipConfigs());
+
+ // copy those things that the user cannot change from the original to the new object
+ updatedGroupObject.setStatus(this.group.getStatus());
+
+ this.updatedObject = updatedGroupObject;
+ }
+
+ public boolean isRemoved() {
+ return this.isSaved;
+ }
+
+ public OnapPDPGroup getUpdatedObject() {
+ return this.updatedObject;
+ }
}
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 a6cda5e68..951f25c25 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
@@ -76,428 +76,428 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RequestMapping("/")
public class PolicyCreation extends AbstractPolicyCreation{
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class);
-
- private String ruleID = "";
- private PolicyDBDao policyDBDao;
- String CLName = null;
-
- private static CommonClassDao commonClassDao;
-
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- PolicyCreation.commonClassDao = commonClassDao;
- }
-
- @Autowired
- public PolicyCreation(CommonClassDao commonClassDao){
- PolicyCreation.commonClassDao = commonClassDao;
- }
-
- public PolicyCreation(){}
-
- @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST)
- @ResponseBody
- public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){
- String body = null;
- HttpStatus status = HttpStatus.BAD_REQUEST;
- Map<String, String> successMap = new HashMap<>();
- Map<String, String> attributeMap = new HashMap<>();
- PolicyVersion policyVersionDao;
- try {
-
- Policy newPolicy = null;
- String policyConfigType = null;
- String userId = policyData.getUserId();
-
- if (policyData.getTtlDate()==null){
- policyData.setTtlDate("NA");
- }else{
- String dateTTL = policyData.getTtlDate();
- String newDate = convertDate(dateTTL);
- policyData.setTtlDate(newDate);
- }
-
- String policyType = policyData.getPolicyType();
-
- String filePrefix = null;
- if ("Config".equalsIgnoreCase(policyType)) {
- policyConfigType = policyData.getConfigPolicyType();
- if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_FW_";
- }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_Fault_";
- }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_PM_";
- }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_MS_";
- }else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_OOF_";
- }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_BRMS_Raw_";
- }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
- filePrefix = "Config_BRMS_Param_";
- }else {
- filePrefix = "Config_";
- }
- } else if ("Action".equalsIgnoreCase(policyType)) {
- filePrefix = "Action_";
- } else if ("Decision".equalsIgnoreCase(policyType)) {
- filePrefix = "Decision_";
- }
-
- int version = 0;
- int highestVersion = 0;
- String createdBy;
- String modifiedBy;
- String scopeCheck = policyData.getDomainDir().replace(".", File.separator);
- PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck);
- if(policyEditorScope == null){
- UserInfo userInfo = new UserInfo();
- userInfo.setUserName("API");
- userInfo.setUserLoginId("API");
- PolicyEditorScopes editorScope = new PolicyEditorScopes();
- editorScope.setScopeName(scopeCheck);
- editorScope.setUserCreatedBy(userInfo);
- 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();
- PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName);
- if(policyVersion == null){
- highestVersion = 0;
- }else{
- highestVersion = policyVersion.getHigherVersion();
- }
-
- if(highestVersion != 0 && policyVersion != null){
- if(policyData.isEditPolicy()){
- version = highestVersion +1;
- if(userId ==null){
- modifiedBy = "API";
- }else{
- modifiedBy = userId;
- }
- policyData.setUserId("API");
- createdBy = policyVersion.getCreatedBy();
- policyVersionDao = policyVersion;
- policyVersionDao.setActiveVersion(version);
- policyVersionDao.setHigherVersion(version);
- policyVersionDao.setModifiedBy(modifiedBy);
- policyVersionDao.setModifiedDate(new Date());
- }else{
- body = "policyExists";
- status = HttpStatus.CONFLICT;
- response.setStatus(HttpServletResponse.SC_CONFLICT);
- response.addHeader("error", "policyExists");
- response.addHeader("policyName", policyData.getPolicyName());
- return new ResponseEntity<>(body, status);
- }
- }else{
- // if policy does not exist and the request is updatePolicy return error
- 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.");
- return new ResponseEntity<>(body, status);
- }
- version = 1;
- if(userId == null){
- createdBy = "API";
- modifiedBy = "API";
- policyData.setUserId("API");
- }else{
- createdBy = userId;
- modifiedBy = userId;
- policyData.setUserId("API");
- }
- policyVersionDao = new PolicyVersion();
- policyVersionDao.setPolicyName(dbCheckPolicyName);
- policyVersionDao.setActiveVersion(version);
- policyVersionDao.setHigherVersion(version);
- policyVersionDao.setCreatedBy(createdBy);
- policyVersionDao.setModifiedBy(modifiedBy);
- }
-
- policyData.setPolicyID(newPolicyID());
- policyData.setRuleID(ruleID);
-
- String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml";
- policyData.setNewFileName(policyFileName);
- 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<?, ?>){
- String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
- String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
- attributeMap.put(key, value);
- }
- }
- }
- policyData.setDynamicFieldConfigAttributes(attributeMap);
- }
-
- policyData.setVersion(String.valueOf(version));
- policyData.setHighestVersion(version);
-
- // Calling Component class per policy type
- if ("Config".equalsIgnoreCase(policyType)) {
- if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
- newPolicy = new FirewallConfigPolicy(policyData);
- }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
- policyData.setOnapName("DROOLS");
- policyData.setConfigName("BRMS_RAW_RULE");
- newPolicy = new CreateBrmsRawPolicy(policyData);
- }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
- policyData.setOnapName("DROOLS");
- policyData.setConfigName("BRMS_PARAM_RULE");
- 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());
- }
- }
- 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("modelName", modelName);
- return new ResponseEntity<String>(body, status);
- }
- }
- newPolicy = new CreateBrmsParamPolicy(policyData);
- }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());
- ObjectMapper jsonMapper = new ObjectMapper();
- String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData());
- jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
- jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
- policyData.setJsonBody(jsonBody);
- }
- newPolicy = new CreateClosedLoopPerformanceMetrics(policyData);
- }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
- newPolicy = new MicroServiceConfigPolicy(policyData);
- }else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
- newPolicy = new OptimizationConfigPolicy(policyData);
- }
- }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<?, ?>){
- 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);
- dynamicRuleAlgorithmField1.add(key);
- dynamicRuleAlgorithmCombo.add(rule);
- dynamicRuleAlgorithmField2.add(value);
- }
- }
- }
-
- String actionDictValue = policyData.getActionAttributeValue();
- ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue));
- if(jsonData!=null){
- String actionBodyString = jsonData.getBody();
- String actionDictHeader = jsonData.getHeader();
- String actionDictType = jsonData.getType();
- String actionDictUrl = jsonData.getUrl();
- String actionDictMethod = jsonData.getMethod();
- policyData.setActionDictHeader(actionDictHeader);
- policyData.setActionDictType(actionDictType);
- policyData.setActionDictUrl(actionDictUrl);
- policyData.setActionDictMethod(actionDictMethod);
- if (actionBodyString != null) {
- policyData.setActionBody(actionBodyString);
- }
- }
- policyData.setActionAttribute(actionDictValue);
- policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
- policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
- policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
- policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
- }else{
- // API request.
- String comboDictValue = policyData.getActionAttribute();
- ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue));
- if(jsonData!=null){
- policyData.setActionBody(jsonData.getBody());
- policyData.setActionDictHeader(jsonData.getHeader());
- policyData.setActionDictType(jsonData.getType());
- policyData.setActionDictUrl(jsonData.getUrl());
- policyData.setActionDictMethod(jsonData.getMethod());
- }
- }
- newPolicy = new ActionPolicy(policyData, commonClassDao);
- } else if ("Decision".equalsIgnoreCase(policyType)) {
- if(policyData.getApiflag() == null){
- Map<String, String> settingsMap = new HashMap<>();
- 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<?, ?>){
- 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<?, ?>){
- 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);
- dynamicRuleAlgorithmField1.add(key);
- dynamicRuleAlgorithmCombo.add(rule);
- dynamicRuleAlgorithmField2.add(value);
- }
- }
- }
- if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML))
- && policyData.getYamlparams()!=null){
- attributeMap.put("actor", policyData.getYamlparams().getActor());
- attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
- attributeMap.put("clname", policyData.getYamlparams().getClname());
- attributeMap.put("limit", policyData.getYamlparams().getLimit());
- attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
- attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits());
- attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
- attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
- if(policyData.getYamlparams().getBlackList()!=null){
- String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ",");
- attributeMap.put("blackList", blackList);
- }
- if(DecisionPolicy.GUARD_BL_YAML.equals(policyData.getRuleProvider()) && "Use File Upload".equals(policyData.getBlackListEntryType())){
- if(policyData.getBlackListEntries() != null && !policyData.getBlackListEntries().isEmpty()){
- String blackList = StringUtils.join(policyData.getBlackListEntries(), ",");
- attributeMap.put("blackList", blackList);
- }
- if(policyData.getAppendBlackListEntries() != null && !policyData.getAppendBlackListEntries().isEmpty()){
- String blackList = StringUtils.join(policyData.getAppendBlackListEntries(), ",");
- attributeMap.put("appendBlackList", blackList);
- }
- }
- if(policyData.getYamlparams().getTargets()!=null){
- String targets = StringUtils.join(policyData.getYamlparams().getTargets(),",");
- attributeMap.put("targets", targets);
- }
- }
- if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){
- attributeMap.put("ServiceType", policyData.getRainyday().getServiceType());
- attributeMap.put("VNFType", policyData.getRainyday().getVnfType());
- attributeMap.put("BB_ID", policyData.getRainyday().getBbid());
- attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep());
-
- if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){
- for (Object table : policyData.getRainyday().getTreatmentTableChoices()){
- if(table instanceof LinkedHashMap<?,?>){
- String errorcode = ((LinkedHashMap<?,?>) table).get("errorcode").toString();
- String treatment = ((LinkedHashMap<?,?>) table).get("treatment").toString();
- treatmentMap.put(errorcode, treatment);
- }
- }
- }
- }
-
- policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
- policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
- policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
- policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
- policyData.setDynamicVariableList(dynamicVariableList);
- policyData.setDynamicSettingsMap(settingsMap);
- policyData.setDynamicFieldConfigAttributes(attributeMap);
- policyData.setDataTypeList(dataTypeList);
- policyData.setRainydayMap(treatmentMap);
- policyData.setErrorCodeList(errorCodeList);
- policyData.setTreatmentList(treatmentList);
- }
- newPolicy = new DecisionPolicy(policyData, commonClassDao);
- }
-
- if(newPolicy != null){
- newPolicy.prepareToSave();
- }else{
- body = "error";
- status = HttpStatus.INTERNAL_SERVER_ERROR;
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error", "error");
- return new ResponseEntity<>(body, status);
- }
-
- PolicyDBDaoTransaction policyDBDaoTransaction = null;
- try{
- policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf());
- policyDBDaoTransaction = policyDBDao.getNewTransaction();
- policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
- successMap = newPolicy.savePolicies();
- if(successMap.containsKey("success")){
- policyDBDaoTransaction.commitTransaction();
- if(policyData.isEditPolicy()){
- commonClassDao.update(policyVersionDao);
- }else{
- commonClassDao.save(policyVersionDao);
- }
- try{
- PolicyElasticSearchController search= new PolicyElasticSearchController();
- search.updateElk(policyData);
- }catch(Exception e){
- LOGGER.error("Error Occured while saving policy to Elastic Database"+e);
- }
- body = "success";
- status = HttpStatus.OK;
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", "success");
- response.addHeader("policyName", policyData.getNewFileName());
-
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class);
+
+ private String ruleID = "";
+ private PolicyDBDao policyDBDao;
+ String CLName = null;
+
+ private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ PolicyCreation.commonClassDao = commonClassDao;
+ }
+
+ @Autowired
+ public PolicyCreation(CommonClassDao commonClassDao){
+ PolicyCreation.commonClassDao = commonClassDao;
+ }
+
+ public PolicyCreation(){}
+
+ @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){
+ String body = null;
+ HttpStatus status = HttpStatus.BAD_REQUEST;
+ Map<String, String> successMap = new HashMap<>();
+ Map<String, String> attributeMap = new HashMap<>();
+ PolicyVersion policyVersionDao;
+ try {
+
+ Policy newPolicy = null;
+ String policyConfigType = null;
+ String userId = policyData.getUserId();
+
+ if (policyData.getTtlDate()==null){
+ policyData.setTtlDate("NA");
+ }else{
+ String dateTTL = policyData.getTtlDate();
+ String newDate = convertDate(dateTTL);
+ policyData.setTtlDate(newDate);
+ }
+
+ String policyType = policyData.getPolicyType();
+
+ String filePrefix = null;
+ if ("Config".equalsIgnoreCase(policyType)) {
+ policyConfigType = policyData.getConfigPolicyType();
+ if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_FW_";
+ }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_Fault_";
+ }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_PM_";
+ }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_MS_";
+ }else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_OOF_";
+ }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_BRMS_Raw_";
+ }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
+ filePrefix = "Config_BRMS_Param_";
+ }else {
+ filePrefix = "Config_";
+ }
+ } else if ("Action".equalsIgnoreCase(policyType)) {
+ filePrefix = "Action_";
+ } else if ("Decision".equalsIgnoreCase(policyType)) {
+ filePrefix = "Decision_";
+ }
+
+ int version = 0;
+ int highestVersion = 0;
+ String createdBy;
+ String modifiedBy;
+ String scopeCheck = policyData.getDomainDir().replace(".", File.separator);
+ PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck);
+ if(policyEditorScope == null){
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserName("API");
+ userInfo.setUserLoginId("API");
+ PolicyEditorScopes editorScope = new PolicyEditorScopes();
+ editorScope.setScopeName(scopeCheck);
+ editorScope.setUserCreatedBy(userInfo);
+ 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();
+ PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName);
+ if(policyVersion == null){
+ highestVersion = 0;
+ }else{
+ highestVersion = policyVersion.getHigherVersion();
+ }
+
+ if(highestVersion != 0 && policyVersion != null){
+ if(policyData.isEditPolicy()){
+ version = highestVersion +1;
+ if(userId ==null){
+ modifiedBy = "API";
+ }else{
+ modifiedBy = userId;
+ }
+ policyData.setUserId("API");
+ createdBy = policyVersion.getCreatedBy();
+ policyVersionDao = policyVersion;
+ policyVersionDao.setActiveVersion(version);
+ policyVersionDao.setHigherVersion(version);
+ policyVersionDao.setModifiedBy(modifiedBy);
+ policyVersionDao.setModifiedDate(new Date());
+ }else{
+ body = "policyExists";
+ status = HttpStatus.CONFLICT;
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ response.addHeader("error", "policyExists");
+ response.addHeader("policyName", policyData.getPolicyName());
+ return new ResponseEntity<>(body, status);
+ }
+ }else{
+ // if policy does not exist and the request is updatePolicy return error
+ 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.");
+ return new ResponseEntity<>(body, status);
+ }
+ version = 1;
+ if(userId == null){
+ createdBy = "API";
+ modifiedBy = "API";
+ policyData.setUserId("API");
+ }else{
+ createdBy = userId;
+ modifiedBy = userId;
+ policyData.setUserId("API");
+ }
+ policyVersionDao = new PolicyVersion();
+ policyVersionDao.setPolicyName(dbCheckPolicyName);
+ policyVersionDao.setActiveVersion(version);
+ policyVersionDao.setHigherVersion(version);
+ policyVersionDao.setCreatedBy(createdBy);
+ policyVersionDao.setModifiedBy(modifiedBy);
+ }
+
+ policyData.setPolicyID(newPolicyID());
+ policyData.setRuleID(ruleID);
+
+ String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml";
+ policyData.setNewFileName(policyFileName);
+ 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<?, ?>){
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+ attributeMap.put(key, value);
+ }
+ }
+ }
+ policyData.setDynamicFieldConfigAttributes(attributeMap);
+ }
+
+ policyData.setVersion(String.valueOf(version));
+ policyData.setHighestVersion(version);
+
+ // Calling Component class per policy type
+ if ("Config".equalsIgnoreCase(policyType)) {
+ if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
+ newPolicy = new FirewallConfigPolicy(policyData);
+ }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
+ policyData.setOnapName("DROOLS");
+ policyData.setConfigName("BRMS_RAW_RULE");
+ newPolicy = new CreateBrmsRawPolicy(policyData);
+ }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
+ policyData.setOnapName("DROOLS");
+ policyData.setConfigName("BRMS_PARAM_RULE");
+ 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());
+ }
+ }
+ 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("modelName", modelName);
+ return new ResponseEntity<String>(body, status);
+ }
+ }
+ newPolicy = new CreateBrmsParamPolicy(policyData);
+ }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());
+ ObjectMapper jsonMapper = new ObjectMapper();
+ String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData());
+ jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
+ jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
+ policyData.setJsonBody(jsonBody);
+ }
+ newPolicy = new CreateClosedLoopPerformanceMetrics(policyData);
+ }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
+ newPolicy = new MicroServiceConfigPolicy(policyData);
+ }else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
+ newPolicy = new OptimizationConfigPolicy(policyData);
+ }
+ }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<?, ?>){
+ 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);
+ dynamicRuleAlgorithmField1.add(key);
+ dynamicRuleAlgorithmCombo.add(rule);
+ dynamicRuleAlgorithmField2.add(value);
+ }
+ }
+ }
+
+ String actionDictValue = policyData.getActionAttributeValue();
+ ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue));
+ if(jsonData!=null){
+ String actionBodyString = jsonData.getBody();
+ String actionDictHeader = jsonData.getHeader();
+ String actionDictType = jsonData.getType();
+ String actionDictUrl = jsonData.getUrl();
+ String actionDictMethod = jsonData.getMethod();
+ policyData.setActionDictHeader(actionDictHeader);
+ policyData.setActionDictType(actionDictType);
+ policyData.setActionDictUrl(actionDictUrl);
+ policyData.setActionDictMethod(actionDictMethod);
+ if (actionBodyString != null) {
+ policyData.setActionBody(actionBodyString);
+ }
+ }
+ policyData.setActionAttribute(actionDictValue);
+ policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
+ policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+ }else{
+ // API request.
+ String comboDictValue = policyData.getActionAttribute();
+ ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue));
+ if(jsonData!=null){
+ policyData.setActionBody(jsonData.getBody());
+ policyData.setActionDictHeader(jsonData.getHeader());
+ policyData.setActionDictType(jsonData.getType());
+ policyData.setActionDictUrl(jsonData.getUrl());
+ policyData.setActionDictMethod(jsonData.getMethod());
+ }
+ }
+ newPolicy = new ActionPolicy(policyData, commonClassDao);
+ } else if ("Decision".equalsIgnoreCase(policyType)) {
+ if(policyData.getApiflag() == null){
+ Map<String, String> settingsMap = new HashMap<>();
+ 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<?, ?>){
+ 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<?, ?>){
+ 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);
+ dynamicRuleAlgorithmField1.add(key);
+ dynamicRuleAlgorithmCombo.add(rule);
+ dynamicRuleAlgorithmField2.add(value);
+ }
+ }
+ }
+ if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML))
+ && policyData.getYamlparams()!=null){
+ attributeMap.put("actor", policyData.getYamlparams().getActor());
+ attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
+ attributeMap.put("clname", policyData.getYamlparams().getClname());
+ attributeMap.put("limit", policyData.getYamlparams().getLimit());
+ attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
+ attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits());
+ attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
+ attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
+ if(policyData.getYamlparams().getBlackList()!=null){
+ String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ",");
+ attributeMap.put("blackList", blackList);
+ }
+ if(DecisionPolicy.GUARD_BL_YAML.equals(policyData.getRuleProvider()) && "Use File Upload".equals(policyData.getBlackListEntryType())){
+ if(policyData.getBlackListEntries() != null && !policyData.getBlackListEntries().isEmpty()){
+ String blackList = StringUtils.join(policyData.getBlackListEntries(), ",");
+ attributeMap.put("blackList", blackList);
+ }
+ if(policyData.getAppendBlackListEntries() != null && !policyData.getAppendBlackListEntries().isEmpty()){
+ String blackList = StringUtils.join(policyData.getAppendBlackListEntries(), ",");
+ attributeMap.put("appendBlackList", blackList);
+ }
+ }
+ if(policyData.getYamlparams().getTargets()!=null){
+ String targets = StringUtils.join(policyData.getYamlparams().getTargets(),",");
+ attributeMap.put("targets", targets);
+ }
+ }
+ if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){
+ attributeMap.put("ServiceType", policyData.getRainyday().getServiceType());
+ attributeMap.put("VNFType", policyData.getRainyday().getVnfType());
+ attributeMap.put("BB_ID", policyData.getRainyday().getBbid());
+ attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep());
+
+ if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){
+ for (Object table : policyData.getRainyday().getTreatmentTableChoices()){
+ if(table instanceof LinkedHashMap<?,?>){
+ String errorcode = ((LinkedHashMap<?,?>) table).get("errorcode").toString();
+ String treatment = ((LinkedHashMap<?,?>) table).get("treatment").toString();
+ treatmentMap.put(errorcode, treatment);
+ }
+ }
+ }
+ }
+
+ policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
+ policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+ policyData.setDynamicVariableList(dynamicVariableList);
+ policyData.setDynamicSettingsMap(settingsMap);
+ policyData.setDynamicFieldConfigAttributes(attributeMap);
+ policyData.setDataTypeList(dataTypeList);
+ policyData.setRainydayMap(treatmentMap);
+ policyData.setErrorCodeList(errorCodeList);
+ policyData.setTreatmentList(treatmentList);
+ }
+ newPolicy = new DecisionPolicy(policyData, commonClassDao);
+ }
+
+ if(newPolicy != null){
+ newPolicy.prepareToSave();
+ }else{
+ body = "error";
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader("error", "error");
+ return new ResponseEntity<>(body, status);
+ }
+
+ PolicyDBDaoTransaction policyDBDaoTransaction = null;
+ try{
+ policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf());
+ policyDBDaoTransaction = policyDBDao.getNewTransaction();
+ policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
+ successMap = newPolicy.savePolicies();
+ if(successMap.containsKey("success")){
+ policyDBDaoTransaction.commitTransaction();
+ if(policyData.isEditPolicy()){
+ commonClassDao.update(policyVersionDao);
+ }else{
+ commonClassDao.save(policyVersionDao);
+ }
+ try{
+ PolicyElasticSearchController search= new PolicyElasticSearchController();
+ search.updateElk(policyData);
+ }catch(Exception e){
+ LOGGER.error("Error Occured while saving policy to Elastic Database"+e);
+ }
+ body = "success";
+ status = HttpStatus.OK;
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ response.addHeader("policyName", policyData.getNewFileName());
+
//get message from the SafetyCheckerResults if present
String safetyCheckerResponse = policyData.getClWarning();
String existingCLName = policyData.getExistingCLName();
@@ -512,77 +512,77 @@ public class PolicyCreation extends AbstractPolicyCreation{
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";
- 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();
- body = "fwdberror";
- status = HttpStatus.BAD_REQUEST;
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE
+ }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";
+ 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();
+ 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")) {
+ 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.";
+ + "Error Validating the Policy on the PAP.";
PolicyLogger.error(message);
body = "Validation";
- status = HttpStatus.BAD_REQUEST;
+ status = HttpStatus.BAD_REQUEST;
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.addHeader("error", message);
response.addHeader("policyName", policyData.getPolicyName());
}else {
- policyDBDaoTransaction.rollbackTransaction();
- body = "error";
- status = HttpStatus.INTERNAL_SERVER_ERROR;
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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.getMessage(),e);
- body = "error";
- response.addHeader("error", e.getMessage());
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return new ResponseEntity<>(body, status);
- }
-
- @ExceptionHandler({ HttpMessageNotReadableException.class })
- 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());
- }
- 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;
- }
- }
- return entityItem;
- }
+ policyDBDaoTransaction.rollbackTransaction();
+ body = "error";
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_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.getMessage(),e);
+ body = "error";
+ response.addHeader("error", e.getMessage());
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ return new ResponseEntity<>(body, status);
+ }
+
+ @ExceptionHandler({ HttpMessageNotReadableException.class })
+ 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());
+ }
+ 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;
+ }
+ }
+ return entityItem;
+ }
}
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 cb03d44ec..e965356be 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
@@ -42,433 +42,433 @@ import org.springframework.web.servlet.ModelAndView;
@Service("DictionaryService")
public class DictionaryService {
- /*
- * Methods that call the controller method directly to Save and Update dictionary data
- */
- public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
-
- DictionaryController dictionary = new DictionaryController();
- ModelAndView result = dictionary.saveOnapDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- DictionaryController dictionary = new DictionaryController();
- ModelAndView result = dictionary.saveAttributeDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
-
- ActionPolicyDictionaryController action = new ActionPolicyDictionaryController();
- ModelAndView result = action.saveActionPolicyDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
-
- BRMSDictionaryController dictionary = new BRMSDictionaryController();
- ModelAndView result = dictionary.saveBRMSParamDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- ModelAndView result = dictionary.saveVSCLAction(request, response);
- return result.getViewName();
- }
-
- public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- ModelAndView result = dictionary.saveVnfType(request, response);
- return result.getViewName();
- }
-
- public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- ModelAndView result = dictionary.savePEPOptions(request, response);
- return result.getViewName();
- }
-
- public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- ModelAndView result = dictionary.saveVarbind(request, response);
- return result.getViewName();
- }
-
- public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- ModelAndView result = dictionary.saveServiceType(request, response);
- return result.getViewName();
- }
-
- public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- ModelAndView result = dictionary.saveSiteType(request, response);
- return result.getViewName();
- }
-
- public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
- ModelAndView result = dictionary.saveSettingsDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
- ModelAndView result = dictionary.saveRainyDayDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController();
- ModelAndView result = dictionary.saveDescriptiveDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveActionListDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveProtocolListDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveZoneDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response);
- return result.getViewName();
- }
-
- public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.savePrefixListDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveAddressGroupDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveServiceGroupDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveServiceListDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- ModelAndView result = dictionary.saveTermListDictionary(request, response);
- return result.getViewName();
- }
-
-
-
-
- public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- OptimizationDictionaryController dictionary = new OptimizationDictionaryController();
- ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response);
- return result.getViewName();
- }
-
- public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- ModelAndView result = dictionary.savePSServiceDictionary(request, response);
- return result.getViewName();
- }
-
- public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- ModelAndView result = dictionary.savePSResourceDictionary(request, response);
- return result.getViewName();
- }
-
- public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- ModelAndView result = dictionary.savePSTypeDictionary(request, response);
- return result.getViewName();
- }
-
- public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response);
- return result.getViewName();
- }
-
- public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- SafePolicyController dictionary = new SafePolicyController();
- ModelAndView result = dictionary.saveRiskTypeDictionary(request, response);
- return result.getViewName();
- }
-
- public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
- SafePolicyController dictionary = new SafePolicyController();
- ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response);
- return result.getViewName();
- }
-
-
- /*
- * Methods that call the controller get methods directly to get dictionary data
- */
- public void getOnapDictionary(HttpServletResponse response){
- DictionaryController dictionary = new DictionaryController();
- dictionary.getOnapNameDictionaryEntityData(response);
- }
-
- public void getAttributeDictionary(HttpServletResponse response){
- DictionaryController dictionary = new DictionaryController();
- dictionary.getAttributeDictionaryEntityData(response);
- }
-
- public void getActionPolicyDictionary(HttpServletResponse response){
- ActionPolicyDictionaryController action = new ActionPolicyDictionaryController();
- action.getActionPolicyDictionaryEntityData(response);
- }
-
- public void getBRMSParamDictionary(HttpServletResponse response){
- BRMSDictionaryController dictionary = new BRMSDictionaryController();
- dictionary.getBRMSParamDictionaryEntityData(response);
- }
-
- public void getVSCLAction(HttpServletResponse response){
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- dictionary.getVSCLActionDictionaryEntityData(response);
- }
-
- public void getVnfType(HttpServletResponse response){
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- dictionary.getVNFTypeDictionaryEntityData(response);
- }
-
- public void getPEPOptions(HttpServletResponse response){
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- dictionary.getPEPOptionsDictionaryEntityData(response);
- }
-
- public void getVarbind(HttpServletResponse response){
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- dictionary.getVarbindDictionaryEntityData(response);
- }
-
- public void getServiceType(HttpServletResponse response){
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- dictionary.getClosedLoopServiceDictionaryEntityData(response);
- }
-
- public void getSiteType(HttpServletResponse response){
- ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
- dictionary.getClosedLoopSiteDictionaryEntityData(response);
- }
-
- public void getSettingsDictionary(HttpServletResponse response){
- DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
- dictionary.getSettingsDictionaryEntityData(response);
- }
-
- public void getRainyDayDictionary(HttpServletResponse response){
- DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
- dictionary.getRainyDayDictionaryEntityData(response);
- }
-
- public void getDescriptiveDictionary(HttpServletResponse response){
- DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController();
- dictionary.getDescriptiveDictionaryEntityData(response);
- }
-
- public void getActionListDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getActionListDictionaryEntityData(response);
- }
-
- public void getProtocolListDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getProtocolListDictionaryEntityData(response);
- }
-
- public void getZoneDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getZoneDictionaryEntityData(response);
- }
-
- public void getSecurityZoneDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getSecurityZoneDictionaryEntityData(response);
- }
-
- public void getPrefixListDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getPrefixListDictionaryEntityData(response);
- }
-
- public void getAddressGroupDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getAddressGroupDictionaryEntityData(response);
- }
-
- public void getServiceGroupDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getServiceGroupDictionaryEntityData(response);
- }
-
- public void getServiceListDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getServiceListDictionaryEntityData(response);
- }
-
- public void getTermListDictionary(HttpServletResponse response){
- FirewallDictionaryController dictionary = new FirewallDictionaryController();
- dictionary.getTermListDictionaryEntityData(response);
- }
-
-
- public void getMicroServiceLocationDictionary(HttpServletResponse response){
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- dictionary.getMicroServiceLocationDictionaryEntityData(response);
- }
-
- public void getMicroServiceConfigNameDictionary(HttpServletResponse response){
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- dictionary.getMicroServiceConfigNameDictionaryEntityData(response);
- }
-
- public void getDCAEUUIDDictionary(HttpServletResponse response){
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- dictionary.getDCAEUUIDDictionaryEntityData(response);
- }
-
- public void getMicroServiceModelsDictionary(HttpServletResponse response){
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- dictionary.getMicroServiceModelsDictionaryEntityData(response);
- }
-
- public void getMicroServiceDictionary(HttpServletResponse response){
- MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
- dictionary.getMicroServiceModelsDictionaryEntityData(response);
- }
-
- public void getOptimizationModelsDictionary(HttpServletResponse response){
- OptimizationDictionaryController dictionary = new OptimizationDictionaryController();
- dictionary.getOptimizationModelsDictionaryEntityData(response);
- }
-
- public void getPSServiceDictionary(HttpServletResponse response){
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- dictionary.getPSServiceEntityData(response);
- }
-
- public void getPSResourceDictionary(HttpServletResponse response){
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- dictionary.getPSResourceEntityData(response);
- }
-
- public void getPSTypeDictionary(HttpServletResponse response){
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- dictionary.getPSTypeEntityData(response);
- }
-
- public void getPSClosedLoopDictionary(HttpServletResponse response){
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- dictionary.getPSClosedLoopEntityData(response);
- }
-
- public void getPSGroupScopeDictionary(HttpServletResponse response){
- PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
- dictionary.getGroupPolicyScopeEntityData(response);
- }
-
- public void getRiskTypeDictionary(HttpServletResponse response){
- SafePolicyController dictionary = new SafePolicyController();
- dictionary.getRiskTypeDictionaryEntityData(response);
- }
-
- public void getSafePolicyWarningDictionary(HttpServletResponse response) {
- SafePolicyController dictionary = new SafePolicyController();
- dictionary.getSafePolicyWarningeEntityData(response);
- }
+ /*
+ * Methods that call the controller method directly to Save and Update dictionary data
+ */
+ public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
+
+ DictionaryController dictionary = new DictionaryController();
+ ModelAndView result = dictionary.saveOnapDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ DictionaryController dictionary = new DictionaryController();
+ ModelAndView result = dictionary.saveAttributeDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
+
+ ActionPolicyDictionaryController action = new ActionPolicyDictionaryController();
+ ModelAndView result = action.saveActionPolicyDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
+
+ BRMSDictionaryController dictionary = new BRMSDictionaryController();
+ ModelAndView result = dictionary.saveBRMSParamDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ ModelAndView result = dictionary.saveVSCLAction(request, response);
+ return result.getViewName();
+ }
+
+ public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ ModelAndView result = dictionary.saveVnfType(request, response);
+ return result.getViewName();
+ }
+
+ public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ ModelAndView result = dictionary.savePEPOptions(request, response);
+ return result.getViewName();
+ }
+
+ public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ ModelAndView result = dictionary.saveVarbind(request, response);
+ return result.getViewName();
+ }
+
+ public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ ModelAndView result = dictionary.saveServiceType(request, response);
+ return result.getViewName();
+ }
+
+ public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ ModelAndView result = dictionary.saveSiteType(request, response);
+ return result.getViewName();
+ }
+
+ public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
+ ModelAndView result = dictionary.saveSettingsDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
+ ModelAndView result = dictionary.saveRainyDayDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController();
+ ModelAndView result = dictionary.saveDescriptiveDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveActionListDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveProtocolListDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveZoneDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.savePrefixListDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveAddressGroupDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveServiceGroupDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveServiceListDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ ModelAndView result = dictionary.saveTermListDictionary(request, response);
+ return result.getViewName();
+ }
+
+
+
+
+ public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ OptimizationDictionaryController dictionary = new OptimizationDictionaryController();
+ ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ ModelAndView result = dictionary.savePSServiceDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ ModelAndView result = dictionary.savePSResourceDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ ModelAndView result = dictionary.savePSTypeDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+
+ SafePolicyController dictionary = new SafePolicyController();
+ ModelAndView result = dictionary.saveRiskTypeDictionary(request, response);
+ return result.getViewName();
+ }
+
+ public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+ SafePolicyController dictionary = new SafePolicyController();
+ ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response);
+ return result.getViewName();
+ }
+
+
+ /*
+ * Methods that call the controller get methods directly to get dictionary data
+ */
+ public void getOnapDictionary(HttpServletResponse response){
+ DictionaryController dictionary = new DictionaryController();
+ dictionary.getOnapNameDictionaryEntityData(response);
+ }
+
+ public void getAttributeDictionary(HttpServletResponse response){
+ DictionaryController dictionary = new DictionaryController();
+ dictionary.getAttributeDictionaryEntityData(response);
+ }
+
+ public void getActionPolicyDictionary(HttpServletResponse response){
+ ActionPolicyDictionaryController action = new ActionPolicyDictionaryController();
+ action.getActionPolicyDictionaryEntityData(response);
+ }
+
+ public void getBRMSParamDictionary(HttpServletResponse response){
+ BRMSDictionaryController dictionary = new BRMSDictionaryController();
+ dictionary.getBRMSParamDictionaryEntityData(response);
+ }
+
+ public void getVSCLAction(HttpServletResponse response){
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ dictionary.getVSCLActionDictionaryEntityData(response);
+ }
+
+ public void getVnfType(HttpServletResponse response){
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ dictionary.getVNFTypeDictionaryEntityData(response);
+ }
+
+ public void getPEPOptions(HttpServletResponse response){
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ dictionary.getPEPOptionsDictionaryEntityData(response);
+ }
+
+ public void getVarbind(HttpServletResponse response){
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ dictionary.getVarbindDictionaryEntityData(response);
+ }
+
+ public void getServiceType(HttpServletResponse response){
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ dictionary.getClosedLoopServiceDictionaryEntityData(response);
+ }
+
+ public void getSiteType(HttpServletResponse response){
+ ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController();
+ dictionary.getClosedLoopSiteDictionaryEntityData(response);
+ }
+
+ public void getSettingsDictionary(HttpServletResponse response){
+ DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
+ dictionary.getSettingsDictionaryEntityData(response);
+ }
+
+ public void getRainyDayDictionary(HttpServletResponse response){
+ DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController();
+ dictionary.getRainyDayDictionaryEntityData(response);
+ }
+
+ public void getDescriptiveDictionary(HttpServletResponse response){
+ DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController();
+ dictionary.getDescriptiveDictionaryEntityData(response);
+ }
+
+ public void getActionListDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getActionListDictionaryEntityData(response);
+ }
+
+ public void getProtocolListDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getProtocolListDictionaryEntityData(response);
+ }
+
+ public void getZoneDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getZoneDictionaryEntityData(response);
+ }
+
+ public void getSecurityZoneDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getSecurityZoneDictionaryEntityData(response);
+ }
+
+ public void getPrefixListDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getPrefixListDictionaryEntityData(response);
+ }
+
+ public void getAddressGroupDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getAddressGroupDictionaryEntityData(response);
+ }
+
+ public void getServiceGroupDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getServiceGroupDictionaryEntityData(response);
+ }
+
+ public void getServiceListDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getServiceListDictionaryEntityData(response);
+ }
+
+ public void getTermListDictionary(HttpServletResponse response){
+ FirewallDictionaryController dictionary = new FirewallDictionaryController();
+ dictionary.getTermListDictionaryEntityData(response);
+ }
+
+
+ public void getMicroServiceLocationDictionary(HttpServletResponse response){
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ dictionary.getMicroServiceLocationDictionaryEntityData(response);
+ }
+
+ public void getMicroServiceConfigNameDictionary(HttpServletResponse response){
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ dictionary.getMicroServiceConfigNameDictionaryEntityData(response);
+ }
+
+ public void getDCAEUUIDDictionary(HttpServletResponse response){
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ dictionary.getDCAEUUIDDictionaryEntityData(response);
+ }
+
+ public void getMicroServiceModelsDictionary(HttpServletResponse response){
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ dictionary.getMicroServiceModelsDictionaryEntityData(response);
+ }
+
+ public void getMicroServiceDictionary(HttpServletResponse response){
+ MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController();
+ dictionary.getMicroServiceModelsDictionaryEntityData(response);
+ }
+
+ public void getOptimizationModelsDictionary(HttpServletResponse response){
+ OptimizationDictionaryController dictionary = new OptimizationDictionaryController();
+ dictionary.getOptimizationModelsDictionaryEntityData(response);
+ }
+
+ public void getPSServiceDictionary(HttpServletResponse response){
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ dictionary.getPSServiceEntityData(response);
+ }
+
+ public void getPSResourceDictionary(HttpServletResponse response){
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ dictionary.getPSResourceEntityData(response);
+ }
+
+ public void getPSTypeDictionary(HttpServletResponse response){
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ dictionary.getPSTypeEntityData(response);
+ }
+
+ public void getPSClosedLoopDictionary(HttpServletResponse response){
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ dictionary.getPSClosedLoopEntityData(response);
+ }
+
+ public void getPSGroupScopeDictionary(HttpServletResponse response){
+ PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController();
+ dictionary.getGroupPolicyScopeEntityData(response);
+ }
+
+ public void getRiskTypeDictionary(HttpServletResponse response){
+ SafePolicyController dictionary = new SafePolicyController();
+ dictionary.getRiskTypeDictionaryEntityData(response);
+ }
+
+ public void getSafePolicyWarningDictionary(HttpServletResponse response) {
+ SafePolicyController dictionary = new SafePolicyController();
+ dictionary.getSafePolicyWarningeEntityData(response);
+ }
} \ No newline at end of file
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 7382a77a1..5e4b4ee7d 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
@@ -41,187 +41,187 @@ import org.onap.policy.pap.xacml.rest.components.CreateNewMicroServiceModel;
import org.onap.policy.pap.xacml.rest.components.CreateNewOptimizationModel;
public class ImportService {
- private static final Logger logger = FlexLogger.getLogger(ImportService.class);
- private static String errorMessage = "Error in reading in file from API call";
- private static String errorMsg = "error";
- private static String operation = "operation";
- private static String importHeader = "import";
- private static String service = "service";
- private static String extractDir = "ExtractDir";
- private static String successMessage = "success";
- private static String invalidServiceName = "Invalid ServiceName";
- private static final String REGEX = "[0-9a-zA-Z._ ]*";
- private static final String MISSING = "missing";
-
- public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) {
- String importServiceCreation = request.getParameter("importService");
- String fileName = request.getParameter("fileName");
- String version = request.getParameter("version");
- String serviceName = request.getParameter("serviceName");
-
- if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader(errorMsg, MISSING);
- response.addHeader(operation, importHeader);
- response.addHeader(service, invalidServiceName);
- return;
- }
+ private static final Logger logger = FlexLogger.getLogger(ImportService.class);
+ private static String errorMessage = "Error in reading in file from API call";
+ private static String errorMsg = "error";
+ private static String operation = "operation";
+ private static String importHeader = "import";
+ private static String service = "service";
+ private static String extractDir = "ExtractDir";
+ private static String successMessage = "success";
+ private static String invalidServiceName = "Invalid ServiceName";
+ private static final String REGEX = "[0-9a-zA-Z._ ]*";
+ private static final String MISSING = "missing";
- String description = request.getParameter("description");
- Map<String, String> successMap = new HashMap<>();
- if(("BRMSPARAM").equals(importServiceCreation)){
- StringBuilder builder = new StringBuilder();
- int ch;
- try {
- while((ch = request.getInputStream().read()) != -1){
- builder.append((char)ch);
- }
- } catch (IOException e) {
- logger.error(e);
- PolicyLogger.error(errorMessage);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader(errorMsg, MISSING);
- response.addHeader(operation, importHeader);
- response.addHeader(service, serviceName);
- }
- CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate();
- successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API");
- }
- else if(("MICROSERVICE").equals(importServiceCreation)){
- CreateNewMicroServiceModel newMS = null;
- String randomID = UUID.randomUUID().toString();
- String type = ".xmi";
- if ( fileName != null) {
- File extracDir = new File(extractDir);
- if (!extracDir.exists()){
- extracDir.mkdirs();
- }
- if (fileName.contains(".xmi") || fileName.contains(".yml")){
- if(fileName.contains(".yml")){
- type = ".yml";
- }
- // get the request content into a String
- String xmi = null;
- java.util.Scanner scanner;
- try {
- scanner = new java.util.Scanner(request.getInputStream());
- scanner.useDelimiter("\\A");
- xmi = scanner.hasNext() ? scanner.next() : "";
- scanner.close();
- } catch (IOException e1) {
- logger.error(e1);
- PolicyLogger.error(errorMessage);
- return;
- }
- 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"))) {
- writer.write(xmi);
- } catch (IOException e) {
- logger.error(e);
- PolicyLogger.error(errorMessage);
- return;
- }
- }else{
- InputStream inputStream = null;
- try(FileOutputStream outputStream = new FileOutputStream(extractDir + File.separator + randomID+".zip")) {
- inputStream = request.getInputStream();
- byte[] buffer = new byte[4096];
- int bytesRead = -1 ;
- while ((bytesRead = inputStream.read(buffer)) != -1) {
- outputStream.write(buffer, 0, bytesRead) ;
- }
- } catch (IOException e) {
- PolicyLogger.error("Error in reading in Zip File from API call"+e);
- return;
- }finally{
- try {
- if(inputStream != null){
- inputStream.close();
- }
- } catch (IOException e) {
- PolicyLogger.error("Exception Occured while closing the input/output stream"+e);
- }
- }
- }
-
- newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID);
-
- successMap = newMS.addValuesToNewModel(type);
-
- if (successMap.containsKey(successMessage)) {
- successMap.clear();
- successMap = newMS.saveImportService();
- }
- }
- } else if(("OPTIMIZATION").equals(importServiceCreation)){
- CreateNewOptimizationModel newOOF = null;
- String randomID = UUID.randomUUID().toString();
- if ( fileName != null) {
- File extracDir = new File(extractDir);
- if (!extracDir.exists()){
- extracDir.mkdirs();
- }
-
- String type = ".yml";
-
- // get the request content into a String
- String yml = null;
- try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){
- scanner.useDelimiter("\\A");
- yml = scanner.hasNext() ? scanner.next() : "";
- } catch (IOException e1) {
- logger.error(e1);
- PolicyLogger.error(errorMessage);
- return;
- }
- 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"))) {
- writer.write(yml);
- } catch (IOException e) {
- logger.error(e);
- PolicyLogger.error(errorMessage);
- return;
- }
-
- newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID);
- successMap = newOOF.addValuesToNewModel();
- if (successMap.containsKey(successMessage)) {
- successMap.clear();
- successMap = newOOF.saveImportService();
- }
- }
- }
-
- // return a response to the PAP
- if (successMap.containsKey(successMessage)) {
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", successMessage);
- response.addHeader(operation, importHeader);
- response.addHeader(service, serviceName);
- } else if (successMap.containsKey("DBError")) {
- if (successMap.get("DBError").contains("EXISTS")){
- response.setStatus(HttpServletResponse.SC_CONFLICT);
- response.addHeader(service, serviceName);
- response.addHeader(errorMsg, "modelExistsDB");
- }else{
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader(errorMsg, "importDB");
- }
- response.addHeader(operation, importHeader);
- response.addHeader(service, serviceName);
- }else if (successMap.get(errorMsg).contains("MISSING")){
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader(errorMsg, MISSING);
- response.addHeader(operation, importHeader);
- response.addHeader(service, serviceName);
- }else if (successMap.get(errorMsg).contains("VALIDATION")){
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader(errorMsg, "validation");
- response.addHeader(operation, importHeader);
- response.addHeader(service, serviceName);
- }
- }
+ public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) {
+ String importServiceCreation = request.getParameter("importService");
+ String fileName = request.getParameter("fileName");
+ String version = request.getParameter("version");
+ String serviceName = request.getParameter("serviceName");
+
+ if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader(errorMsg, MISSING);
+ response.addHeader(operation, importHeader);
+ response.addHeader(service, invalidServiceName);
+ return;
+ }
+
+ String description = request.getParameter("description");
+ Map<String, String> successMap = new HashMap<>();
+ if(("BRMSPARAM").equals(importServiceCreation)){
+ StringBuilder builder = new StringBuilder();
+ int ch;
+ try {
+ while((ch = request.getInputStream().read()) != -1){
+ builder.append((char)ch);
+ }
+ } catch (IOException e) {
+ logger.error(e);
+ PolicyLogger.error(errorMessage);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader(errorMsg, MISSING);
+ response.addHeader(operation, importHeader);
+ response.addHeader(service, serviceName);
+ }
+ CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate();
+ successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API");
+ }
+ else if(("MICROSERVICE").equals(importServiceCreation)){
+ CreateNewMicroServiceModel newMS = null;
+ String randomID = UUID.randomUUID().toString();
+ String type = ".xmi";
+ if ( fileName != null) {
+ File extracDir = new File(extractDir);
+ if (!extracDir.exists()){
+ extracDir.mkdirs();
+ }
+ if (fileName.contains(".xmi") || fileName.contains(".yml")){
+ if(fileName.contains(".yml")){
+ type = ".yml";
+ }
+ // get the request content into a String
+ String xmi = null;
+ java.util.Scanner scanner;
+ try {
+ scanner = new java.util.Scanner(request.getInputStream());
+ scanner.useDelimiter("\\A");
+ xmi = scanner.hasNext() ? scanner.next() : "";
+ scanner.close();
+ } catch (IOException e1) {
+ logger.error(e1);
+ PolicyLogger.error(errorMessage);
+ return;
+ }
+ 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"))) {
+ writer.write(xmi);
+ } catch (IOException e) {
+ logger.error(e);
+ PolicyLogger.error(errorMessage);
+ return;
+ }
+ }else{
+ InputStream inputStream = null;
+ try(FileOutputStream outputStream = new FileOutputStream(extractDir + File.separator + randomID+".zip")) {
+ inputStream = request.getInputStream();
+ byte[] buffer = new byte[4096];
+ int bytesRead = -1 ;
+ while ((bytesRead = inputStream.read(buffer)) != -1) {
+ outputStream.write(buffer, 0, bytesRead) ;
+ }
+ } catch (IOException e) {
+ PolicyLogger.error("Error in reading in Zip File from API call"+e);
+ return;
+ }finally{
+ try {
+ if(inputStream != null){
+ inputStream.close();
+ }
+ } catch (IOException e) {
+ PolicyLogger.error("Exception Occured while closing the input/output stream"+e);
+ }
+ }
+ }
+
+ newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID);
+
+ successMap = newMS.addValuesToNewModel(type);
+
+ if (successMap.containsKey(successMessage)) {
+ successMap.clear();
+ successMap = newMS.saveImportService();
+ }
+ }
+ } else if(("OPTIMIZATION").equals(importServiceCreation)){
+ CreateNewOptimizationModel newOOF = null;
+ String randomID = UUID.randomUUID().toString();
+ if ( fileName != null) {
+ File extracDir = new File(extractDir);
+ if (!extracDir.exists()){
+ extracDir.mkdirs();
+ }
+
+ String type = ".yml";
+
+ // get the request content into a String
+ String yml = null;
+ try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){
+ scanner.useDelimiter("\\A");
+ yml = scanner.hasNext() ? scanner.next() : "";
+ } catch (IOException e1) {
+ logger.error(e1);
+ PolicyLogger.error(errorMessage);
+ return;
+ }
+ 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"))) {
+ writer.write(yml);
+ } catch (IOException e) {
+ logger.error(e);
+ PolicyLogger.error(errorMessage);
+ return;
+ }
+
+ newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID);
+ successMap = newOOF.addValuesToNewModel();
+ if (successMap.containsKey(successMessage)) {
+ successMap.clear();
+ successMap = newOOF.saveImportService();
+ }
+ }
+ }
+
+ // return a response to the PAP
+ if (successMap.containsKey(successMessage)) {
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", successMessage);
+ response.addHeader(operation, importHeader);
+ response.addHeader(service, serviceName);
+ } else if (successMap.containsKey("DBError")) {
+ if (successMap.get("DBError").contains("EXISTS")){
+ response.setStatus(HttpServletResponse.SC_CONFLICT);
+ response.addHeader(service, serviceName);
+ response.addHeader(errorMsg, "modelExistsDB");
+ }else{
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader(errorMsg, "importDB");
+ }
+ response.addHeader(operation, importHeader);
+ response.addHeader(service, serviceName);
+ }else if (successMap.get(errorMsg).contains("MISSING")){
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader(errorMsg, MISSING);
+ response.addHeader(operation, importHeader);
+ response.addHeader(service, serviceName);
+ }else if (successMap.get(errorMsg).contains("VALIDATION")){
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.addHeader(errorMsg, "validation");
+ response.addHeader(operation, importHeader);
+ response.addHeader(service, serviceName);
+ }
+ }
} \ No newline at end of file
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 3fff9f266..864201cfe 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
@@ -35,64 +35,64 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import com.att.research.xacml.api.pap.PDPPolicy;
public class MetricService {
- private static String errorMsg = "error";
- /*
- * This is a private constructor
- * */
- private MetricService(){
-
- }
- public static void doGetPolicyMetrics(HttpServletResponse response) {
- Set<OnapPDPGroup> groups = new HashSet<>();
- try {
- //get the count of policies on the PDP
- if(XACMLPapServlet.getPAPEngine()!=null){
- groups = XACMLPapServlet.getPAPEngine().getOnapPDPGroups();
- }
- int pdpCount = 0;
- for (OnapPDPGroup group : groups) {
- Set<PDPPolicy> policies = group.getPolicies();
- pdpCount += policies.size();
- }
- //get the count of policies on the PAP
- EntityManager em = null;
- if(XACMLPapServlet.getEmf()!=null){
- em = XACMLPapServlet.getEmf().createEntityManager();
- }
- if (em==null){
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit());
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader(errorMsg, "Error creating entity manager with persistence unit");
- return;
- }
- int papCount = ((Number) em.createNamedQuery("PolicyVersion.findAllCount").getSingleResult()).intValue();
- em.close();
- int totalCount = pdpCount + papCount;
- //create json string for API response
- JSONObject json = new JSONObject();
- json.put("papCount", papCount);
- json.put("pdpCount", pdpCount);
- 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.");
- response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", "success");
- response.addHeader("operation", "getMetrics");
- response.addHeader("metrics", json.toString() );
- 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.";
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader(errorMsg, message);
- return;
- }
- } catch (Exception e) {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage();
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Querying the Database.");
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- response.addHeader(errorMsg, message);
- return;
- }
- }
+ private static String errorMsg = "error";
+ /*
+ * This is a private constructor
+ * */
+ private MetricService(){
+
+ }
+ public static void doGetPolicyMetrics(HttpServletResponse response) {
+ Set<OnapPDPGroup> groups = new HashSet<>();
+ try {
+ //get the count of policies on the PDP
+ if(XACMLPapServlet.getPAPEngine()!=null){
+ groups = XACMLPapServlet.getPAPEngine().getOnapPDPGroups();
+ }
+ int pdpCount = 0;
+ for (OnapPDPGroup group : groups) {
+ Set<PDPPolicy> policies = group.getPolicies();
+ pdpCount += policies.size();
+ }
+ //get the count of policies on the PAP
+ EntityManager em = null;
+ if(XACMLPapServlet.getEmf()!=null){
+ em = XACMLPapServlet.getEmf().createEntityManager();
+ }
+ if (em==null){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit());
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader(errorMsg, "Error creating entity manager with persistence unit");
+ return;
+ }
+ int papCount = ((Number) em.createNamedQuery("PolicyVersion.findAllCount").getSingleResult()).intValue();
+ em.close();
+ int totalCount = pdpCount + papCount;
+ //create json string for API response
+ JSONObject json = new JSONObject();
+ json.put("papCount", papCount);
+ json.put("pdpCount", pdpCount);
+ 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.");
+ response.setStatus(HttpServletResponse.SC_OK);
+ response.addHeader("successMapKey", "success");
+ response.addHeader("operation", "getMetrics");
+ response.addHeader("metrics", json.toString() );
+ 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.";
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.addHeader(errorMsg, message);
+ return;
+ }
+ } catch (Exception e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage();
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Querying the Database.");
+ 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 0c98a44a3..f411e7d98 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
@@ -30,69 +30,69 @@ import com.google.common.base.Joiner;
@Component
public abstract class AbstractPolicyCreation {
-
- public static String getDomain() {
- return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
- }
-
- public String newPolicyID() {
- 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("/")){
- formateDate = dateTTL.replace("/", "-");
- }else {
- formateDate = dateTTL;
- }
- return formateDate;
- }
-
-
- public void updatePolicyCreationToDatabase(){
- // Add it into our tree
+ public static String getDomain() {
+ return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
+ }
+
+ public String newPolicyID() {
+ 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("/")){
+ formateDate = dateTTL.replace("/", "-");
+ }else {
+ formateDate = dateTTL;
+ }
+ return formateDate;
+ }
+
+
+
+ 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);
- }
- }*/
- }
+ 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 5610577a9..f85255785 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
@@ -48,166 +48,166 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class DictionaryUtils {
- private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class);
-
- private static String apiflag = "apiflag";
- private static String operation = "operation";
- private static String duplicateResponseString = "Duplicate";
- private static String utf8 = "UTF-8";
- private static String applicationJsonContentType = "application / json";
-
- private static CommonClassDao commonClassDao;
-
- private static DictionaryUtils dictionaryUtils;
-
- public static synchronized DictionaryUtils getDictionaryUtils() {
- return dictionaryUtils != null ? dictionaryUtils : new DictionaryUtils();
- }
-
- public static synchronized void setDictionaryUtils(DictionaryUtils dictionaryUtils) {
- DictionaryUtils.dictionaryUtils = dictionaryUtils;
- }
-
- @Autowired
- public DictionaryUtils(CommonClassDao commonClassDao){
- DictionaryUtils.commonClassDao = commonClassDao;
- }
-
- public DictionaryUtils(){
- super();
- }
-
- public UserInfo getUserInfo(String loginId){
- return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
- }
-
- public boolean isRequestFromAPI(HttpServletRequest request){
- return request.getParameter(apiflag)!=null && "api".equalsIgnoreCase(request.getParameter(apiflag));
- }
-
- public String appendKey(List<Object> objects, String key1, String appendValue){
- StringBuilder userValue = new StringBuilder();
- int counter = 0;
- for(Object attribute : objects){
- if(attribute instanceof LinkedHashMap<?, ?>){
- String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString();
- if(counter>0){
- userValue.append(appendValue);
- }
- userValue.append(key);
- counter ++;
- }
- }
- return userValue.toString();
- }
-
- public String appendKeyValue(List<Object> objects, String append1, String append2){
- StringBuilder header = new StringBuilder();
- int counter = 0;
- for(Object attribute : objects){
- if(attribute instanceof LinkedHashMap<?, ?>){
- String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
- String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
- if(counter>0){
- header.append(append1);
- }
- header.append(key).append(append2).append(value);
- counter ++;
- }
- }
- return header.toString();
- }
-
- public Datatype getDataType(String datatype){
- Datatype a = new Datatype();
- if("string".equalsIgnoreCase(datatype)){
- a.setId(26);
- }else if("integer".equalsIgnoreCase(datatype)){
- a.setId(12);
- }else if("boolean".equalsIgnoreCase(datatype)){
- a.setId(18);
- }else if("double".equalsIgnoreCase(datatype)){
- a.setId(25);
- }else if("user".equalsIgnoreCase(datatype)){
- a.setId(29);
- }
- return a;
- }
-
- public Category getCategory(){
- return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0);
- }
-
- public ModelAndView getResultForApi(String inResponseString){
- String responseString = inResponseString;
- if(responseString!=null && !duplicateResponseString.equals(responseString)){
- responseString = "Success";
- }
- ModelAndView result = new ModelAndView();
- result.setViewName(responseString);
- return result;
- }
-
- public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException{
- response.setCharacterEncoding(utf8);
- response.setContentType(applicationJsonContentType);
-
- PrintWriter out = response.getWriter();
- JSONObject j = new JSONObject("{"+key+":" + responseString + "}");
- out.write(j.toString());
- }
-
- public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
- response.setCharacterEncoding(utf8);
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
-
- @SuppressWarnings("rawtypes")
- 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)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
- }
- }
-
- @SuppressWarnings("rawtypes")
- public void getData(HttpServletResponse response, String key, Class className){
- try{
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- model.put(key, mapper.writeValueAsString(commonClassDao.getData(className)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
+ private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class);
+
+ private static String apiflag = "apiflag";
+ private static String operation = "operation";
+ private static String duplicateResponseString = "Duplicate";
+ private static String utf8 = "UTF-8";
+ private static String applicationJsonContentType = "application / json";
+
+ private static CommonClassDao commonClassDao;
+
+ private static DictionaryUtils dictionaryUtils;
+
+ public static synchronized DictionaryUtils getDictionaryUtils() {
+ return dictionaryUtils != null ? dictionaryUtils : new DictionaryUtils();
+ }
+
+ public static synchronized void setDictionaryUtils(DictionaryUtils dictionaryUtils) {
+ DictionaryUtils.dictionaryUtils = dictionaryUtils;
+ }
+
+ @Autowired
+ public DictionaryUtils(CommonClassDao commonClassDao){
+ DictionaryUtils.commonClassDao = commonClassDao;
+ }
+
+ public DictionaryUtils(){
+ super();
+ }
+
+ public UserInfo getUserInfo(String loginId){
+ return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
+ }
+
+ public boolean isRequestFromAPI(HttpServletRequest request){
+ return request.getParameter(apiflag)!=null && "api".equalsIgnoreCase(request.getParameter(apiflag));
+ }
+
+ public String appendKey(List<Object> objects, String key1, String appendValue){
+ StringBuilder userValue = new StringBuilder();
+ int counter = 0;
+ for(Object attribute : objects){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString();
+ if(counter>0){
+ userValue.append(appendValue);
+ }
+ userValue.append(key);
+ counter ++;
+ }
+ }
+ return userValue.toString();
+ }
+
+ public String appendKeyValue(List<Object> objects, String append1, String append2){
+ StringBuilder header = new StringBuilder();
+ int counter = 0;
+ for(Object attribute : objects){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
+ if(counter>0){
+ header.append(append1);
+ }
+ header.append(key).append(append2).append(value);
+ counter ++;
+ }
+ }
+ return header.toString();
+ }
+
+ public Datatype getDataType(String datatype){
+ Datatype a = new Datatype();
+ if("string".equalsIgnoreCase(datatype)){
+ a.setId(26);
+ }else if("integer".equalsIgnoreCase(datatype)){
+ a.setId(12);
+ }else if("boolean".equalsIgnoreCase(datatype)){
+ a.setId(18);
+ }else if("double".equalsIgnoreCase(datatype)){
+ a.setId(25);
+ }else if("user".equalsIgnoreCase(datatype)){
+ a.setId(29);
+ }
+ return a;
+ }
+
+ public Category getCategory(){
+ return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0);
+ }
+
+ public ModelAndView getResultForApi(String inResponseString){
+ String responseString = inResponseString;
+ if(responseString!=null && !duplicateResponseString.equals(responseString)){
+ responseString = "Success";
+ }
+ ModelAndView result = new ModelAndView();
+ result.setViewName(responseString);
+ return result;
+ }
+
+ public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException{
+ response.setCharacterEncoding(utf8);
+ response.setContentType(applicationJsonContentType);
+
+ PrintWriter out = response.getWriter();
+ JSONObject j = new JSONObject("{"+key+":" + responseString + "}");
+ out.write(j.toString());
+ }
+
+ public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ response.setCharacterEncoding(utf8);
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+
+ @SuppressWarnings("rawtypes")
+ 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)));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ public void getData(HttpServletResponse response, String key, Class className){
+ try{
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put(key, mapper.writeValueAsString(commonClassDao.getData(className)));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
response.addHeader("successMapKey", "success");
response.addHeader(operation, "getDictionary");
- response.getWriter().write(j.toString());
- }catch(Exception e){
+ response.getWriter().write(j.toString());
+ }catch(Exception e){
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.addHeader("error", "dictionaryDBQuery");
- }
- }
-
- @SuppressWarnings("unchecked")
- public void removeData(HttpServletRequest request, HttpServletResponse response, String key, @SuppressWarnings("rawtypes") Class className) throws IOException{
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- commonClassDao.delete((Object)mapper.readValue(root.get("data").toString(), className));
- String responseString = mapper.writeValueAsString(commonClassDao.getData(className));
- setResponseData(response, key, responseString);
- }catch(Exception e){
- setErrorResponseData(response, e);
- }
- }
-
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public void removeData(HttpServletRequest request, HttpServletResponse response, String key, @SuppressWarnings("rawtypes") Class className) throws IOException{
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ commonClassDao.delete((Object)mapper.readValue(root.get("data").toString(), className));
+ String responseString = mapper.writeValueAsString(commonClassDao.getData(className));
+ setResponseData(response, key, responseString);
+ }catch(Exception e){
+ setErrorResponseData(response, 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 22c44a8ab..b9880d8ac 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
@@ -31,88 +31,88 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
public class JPAUtils {
- private static final Logger LOGGER = FlexLogger.getLogger(JPAUtils.class);
-
- private static EntityManagerFactory emf;
- private static JPAUtils currentInstance = null;
-
-
- /**
- * Get an instance of a JPAUtils. It creates one if it does not exist.
- * Only one instance is allowed to be created per server.
- * @param emf The EntityFactoryManager to be used for database connections
- * @return The new instance of JPAUtils or throw exception if the given emf is null.
- * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this.
- */
- public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf){
- LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called");
- if(currentInstance == null){
- if(emf != null){
- currentInstance = new JPAUtils(emf);
- return currentInstance;
- }
- throw new IllegalStateException("The EntityManagerFactory is Null");
- }
- return currentInstance;
- }
-
- private JPAUtils(EntityManagerFactory emf){
- LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called");
- JPAUtils.emf = emf;
- }
-
- /**
- * Returns the lockdown value, in case of exception it is assumed that lockdown functionality
- * is not supported and returns false.
- *
- *
- * @throws ReadOnlyException
- * @throws ConversionException
- */
- public boolean dbLockdownIgnoreErrors() {
- if (LOGGER.isTraceEnabled())
- LOGGER.trace("ENTER");
-
- boolean lockdown = false;
- try {
- lockdown = dbLockdown();
- } catch (Exception e) {
- LOGGER.warn("Cannot access DB lockdown value", e);
- }
- return lockdown;
- }
-
- /**
- * Returns the lockdown value from the database.
- *
- * @throws ReadOnlyException
- * @throws ConversionException
- */
- public boolean dbLockdown()
- throws IllegalAccessException {
- if (LOGGER.isTraceEnabled())
- LOGGER.trace("ENTER");
-
- EntityManager em = emf.createEntityManager();
- Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll");
-
- GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult();
-
- if (globalRoleSettings == null) {
- // this should not happen
- String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
- if (LOGGER.isErrorEnabled())
- LOGGER.error(msg);
- throw new IllegalAccessException(msg);
- }
-
- if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) {
- String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
- if (LOGGER.isErrorEnabled())
- LOGGER.error(msg);
- throw new IllegalAccessException(msg);
- }
-
- return globalRoleSettings.isLockdown();
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(JPAUtils.class);
+
+ private static EntityManagerFactory emf;
+ private static JPAUtils currentInstance = null;
+
+
+ /**
+ * Get an instance of a JPAUtils. It creates one if it does not exist.
+ * Only one instance is allowed to be created per server.
+ * @param emf The EntityFactoryManager to be used for database connections
+ * @return The new instance of JPAUtils or throw exception if the given emf is null.
+ * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this.
+ */
+ public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf){
+ LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called");
+ if(currentInstance == null){
+ if(emf != null){
+ currentInstance = new JPAUtils(emf);
+ return currentInstance;
+ }
+ throw new IllegalStateException("The EntityManagerFactory is Null");
+ }
+ return currentInstance;
+ }
+
+ private JPAUtils(EntityManagerFactory emf){
+ LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called");
+ JPAUtils.emf = emf;
+ }
+
+ /**
+ * Returns the lockdown value, in case of exception it is assumed that lockdown functionality
+ * is not supported and returns false.
+ *
+ *
+ * @throws ReadOnlyException
+ * @throws ConversionException
+ */
+ public boolean dbLockdownIgnoreErrors() {
+ if (LOGGER.isTraceEnabled())
+ LOGGER.trace("ENTER");
+
+ boolean lockdown = false;
+ try {
+ lockdown = dbLockdown();
+ } catch (Exception e) {
+ LOGGER.warn("Cannot access DB lockdown value", e);
+ }
+ return lockdown;
+ }
+
+ /**
+ * Returns the lockdown value from the database.
+ *
+ * @throws ReadOnlyException
+ * @throws ConversionException
+ */
+ public boolean dbLockdown()
+ throws IllegalAccessException {
+ if (LOGGER.isTraceEnabled())
+ LOGGER.trace("ENTER");
+
+ EntityManager em = emf.createEntityManager();
+ Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll");
+
+ GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult();
+
+ if (globalRoleSettings == null) {
+ // this should not happen
+ String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
+ if (LOGGER.isErrorEnabled())
+ LOGGER.error(msg);
+ throw new IllegalAccessException(msg);
+ }
+
+ if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) {
+ String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString();
+ if (LOGGER.isErrorEnabled())
+ LOGGER.error(msg);
+ throw new IllegalAccessException(msg);
+ }
+
+ return globalRoleSettings.isLockdown();
+ }
}
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 ab3b126ea..6ea0c79ee 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
@@ -22,46 +22,46 @@ package org.onap.policy.pap.xacml.rest.util;
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) {
- super();
- this.data = data;
- this.data2 = data2;
- }
+ private String data;
+ private String data2;
+ private String data3;
+ public JsonMessage(String data) {
+ super();
+ this.data = data;
+ }
+ public JsonMessage(String data,String data2) {
+ super();
+ this.data = data;
+ this.data2 = data2;
+ }
+
+ public JsonMessage(String data,String data2,String data3) {
+ super();
+ this.data = data;
+ this.data2 = data2;
+ this.data3 = data3;
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ 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;
+ }
- public JsonMessage(String data,String data2,String data3) {
- super();
- this.data = data;
- this.data2 = data2;
- this.data3 = data3;
- }
-
- public String getData() {
- return data;
- }
- 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 352505ec5..0ac6c7009 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
@@ -31,34 +31,34 @@ import org.onap.policy.utils.CryptoUtils;
import com.att.research.xacml.util.XACMLProperties;
public class AuthenticationService {
- private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- private String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
-
- public boolean authenticate(String authCredentials) {
+ private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ private String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
- if (null == authCredentials)
- return false;
- // header value format will be "Basic encodedstring" for Basic authentication.
- final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
- String usernameAndPassword = null;
- try {
- byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
- usernameAndPassword = new String(decodedBytes, "UTF-8");
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password");
- return false;
- }
- try {
- final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
- final String username = tokenizer.nextToken();
- final String password = tokenizer.nextToken();
+ public boolean authenticate(String authCredentials) {
+
+ if (null == authCredentials)
+ return false;
+ // header value format will be "Basic encodedstring" for Basic authentication.
+ final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
+ String usernameAndPassword = null;
+ try {
+ byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
+ usernameAndPassword = new String(decodedBytes, "UTF-8");
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password");
+ return false;
+ }
+ try {
+ final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
+ final String username = tokenizer.nextToken();
+ final String password = tokenizer.nextToken();
+
+ boolean authenticationStatus = papID.equals(username) && papPass.equals(password);
+ return authenticationStatus;
+ } catch (Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user");
+ return false;
+ }
+ }
- boolean authenticationStatus = papID.equals(username) && papPass.equals(password);
- return authenticationStatus;
- } catch (Exception e){
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user");
- return false;
- }
- }
-
}
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 335b94f51..28207f29d 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
@@ -47,137 +47,137 @@ import com.att.research.xacml.api.pap.PAPException;
public class CheckPDP {
- private static Path pdpPath = null;
- private static Properties pdpProp = null;
- private static Long oldModified = null;
- private static Long newModified = null;
- private static HashMap<String, String> pdpMap = null;
- private static final Logger logger = FlexLogger.getLogger(CheckPDP.class);
+ private static Path pdpPath = null;
+ private static Properties pdpProp = null;
+ private static Long oldModified = null;
+ private static Long newModified = null;
+ private static HashMap<String, String> pdpMap = null;
+ private static final Logger logger = FlexLogger.getLogger(CheckPDP.class);
- public static boolean validateID(String id) {
- // ReadFile
- try {
- readFile();
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file");
- return false;
- }
- // Check ID
- if (pdpMap.containsKey(id)) {
- return true;
- }
- return false;
- }
+ public static boolean validateID(String id) {
+ // ReadFile
+ try {
+ readFile();
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file");
+ return false;
+ }
+ // Check ID
+ if (pdpMap.containsKey(id)) {
+ return true;
+ }
+ return false;
+ }
- private static void readFile() throws PAPException {
- 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);
- }
- 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());
- }
- 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");
- }
- }
- // Check if File is updated recently
- else {
- newModified = pdpPath.toFile().lastModified();
- if (newModified != oldModified) {
- // File has been updated.
- readProps();
- }
- }
- }
+ private static void readFile() throws PAPException {
+ 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);
+ }
+ 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());
+ }
+ 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");
+ }
+ }
+ // Check if File is updated recently
+ else {
+ newModified = pdpPath.toFile().lastModified();
+ if (newModified != oldModified) {
+ // File has been updated.
+ readProps();
+ }
+ }
+ }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static void readProps() throws PAPException {
- InputStream in;
- pdpProp = new Properties();
- try {
- in = new FileInputStream(pdpPath.toFile());
- oldModified = pdpPath.toFile().lastModified();
- pdpProp.load(in);
- } catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file");
- throw new PAPException("Cannot Load the Properties file", e);
- }
- // Read the Properties and Load the PDPs and encoding.
- pdpMap = new HashMap<>();
- // Check the Keys for PDP_URLs
- Collection<Object> unsorted = pdpProp.keySet();
- List<String> sorted = new ArrayList(unsorted);
- Collections.sort(sorted);
- for (String propKey : sorted) {
- if (propKey.startsWith("PDP_URL")) {
- String check_val = pdpProp.getProperty(propKey);
- if (check_val == null) {
- throw new PAPException("Properties file doesn't have the PDP_URL parameter");
- }
- if (check_val.contains(";")) {
- List<String> pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*")));
- int pdpCount = 0;
- while (pdpCount < pdp_default.size()) {
- String pdpVal = pdp_default.get(pdpCount);
- readPDPParam(pdpVal);
- pdpCount++;
- }
- } else {
- readPDPParam(check_val);
- }
- }
- }
- 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");
- }
- }
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private static void readProps() throws PAPException {
+ InputStream in;
+ pdpProp = new Properties();
+ try {
+ in = new FileInputStream(pdpPath.toFile());
+ oldModified = pdpPath.toFile().lastModified();
+ pdpProp.load(in);
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file");
+ throw new PAPException("Cannot Load the Properties file", e);
+ }
+ // Read the Properties and Load the PDPs and encoding.
+ pdpMap = new HashMap<>();
+ // Check the Keys for PDP_URLs
+ Collection<Object> unsorted = pdpProp.keySet();
+ List<String> sorted = new ArrayList(unsorted);
+ Collections.sort(sorted);
+ for (String propKey : sorted) {
+ if (propKey.startsWith("PDP_URL")) {
+ String check_val = pdpProp.getProperty(propKey);
+ if (check_val == null) {
+ throw new PAPException("Properties file doesn't have the PDP_URL parameter");
+ }
+ if (check_val.contains(";")) {
+ List<String> pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*")));
+ int pdpCount = 0;
+ while (pdpCount < pdp_default.size()) {
+ String pdpVal = pdp_default.get(pdpCount);
+ readPDPParam(pdpVal);
+ pdpCount++;
+ }
+ } else {
+ readPDPParam(check_val);
+ }
+ }
+ }
+ 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");
+ }
+ }
- 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){
- // 1:2 will be UserID:Password
- String userID = pdpValues.get(1);
- String pass = pdpValues.get(2);
- Base64.Encoder encoder = Base64.getEncoder();
- // 0 - PDPURL
- 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);
- }
- }else{
- PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
- throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request.");
- }
- }
-
- 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{
- encoding = pdpMap.get(pdpID);
- } catch(Exception e){
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding");
- }
- return encoding;
- }else{
- return null;
- }
- }
+ 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){
+ // 1:2 will be UserID:Password
+ String userID = pdpValues.get(1);
+ String pass = pdpValues.get(2);
+ Base64.Encoder encoder = Base64.getEncoder();
+ // 0 - PDPURL
+ 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);
+ }
+ }else{
+ PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
+ throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request.");
+ }
+ }
+
+ 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{
+ encoding = pdpMap.get(pdpID);
+ } catch(Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding");
+ }
+ return encoding;
+ }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 c4b97f592..94cd9c798 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
@@ -41,69 +41,69 @@ import org.apache.commons.logging.LogFactory;
@WebFilter("/*")
public class PAPAuthenticationFilter implements Filter {
- 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 {
-
-
- if (request instanceof HttpServletRequest) {
- HttpServletRequest httpServletRequest = (HttpServletRequest) request;
-
- String authCredentials = null;
- String url = httpServletRequest.getRequestURI();
-
- logger.info("Request URI: " + url);
-
- //getting authentication credentials
- authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER);
-
- // Check Authentication credentials
- AuthenticationService authenticationService = new AuthenticationService();
- boolean authenticationStatus = authenticationService.authenticate(authCredentials);
-
- if (authenticationStatus) {
- //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
- 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);
- addCorsHeader(alteredResponse);
- logger.info("Request comes from Onap Portal");
- //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path
- filter.doFilter(request, response);
- }
- } else {
- if (response instanceof HttpServletResponse) {
- HttpServletResponse httpServletResponse = (HttpServletResponse) response;
- httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- }
- }
-
- }
- }
-
- //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", "*");
+ 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 {
+
+
+ if (request instanceof HttpServletRequest) {
+ HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+
+ String authCredentials = null;
+ String url = httpServletRequest.getRequestURI();
+
+ logger.info("Request URI: " + url);
+
+ //getting authentication credentials
+ authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER);
+
+ // Check Authentication credentials
+ AuthenticationService authenticationService = new AuthenticationService();
+ boolean authenticationStatus = authenticationService.authenticate(authCredentials);
+
+ if (authenticationStatus) {
+ //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
+ 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);
+ addCorsHeader(alteredResponse);
+ logger.info("Request comes from Onap Portal");
+ //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path
+ filter.doFilter(request, response);
+ }
+ } else {
+ if (response instanceof HttpServletResponse) {
+ HttpServletResponse httpServletResponse = (HttpServletResponse) response;
+ httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+
+ }
+ }
+
+ //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");
- }
+ }
- @Override
- public void destroy() {
- //Empty
- }
+ @Override
+ public void destroy() {
+ //Empty
+ }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- //Empty
- }
+ @Override
+ public void init(FilterConfig arg0) throws ServletException {
+ //Empty
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java
index 049f721ea..5b4165fdb 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java
@@ -50,404 +50,404 @@ import org.onap.policy.jpa.BackUpMonitorEntity;
public class DbAuditCompareEntriesTest {
- private static Log logger = LogFactory.getLog(DbAuditCompareEntriesTest.class);
- private DbDAO dbDAO;
- private String persistenceUnit;
- private Properties properties;
- private String resourceName;
- private String dbDriver;
- private String dbUrl;
- private String dbUser;
- private String dbPwd;
- private String siteName;
- private String nodeType;
- private static final String DEFAULT_DB_DRIVER = "org.h2.Driver";
- private static final String DEFAULT_DB_USER = "sa";
- private static final String DEFAULT_DB_PWD = "";
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
-
- properties = new Properties();
- properties.put(IntegrityAuditProperties.DB_DRIVER, DbAuditCompareEntriesTest.DEFAULT_DB_DRIVER);
- properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest");
- properties.put(IntegrityAuditProperties.DB_USER, DbAuditCompareEntriesTest.DEFAULT_DB_USER);
- properties.put(IntegrityAuditProperties.DB_PWD, DbAuditCompareEntriesTest.DEFAULT_DB_PWD);
- properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA");
- properties.put(IntegrityAuditProperties.NODE_TYPE, "pap");
-
- dbDriver = DbAuditCompareEntriesTest.DEFAULT_DB_DRIVER;
- dbUrl = "jdbc:h2:file:./sql/xacmlTest";
- dbUser = DbAuditCompareEntriesTest.DEFAULT_DB_USER;
- dbPwd = DbAuditCompareEntriesTest.DEFAULT_DB_PWD;
- siteName = "SiteA";
- nodeType = "pap";
- persistenceUnit = "testPapPU";
- resourceName = "siteA.pap1";
-
- //Clean the iaTest DB table for IntegrityAuditEntity entries
- cleanDb(persistenceUnit, properties);
-
- logger.info("setUp: Exiting");
- }
-
- @After
- public void tearDown() throws Exception {
- logger.info("tearDown: Entering");
- //nothing to do
- logger.info("tearDown: Exiting");
- }
-
- public void cleanDb(String persistenceUnit, Properties properties){
- logger.debug("cleanDb: enter");
-
- EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
-
- EntityManager em = emf.createEntityManager();
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- // Clean up the DB
- em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
-
- // commit transaction
- et.commit();
- em.close();
- logger.debug("cleanDb: exit");
- }
-
-
- /*
- * Tests that a comparison between hashsets is successful if
- * the entries match
- */
- @Test
- public void runAllTests() throws Exception {
- logger.info("runAllTests: Entering");
-
-
- testIntegrityAuditEntity();
- testBackupMonitorEntity();
- testStateManagementEntity();
- testForwardProgressEntity();
- testResourceRegistrationEntity();
-
- //clean up the IntegrityAuditEntity table
- cleanDb(persistenceUnit, properties);
-
- logger.info("runAllTests: Exit");
- }
-
-
- public void testIntegrityAuditEntity() throws Exception {
- logger.info("testIntegrityAuditEntity: Entering");
-
- dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
- DbAudit dbAudit = new DbAudit(dbDAO);
-
- String className = null;
- //There is only one entry IntegrityAuditEntity, but we will check anyway
- Set<String> classNameSet = dbDAO.getPersistenceClassNames();
- for(String c : classNameSet){
- if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){
- className = c;
- }
- }
- String resourceName1 = resourceName;
- String resourceName2 = resourceName;
-
- IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
- IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
- Date date = new Date();
-
- /*
- * Two entries with the same field values
- */
- entry1.setDesignated(false);
- entry1.setJdbcDriver(dbDriver);
- entry1.setJdbcPassword(dbPwd);
- entry1.setJdbcUrl(dbUrl);
- entry1.setJdbcUser(dbUser);
- entry1.setLastUpdated(date);
- entry1.setNodeType(nodeType);
- entry1.setPersistenceUnit(persistenceUnit);
- entry1.setResourceName(resourceName1);
- entry1.setSite(siteName);
-
- entry2 = SerializationUtils.clone(entry1);
-
- dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
- /*
- * Assert that there are no mismatches returned
- */
- assertTrue(result.isEmpty());
-
- /*
- * ************************************
- * Now test with a mis-matched entry
- * ************************************
- */
-
- /*
- * Change the entry2 to different designated value
- */
- entry2.setDesignated(true);
-
- myEntries = new HashMap<>();
- theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- result = dbAudit.compareEntries(myEntries, theirEntries);
-
- /*
- * Assert that there was one mismatch
- */
- assertEquals(1, result.size());
- logger.info("testIntegrityAuditEntity: Exit");
- }
-
- void testBackupMonitorEntity() throws Exception {
- logger.info("testBackupMonitorEntity: Entering");
-
- dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
- DbAudit dbAudit = new DbAudit(dbDAO);
-
- BackUpMonitorEntity entry1 = new BackUpMonitorEntity();
- BackUpMonitorEntity entry2 = new BackUpMonitorEntity();
-
- // Two entries with the same field values
-
-
- entry1.setFlag("flag1");
- entry1.setResourceNodeName("node1");
- entry1.setResourceName("resourceName");
- entry1.setTimeStamp(new Date());
-
- // Clone the first entry
- entry2 = SerializationUtils.clone(entry1);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- // Assert that there are no mismatches returned
-
- assertTrue(result.isEmpty());
-
-
- /* ************************************
- * Now test with a mis-matched entry
- * ************************************/
-
-
-
- // Change a field on entry2
-
- entry2.setFlag("flag2");
-
- myEntries = new HashMap<>();
- theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- //Assert that there was one mismatch
-
- assertEquals(1, result.size());
- logger.info("testBackupMonitorEntity: Exit");
- }
-
- void testStateManagementEntity() throws Exception {
- logger.info("testStateManagementEntity: Entering");
-
- dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
- DbAudit dbAudit = new DbAudit(dbDAO);
-
- StateManagementEntity entry1 = new StateManagementEntity();
- StateManagementEntity entry2 = new StateManagementEntity();
-
- // Two entries with the same field values
-
- entry1.setAdminState("locked");
- entry1.setAvailStatus("null");
- entry1.setModifiedDate(new Date());
- entry1.setOpState("enabled");
- entry1.setResourceName("myResource");
- entry1.setStandbyStatus("coldstandby");
-
- // Clone the first entry
- entry2 = SerializationUtils.clone(entry1);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- // Assert that there are no mismatches returned
-
- assertTrue(result.isEmpty());
-
-
- /* ************************************
- * Now test with a mis-matched entry
- * ************************************/
-
-
-
- // Change a field on entry2
-
- entry2.setAdminState("unlocked");
-
- myEntries = new HashMap<>();
- theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- //Assert that there was one mismatch
-
- assertEquals(1, result.size());
- logger.info("testStateManagementEntity: Exit");
- }
-
- void testForwardProgressEntity() throws Exception {
- logger.info("testForwardProgressEntity: Entering");
-
- dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
- DbAudit dbAudit = new DbAudit(dbDAO);
-
- ForwardProgressEntity entry1 = new ForwardProgressEntity();
- ForwardProgressEntity entry2 = new ForwardProgressEntity();
-
- // Two entries with the same field values
-
- entry1.setFpcCount(123L);
- entry1.setLastUpdated(new Date());
- entry1.setResourceName("myResource");
-
- // Clone the first entry
- entry2 = SerializationUtils.clone(entry1);
-
- HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
- HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- // Assert that there are no mismatches returned
-
- assertTrue(result.isEmpty());
-
-
- /* ************************************
- * Now test with a mis-matched entry
- * ************************************/
-
- // Change a field on entry2
-
- entry2.setFpcCount(321L);
-
- myEntries = new HashMap<>();
- theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- //Assert that there was one mismatch
-
- assertEquals(1, result.size());
- logger.info("testForwardProgressEntity: Exit");
- }
-
- void testResourceRegistrationEntity() throws Exception {
- logger.info("testResourceRegistrationEntity: Entering");
-
- dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
- DbAudit dbAudit = new DbAudit(dbDAO);
-
- ResourceRegistrationEntity entry1 = new ResourceRegistrationEntity();
- ResourceRegistrationEntity entry2 = new ResourceRegistrationEntity();
-
- // Two entries with the same field values
-
- entry1.setNodeType("pap");
- entry1.setLastUpdated(new Date());
- entry1.setResourceName("myResource");
- entry1.setResourceUrl("http://nowhere.com");
- entry1.setSite("site_1");
-
- // Clone the first entry
- entry2 = SerializationUtils.clone(entry1);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- // Assert that there are no mismatches returned
-
- assertTrue(result.isEmpty());
-
-
- /* ************************************
- * Now test with a mis-matched entry
- * ************************************/
-
- // Change a field on entry2
-
- entry2.setSite("site_1a");
-
- myEntries = new HashMap<>();
- theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- result = dbAudit.compareEntries(myEntries, theirEntries);
-
-
- //Assert that there was one mismatch
-
- assertEquals(1, result.size());
- logger.info("testResourceRegistrationEntity: Exit");
- }
+ private static Log logger = LogFactory.getLog(DbAuditCompareEntriesTest.class);
+ private DbDAO dbDAO;
+ private String persistenceUnit;
+ private Properties properties;
+ private String resourceName;
+ private String dbDriver;
+ private String dbUrl;
+ private String dbUser;
+ private String dbPwd;
+ private String siteName;
+ private String nodeType;
+ private static final String DEFAULT_DB_DRIVER = "org.h2.Driver";
+ private static final String DEFAULT_DB_USER = "sa";
+ private static final String DEFAULT_DB_PWD = "";
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+
+ properties = new Properties();
+ properties.put(IntegrityAuditProperties.DB_DRIVER, DbAuditCompareEntriesTest.DEFAULT_DB_DRIVER);
+ properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest");
+ properties.put(IntegrityAuditProperties.DB_USER, DbAuditCompareEntriesTest.DEFAULT_DB_USER);
+ properties.put(IntegrityAuditProperties.DB_PWD, DbAuditCompareEntriesTest.DEFAULT_DB_PWD);
+ properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA");
+ properties.put(IntegrityAuditProperties.NODE_TYPE, "pap");
+
+ dbDriver = DbAuditCompareEntriesTest.DEFAULT_DB_DRIVER;
+ dbUrl = "jdbc:h2:file:./sql/xacmlTest";
+ dbUser = DbAuditCompareEntriesTest.DEFAULT_DB_USER;
+ dbPwd = DbAuditCompareEntriesTest.DEFAULT_DB_PWD;
+ siteName = "SiteA";
+ nodeType = "pap";
+ persistenceUnit = "testPapPU";
+ resourceName = "siteA.pap1";
+
+ //Clean the iaTest DB table for IntegrityAuditEntity entries
+ cleanDb(persistenceUnit, properties);
+
+ logger.info("setUp: Exiting");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ logger.info("tearDown: Entering");
+ //nothing to do
+ logger.info("tearDown: Exiting");
+ }
+
+ public void cleanDb(String persistenceUnit, Properties properties){
+ logger.debug("cleanDb: enter");
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+
+ EntityManager em = emf.createEntityManager();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
+
+ et.begin();
+
+ // Clean up the DB
+ em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
+
+ // commit transaction
+ et.commit();
+ em.close();
+ logger.debug("cleanDb: exit");
+ }
+
+
+ /*
+ * Tests that a comparison between hashsets is successful if
+ * the entries match
+ */
+ @Test
+ public void runAllTests() throws Exception {
+ logger.info("runAllTests: Entering");
+
+
+ testIntegrityAuditEntity();
+ testBackupMonitorEntity();
+ testStateManagementEntity();
+ testForwardProgressEntity();
+ testResourceRegistrationEntity();
+
+ //clean up the IntegrityAuditEntity table
+ cleanDb(persistenceUnit, properties);
+
+ logger.info("runAllTests: Exit");
+ }
+
+
+ public void testIntegrityAuditEntity() throws Exception {
+ logger.info("testIntegrityAuditEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ String className = null;
+ //There is only one entry IntegrityAuditEntity, but we will check anyway
+ Set<String> classNameSet = dbDAO.getPersistenceClassNames();
+ for(String c : classNameSet){
+ if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){
+ className = c;
+ }
+ }
+ String resourceName1 = resourceName;
+ String resourceName2 = resourceName;
+
+ IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
+ IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
+ Date date = new Date();
+
+ /*
+ * Two entries with the same field values
+ */
+ entry1.setDesignated(false);
+ entry1.setJdbcDriver(dbDriver);
+ entry1.setJdbcPassword(dbPwd);
+ entry1.setJdbcUrl(dbUrl);
+ entry1.setJdbcUser(dbUser);
+ entry1.setLastUpdated(date);
+ entry1.setNodeType(nodeType);
+ entry1.setPersistenceUnit(persistenceUnit);
+ entry1.setResourceName(resourceName1);
+ entry1.setSite(siteName);
+
+ entry2 = SerializationUtils.clone(entry1);
+
+ dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2);
+
+ HashMap<Object, Object> myEntries = new HashMap<>();
+ HashMap<Object, Object> theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+ /*
+ * Assert that there are no mismatches returned
+ */
+ assertTrue(result.isEmpty());
+
+ /*
+ * ************************************
+ * Now test with a mis-matched entry
+ * ************************************
+ */
+
+ /*
+ * Change the entry2 to different designated value
+ */
+ entry2.setDesignated(true);
+
+ myEntries = new HashMap<>();
+ theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+ /*
+ * Assert that there was one mismatch
+ */
+ assertEquals(1, result.size());
+ logger.info("testIntegrityAuditEntity: Exit");
+ }
+
+ void testBackupMonitorEntity() throws Exception {
+ logger.info("testBackupMonitorEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ BackUpMonitorEntity entry1 = new BackUpMonitorEntity();
+ BackUpMonitorEntity entry2 = new BackUpMonitorEntity();
+
+ // Two entries with the same field values
+
+
+ entry1.setFlag("flag1");
+ entry1.setResourceNodeName("node1");
+ entry1.setResourceName("resourceName");
+ entry1.setTimeStamp(new Date());
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<>();
+ HashMap<Object, Object> theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+
+
+ // Change a field on entry2
+
+ entry2.setFlag("flag2");
+
+ myEntries = new HashMap<>();
+ theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testBackupMonitorEntity: Exit");
+ }
+
+ void testStateManagementEntity() throws Exception {
+ logger.info("testStateManagementEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ StateManagementEntity entry1 = new StateManagementEntity();
+ StateManagementEntity entry2 = new StateManagementEntity();
+
+ // Two entries with the same field values
+
+ entry1.setAdminState("locked");
+ entry1.setAvailStatus("null");
+ entry1.setModifiedDate(new Date());
+ entry1.setOpState("enabled");
+ entry1.setResourceName("myResource");
+ entry1.setStandbyStatus("coldstandby");
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<>();
+ HashMap<Object, Object> theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+
+
+ // Change a field on entry2
+
+ entry2.setAdminState("unlocked");
+
+ myEntries = new HashMap<>();
+ theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testStateManagementEntity: Exit");
+ }
+
+ void testForwardProgressEntity() throws Exception {
+ logger.info("testForwardProgressEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ ForwardProgressEntity entry1 = new ForwardProgressEntity();
+ ForwardProgressEntity entry2 = new ForwardProgressEntity();
+
+ // Two entries with the same field values
+
+ entry1.setFpcCount(123L);
+ entry1.setLastUpdated(new Date());
+ entry1.setResourceName("myResource");
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
+ HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+ // Change a field on entry2
+
+ entry2.setFpcCount(321L);
+
+ myEntries = new HashMap<>();
+ theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testForwardProgressEntity: Exit");
+ }
+
+ void testResourceRegistrationEntity() throws Exception {
+ logger.info("testResourceRegistrationEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ ResourceRegistrationEntity entry1 = new ResourceRegistrationEntity();
+ ResourceRegistrationEntity entry2 = new ResourceRegistrationEntity();
+
+ // Two entries with the same field values
+
+ entry1.setNodeType("pap");
+ entry1.setLastUpdated(new Date());
+ entry1.setResourceName("myResource");
+ entry1.setResourceUrl("http://nowhere.com");
+ entry1.setSite("site_1");
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<>();
+ HashMap<Object, Object> theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+ // Change a field on entry2
+
+ entry2.setSite("site_1a");
+
+ myEntries = new HashMap<>();
+ theirEntries = new HashMap<>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testResourceRegistrationEntity: Exit");
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java
index f9ed0ac70..5a8e20b26 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java
@@ -51,66 +51,66 @@ import org.springframework.mock.web.MockHttpServletResponse;
@RunWith(PowerMockRunner.class)
public class UpdateOthersPAPSTest {
- private static Logger logger = FlexLogger.getLogger(UpdateOthersPAPSTest.class);
- private static CommonClassDao commonClassDao;
- private HttpServletRequest request;
- private MockHttpServletResponse response;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
+ private static Logger logger = FlexLogger.getLogger(UpdateOthersPAPSTest.class);
+ private static CommonClassDao commonClassDao;
+ private HttpServletRequest request;
+ private MockHttpServletResponse response;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
commonClassDao = mock(CommonClassDao.class);
request = mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- List<Object> data = new ArrayList<>();
- PolicyDBDaoEntity entity = new PolicyDBDaoEntity();
- entity.setPolicyDBDaoUrl("http://localhost:8070/pap");
- entity.setUsername("test");
- entity.setPassword("test");
-
- PolicyDBDaoEntity entity1 = new PolicyDBDaoEntity();
- entity1.setPolicyDBDaoUrl("http://localhost:8071/pap");
- entity1.setUsername("test");
- entity1.setPassword("test");
-
- data.add(entity);
- data.add(entity1);
- System.setProperty("xacml.rest.pap.url","http://localhost:8070/pap");
- when(commonClassDao.getData(PolicyDBDaoEntity.class)).thenReturn(data);
- }
-
- @Test
- public void testNotifyOthersPAPsToUpdateConfigurations(){
- UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS();
- UpdateOthersPAPS.setCommonClassDao(commonClassDao);
- when(request.getParameter("action")).thenReturn("rename");
- when(request.getParameter("newPolicyName")).thenReturn("com.Config_newTest.1.json");
- when(request.getParameter("oldPolicyName")).thenReturn("com.Config_Test.1.json");
- updateOtherPaps.notifyOthersPAPsToUpdateConfigurations(request, response);
- try {
- JSONObject responseString = new JSONObject(response.getContentAsString());
- assertTrue(responseString.get("data").toString().contains("http://localhost:8071/pap"));
- } catch (Exception e) {
- fail();
- }
- }
-
- @PrepareForTest({Policy.class})
- @Test
- public void testUpdateConfiguration() throws Exception{
- UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS();
- UpdateObjectData data = new UpdateObjectData();
- PowerMockito.mockStatic(Policy.class);
- data.setNewPolicyName("com.Config_newTest.1.json");
- data.setOldPolicyName("com.Config_Test.1.json");
- data.setAction("rename");
- when(Policy.getConfigHome()).thenReturn("test");
- when(Policy.getActionHome()).thenReturn("test");
- File mockedFile = Mockito.mock(File.class);
- Mockito.when(mockedFile.exists()).thenReturn(true);
- PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(mockedFile);
- updateOtherPaps.updateConfiguration(data, response);
- assertTrue(response.getStatus() == 200);
- }
+ response = new MockHttpServletResponse();
+ List<Object> data = new ArrayList<>();
+ PolicyDBDaoEntity entity = new PolicyDBDaoEntity();
+ entity.setPolicyDBDaoUrl("http://localhost:8070/pap");
+ entity.setUsername("test");
+ entity.setPassword("test");
+
+ PolicyDBDaoEntity entity1 = new PolicyDBDaoEntity();
+ entity1.setPolicyDBDaoUrl("http://localhost:8071/pap");
+ entity1.setUsername("test");
+ entity1.setPassword("test");
+
+ data.add(entity);
+ data.add(entity1);
+ System.setProperty("xacml.rest.pap.url","http://localhost:8070/pap");
+ when(commonClassDao.getData(PolicyDBDaoEntity.class)).thenReturn(data);
+ }
+
+ @Test
+ public void testNotifyOthersPAPsToUpdateConfigurations(){
+ UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS();
+ UpdateOthersPAPS.setCommonClassDao(commonClassDao);
+ when(request.getParameter("action")).thenReturn("rename");
+ when(request.getParameter("newPolicyName")).thenReturn("com.Config_newTest.1.json");
+ when(request.getParameter("oldPolicyName")).thenReturn("com.Config_Test.1.json");
+ updateOtherPaps.notifyOthersPAPsToUpdateConfigurations(request, response);
+ try {
+ JSONObject responseString = new JSONObject(response.getContentAsString());
+ assertTrue(responseString.get("data").toString().contains("http://localhost:8071/pap"));
+ } catch (Exception e) {
+ fail();
+ }
+ }
+
+ @PrepareForTest({Policy.class})
+ @Test
+ public void testUpdateConfiguration() throws Exception{
+ UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS();
+ UpdateObjectData data = new UpdateObjectData();
+ PowerMockito.mockStatic(Policy.class);
+ data.setNewPolicyName("com.Config_newTest.1.json");
+ data.setOldPolicyName("com.Config_Test.1.json");
+ data.setAction("rename");
+ when(Policy.getConfigHome()).thenReturn("test");
+ when(Policy.getActionHome()).thenReturn("test");
+ File mockedFile = Mockito.mock(File.class);
+ Mockito.when(mockedFile.exists()).thenReturn(true);
+ PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(mockedFile);
+ updateOtherPaps.updateConfiguration(data, response);
+ assertTrue(response.getStatus() == 200);
+ }
}
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 5208ad7a7..717266264 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
@@ -81,7 +81,7 @@ import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import com.mockrunner.mock.web.MockServletInputStream;
public class XACMLPAPTest {
- private static final Log logger = LogFactory.getLog(XACMLPAPTest.class);
+ private static final Log logger = LogFactory.getLog(XACMLPAPTest.class);
private static final String ENVIRONMENT_HEADER = "Environment";
private List<String> headers = new ArrayList<>();
@@ -93,47 +93,47 @@ public class XACMLPAPTest {
private SessionFactory sessionFactory;
private CommonClassDao commonClassDao;
- private static final String DEFAULT_DB_DRIVER = "org.h2.Driver";
- private static final String DEFAULT_DB_USER = "sa";
- private static final String DEFAULT_DB_PWD = "";
+ private static final String DEFAULT_DB_DRIVER = "org.h2.Driver";
+ private static final String DEFAULT_DB_USER = "sa";
+ private static final String DEFAULT_DB_PWD = "";
- @Before
- public void setUpDB() throws Exception {
- logger.info("setUpDB: Entering");
+ @Before
+ public void setUpDB() throws Exception {
+ logger.info("setUpDB: Entering");
- Properties properties = new Properties();
- properties.put(IntegrityAuditProperties.DB_DRIVER, XACMLPAPTest.DEFAULT_DB_DRIVER);
- properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest");
- properties.put(IntegrityAuditProperties.DB_USER, XACMLPAPTest.DEFAULT_DB_USER);
- properties.put(IntegrityAuditProperties.DB_PWD, XACMLPAPTest.DEFAULT_DB_PWD);
- properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA");
- properties.put(IntegrityAuditProperties.NODE_TYPE, "pap");
+ Properties properties = new Properties();
+ properties.put(IntegrityAuditProperties.DB_DRIVER, XACMLPAPTest.DEFAULT_DB_DRIVER);
+ properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest");
+ properties.put(IntegrityAuditProperties.DB_USER, XACMLPAPTest.DEFAULT_DB_USER);
+ properties.put(IntegrityAuditProperties.DB_PWD, XACMLPAPTest.DEFAULT_DB_PWD);
+ properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA");
+ properties.put(IntegrityAuditProperties.NODE_TYPE, "pap");
- //Clean the iaTest DB table for IntegrityAuditEntity entries
- cleanDb("testPapPU", properties);
+ //Clean the iaTest DB table for IntegrityAuditEntity entries
+ cleanDb("testPapPU", properties);
- logger.info("setUpDB: Exiting");
- }
+ logger.info("setUpDB: Exiting");
+ }
- public void cleanDb(String persistenceUnit, Properties properties){
- logger.debug("cleanDb: enter");
+ public void cleanDb(String persistenceUnit, Properties properties){
+ logger.debug("cleanDb: enter");
- EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- EntityManager em = emf.createEntityManager();
- // Start a transaction
- EntityTransaction et = em.getTransaction();
+ EntityManager em = emf.createEntityManager();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
- et.begin();
+ et.begin();
- // Clean up the DB
- em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
+ // Clean up the DB
+ em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
- // commit transaction
- et.commit();
- em.close();
- logger.debug("cleanDb: exit");
- }
+ // commit transaction
+ et.commit();
+ em.close();
+ logger.debug("cleanDb: exit");
+ }
@Before
public void setUp() throws ServletException {
@@ -584,166 +584,166 @@ public class XACMLPAPTest {
@Test
public void testCommonCreateDictionary() throws IOException, SQLException, ServletException {
- new DictionaryController(commonClassDao);
- new ActionPolicyDictionaryController(commonClassDao);
- new SafePolicyController(commonClassDao);
- new DescriptiveDictionaryController(commonClassDao);
- List<Object> object = new ArrayList<>();
+ new DictionaryController(commonClassDao);
+ new ActionPolicyDictionaryController(commonClassDao);
+ new SafePolicyController(commonClassDao);
+ new DescriptiveDictionaryController(commonClassDao);
+ List<Object> object = new ArrayList<>();
object.add(new Category());
when(commonClassDao.getDataById(Category.class, "shortName", "resource")).thenReturn(object);
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- String json = "{\"dictionaryFields\": {\"onapName\": \"testMMRestAPI1\",\"description\": \"testing update response message\"}}";
- dictionaryTestSetup(false, "OnapName", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\": {\"xacmlId\": \"testMMRestAPI1\",\"datatypeBean\": {\"shortName\": \"string\"}, \"description\": \"testing update\",\"priority\": \"High\",\"userDataTypeValues\": [{\"attributeValues\": \"testAttr\"}, {\"attributeValues\": \"testAttr2\"}, {\"attributeValues\": \"testAttr3\"}]}}";
- dictionaryTestSetup(false, "Attribute", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl.com\",\"method\":\"GET\",\"description\":\"test create\",\"body\":\"Testing Create\",\"headers\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\",\"number\":\"test\"}]}}";
- dictionaryTestSetup(false, "Action", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"scopeName\":\"testMMRestAPI1\",\"description\":\"test\",\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\",\"number\":\"test\"}]}}";
- dictionaryTestSetup(false, "DescriptiveScope", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"riskName\":\"testMMrestAPI1\",\"description\":\"test\"}}";
- dictionaryTestSetup(false, "RiskType", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"message\":\"test\",\"riskType\":\"testMMrestAPI1\"}}";
- dictionaryTestSetup(false, "SafePolicyWarning", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ String json = "{\"dictionaryFields\": {\"onapName\": \"testMMRestAPI1\",\"description\": \"testing update response message\"}}";
+ dictionaryTestSetup(false, "OnapName", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\": {\"xacmlId\": \"testMMRestAPI1\",\"datatypeBean\": {\"shortName\": \"string\"}, \"description\": \"testing update\",\"priority\": \"High\",\"userDataTypeValues\": [{\"attributeValues\": \"testAttr\"}, {\"attributeValues\": \"testAttr2\"}, {\"attributeValues\": \"testAttr3\"}]}}";
+ dictionaryTestSetup(false, "Attribute", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl.com\",\"method\":\"GET\",\"description\":\"test create\",\"body\":\"Testing Create\",\"headers\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\",\"number\":\"test\"}]}}";
+ dictionaryTestSetup(false, "Action", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"scopeName\":\"testMMRestAPI1\",\"description\":\"test\",\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\",\"number\":\"test\"}]}}";
+ dictionaryTestSetup(false, "DescriptiveScope", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"riskName\":\"testMMrestAPI1\",\"description\":\"test\"}}";
+ dictionaryTestSetup(false, "RiskType", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"message\":\"test\",\"riskType\":\"testMMrestAPI1\"}}";
+ dictionaryTestSetup(false, "SafePolicyWarning", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
}
@Test
public void testDecisionCreateDictionary() throws IOException, SQLException, ServletException {
- new DecisionPolicyDictionaryController(commonClassDao);
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- String json = "{\"dictionaryFields\":{\"xacmlId\":\"testMMRestAPI1\",\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"test\",\"priority\":\"High\"}}";
- dictionaryTestSetup(false, "Settings", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"bbid\":\"BB1\",\"workstep\":\"1\",\"treatments\":\"Manual Handling,Abort,Retry\"}}";
- dictionaryTestSetup(false, "RainyDayTreatments", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ new DecisionPolicyDictionaryController(commonClassDao);
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ String json = "{\"dictionaryFields\":{\"xacmlId\":\"testMMRestAPI1\",\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"test\",\"priority\":\"High\"}}";
+ dictionaryTestSetup(false, "Settings", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"bbid\":\"BB1\",\"workstep\":\"1\",\"treatments\":\"Manual Handling,Abort,Retry\"}}";
+ dictionaryTestSetup(false, "RainyDayTreatments", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
}
@Test
public void testMSCreateDictionary() throws IOException, SQLException, ServletException {
- new MicroServiceDictionaryController(commonClassDao);
- new PolicyScopeDictionaryController(commonClassDao);
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- String json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"descriptionValue\":\"test\"}}";
- dictionaryTestSetup(false, "MicroServiceLocation", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"descriptionValue\":\"test\"}}";
- dictionaryTestSetup(false, "MicroServiceConfigName", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"description\":\"test\"}}";
- dictionaryTestSetup(false, "DCAEUUID", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
- dictionaryTestSetup(false, "PolicyScopeService", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
- dictionaryTestSetup(false, "PolicyScopeResource", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
- dictionaryTestSetup(false, "PolicyScopeType", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
- dictionaryTestSetup(false, "PolicyScopeClosedLoop", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
- json = "{\"dictionaryFields\":{\"groupName\":\"testMMrestAPI1\",\"description\":\"testing\"},\"groupPolicyScopeListData1\":{\"resource\":\"ANY\",\"type\":\"ANY\",\"service\":\"ANY\",\"closedloop\":\"ANY\"}}";
- dictionaryTestSetup(false, "GroupPolicyScopeList", json);
- // send Request to PAP
- pap.service(httpServletRequest, httpServletResponse);
- // Verify
- Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ new MicroServiceDictionaryController(commonClassDao);
+ new PolicyScopeDictionaryController(commonClassDao);
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ String json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"descriptionValue\":\"test\"}}";
+ dictionaryTestSetup(false, "MicroServiceLocation", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"descriptionValue\":\"test\"}}";
+ dictionaryTestSetup(false, "MicroServiceConfigName", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"description\":\"test\"}}";
+ dictionaryTestSetup(false, "DCAEUUID", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
+ dictionaryTestSetup(false, "PolicyScopeService", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
+ dictionaryTestSetup(false, "PolicyScopeResource", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
+ dictionaryTestSetup(false, "PolicyScopeType", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"name\":\"testApiANY\",\"descriptionValue\":\"default test\"}}";
+ dictionaryTestSetup(false, "PolicyScopeClosedLoop", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ json = "{\"dictionaryFields\":{\"groupName\":\"testMMrestAPI1\",\"description\":\"testing\"},\"groupPolicyScopeListData1\":{\"resource\":\"ANY\",\"type\":\"ANY\",\"service\":\"ANY\",\"closedloop\":\"ANY\"}}";
+ dictionaryTestSetup(false, "GroupPolicyScopeList", json);
+ // send Request to PAP
+ pap.service(httpServletRequest, httpServletResponse);
+ // Verify
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
}
private void dictionaryTestSetup(Boolean updateFlag, String dictionaryType, String json) throws IOException, SQLException {
@@ -790,23 +790,23 @@ public class XACMLPAPTest {
@Test
public void getDictionary() throws ServletException, IOException{
- String[] dictionarys = new String[]{"Attribute", "OnapName", "Action", "BRMSParamTemplate","VSCLAction"
- ,"VNFType","PEPOptions","Varbind","Service","Site", "Settings", "RainyDayTreatments",
- "DescriptiveScope", "ActionList", "ProtocolList", "Zone", "SecurityZone",
- "PrefixList", "AddressGroup", "ServiceGroup", "ServiceList", "TermList",
- "MicroServiceLocation", "MicroServiceConfigName", "DCAEUUID", "MicroServiceModels",
- "PolicyScopeService", "PolicyScopeResource", "PolicyScopeType", "PolicyScopeClosedLoop",
- "GroupPolicyScopeList", "RiskType", "SafePolicyWarning", "MicroServiceDictionary"};
- for(String dictionary : dictionarys){
- httpServletRequest = Mockito.mock(HttpServletRequest.class);
- httpServletResponse = new MockHttpServletResponse();
- Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn("DEVL");
- Mockito.when(httpServletRequest.getMethod()).thenReturn("GET");
- Mockito.when(httpServletRequest.getParameter("apiflag")).thenReturn("api");
- Mockito.when(httpServletRequest.getParameter("dictionaryType")).thenReturn(dictionary);
- pap.service(httpServletRequest, httpServletResponse);
- assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus());
- }
+ String[] dictionarys = new String[]{"Attribute", "OnapName", "Action", "BRMSParamTemplate","VSCLAction"
+ ,"VNFType","PEPOptions","Varbind","Service","Site", "Settings", "RainyDayTreatments",
+ "DescriptiveScope", "ActionList", "ProtocolList", "Zone", "SecurityZone",
+ "PrefixList", "AddressGroup", "ServiceGroup", "ServiceList", "TermList",
+ "MicroServiceLocation", "MicroServiceConfigName", "DCAEUUID", "MicroServiceModels",
+ "PolicyScopeService", "PolicyScopeResource", "PolicyScopeType", "PolicyScopeClosedLoop",
+ "GroupPolicyScopeList", "RiskType", "SafePolicyWarning", "MicroServiceDictionary"};
+ for(String dictionary : dictionarys){
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = new MockHttpServletResponse();
+ Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn("DEVL");
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("GET");
+ Mockito.when(httpServletRequest.getParameter("apiflag")).thenReturn("api");
+ Mockito.when(httpServletRequest.getParameter("dictionaryType")).thenReturn(dictionary);
+ pap.service(httpServletRequest, httpServletResponse);
+ assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus());
+ }
}
@Test
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java
index b57c187c7..dfadf8e81 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java
@@ -28,46 +28,46 @@ import org.onap.policy.pap.xacml.rest.PAPRestConfig;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
public class PAPRestConfigTest {
- @Test
- public void testSetAndGet() {
- String testVal = "testVal";
-
- PAPRestConfig.setDbDriver(testVal);
- assertEquals(PAPRestConfig.getDbDriver(), testVal);
- PAPRestConfig.setDbUrl(testVal);
- assertEquals(PAPRestConfig.getDbUrl(), testVal);
- PAPRestConfig.setDbUserName(testVal);
- assertEquals(PAPRestConfig.getDbUserName(), testVal);
- PAPRestConfig.setDbPassword(testVal);
- assertEquals(PAPRestConfig.getDbPassword(), testVal);
- }
-
- @Test
- public void testInit() {
- String driver = "org.mariadb.jdbc.Driver";
- String url = "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=true&sessionVariables=max_statement_time=30";
- String user = "policy_user";
- String password = "policy_user";
-
- PAPRestConfig config = new PAPRestConfig();
- config.init();
-
- assertEquals(PAPRestConfig.getDbDriver(), driver);
- assertEquals(PAPRestConfig.getDbUrl(), url);
- assertEquals(PAPRestConfig.getDbUserName(), user);
- assertEquals(PAPRestConfig.getDbPassword(), password);
-
- // Test hibernate
- BasicDataSource source = (BasicDataSource)config.getDataSource();
- assertEquals(source.getDriverClassName(), driver);
- assertEquals(source.getUrl(), url);
- assertEquals(source.getUsername(), user);
- assertEquals(source.getPassword(), password);
-
- SessionFactory factory = config.getSessionFactory(source);
- assertEquals(factory.isClosed(), false);
-
- HibernateTransactionManager manager = config.getTransactionManager(factory);
- assertEquals(manager.getSessionFactory(), factory);
- }
+ @Test
+ public void testSetAndGet() {
+ String testVal = "testVal";
+
+ PAPRestConfig.setDbDriver(testVal);
+ assertEquals(PAPRestConfig.getDbDriver(), testVal);
+ PAPRestConfig.setDbUrl(testVal);
+ assertEquals(PAPRestConfig.getDbUrl(), testVal);
+ PAPRestConfig.setDbUserName(testVal);
+ assertEquals(PAPRestConfig.getDbUserName(), testVal);
+ PAPRestConfig.setDbPassword(testVal);
+ assertEquals(PAPRestConfig.getDbPassword(), testVal);
+ }
+
+ @Test
+ public void testInit() {
+ String driver = "org.mariadb.jdbc.Driver";
+ String url = "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=true&sessionVariables=max_statement_time=30";
+ String user = "policy_user";
+ String password = "policy_user";
+
+ PAPRestConfig config = new PAPRestConfig();
+ config.init();
+
+ assertEquals(PAPRestConfig.getDbDriver(), driver);
+ assertEquals(PAPRestConfig.getDbUrl(), url);
+ assertEquals(PAPRestConfig.getDbUserName(), user);
+ assertEquals(PAPRestConfig.getDbPassword(), password);
+
+ // Test hibernate
+ BasicDataSource source = (BasicDataSource)config.getDataSource();
+ assertEquals(source.getDriverClassName(), driver);
+ assertEquals(source.getUrl(), url);
+ assertEquals(source.getUsername(), user);
+ assertEquals(source.getPassword(), password);
+
+ SessionFactory factory = config.getSessionFactory(source);
+ assertEquals(factory.isClosed(), false);
+
+ HibernateTransactionManager manager = config.getTransactionManager(factory);
+ assertEquals(manager.getSessionFactory(), factory);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java
index 15bdf8962..32d7dedd3 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java
@@ -27,11 +27,11 @@ import org.junit.Test;
import org.mockito.Mockito;
public class WebConfigTest {
- @Test(expected=NullPointerException.class)
- public void testNegativeStartup() throws ServletException {
- WebConfig init = new WebConfig();
- ServletContext container = Mockito.mock(ServletContext.class);
- init.onStartup(container);
- fail("Expecting an exception.");
- }
+ @Test(expected=NullPointerException.class)
+ public void testNegativeStartup() throws ServletException {
+ WebConfig init = new WebConfig();
+ ServletContext container = Mockito.mock(ServletContext.class);
+ init.onStartup(container);
+ fail("Expecting an exception.");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java
index 3630889b0..36d40278b 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java
@@ -26,44 +26,44 @@ import org.junit.Test;
import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
public class XACMLPapServletTest {
- @Test
- public void testSetAndGet() {
- String systemKey = "xacml.properties";
- String testVal = "testVal";
- XACMLPapServlet servlet = new XACMLPapServlet();
-
- // Set the system property temporarily
- String oldProperty = System.getProperty(systemKey);
- System.setProperty(systemKey, "xacml.pap.properties");
-
- assertNotNull(XACMLPapServlet.getConfigHome());
- assertNotNull(XACMLPapServlet.getActionHome());
- assertEquals(XACMLPapServlet.getPersistenceUnit(), "XACML-PAP-REST");
+ @Test
+ public void testSetAndGet() {
+ String systemKey = "xacml.properties";
+ String testVal = "testVal";
+ XACMLPapServlet servlet = new XACMLPapServlet();
- //assertNull(XACMLPapServlet.getEmf());
- //assertNull(XACMLPapServlet.getPDPFile());
- //assertNull(XACMLPapServlet.getPAPEngine());
- //assertNull(servlet.getIa());
-
- XACMLPapServlet.setPapDbDriver(testVal);
- assertEquals(XACMLPapServlet.getPapDbDriver(), testVal);
- XACMLPapServlet.setPapDbUrl(testVal);
- assertEquals(XACMLPapServlet.getPapDbUrl(), testVal);
- XACMLPapServlet.setPapDbUser(testVal);
- assertEquals(XACMLPapServlet.getPapDbUser(), testVal);
- XACMLPapServlet.setPapDbPassword(testVal);
- assertEquals(XACMLPapServlet.getPapDbPassword(), testVal);
- XACMLPapServlet.setMsOnapName(testVal);
- assertEquals(XACMLPapServlet.getMsOnapName(), testVal);
- XACMLPapServlet.setMsPolicyName(testVal);
- assertEquals(XACMLPapServlet.getMsPolicyName(), testVal);
-
- // Restore the original system property
- if (oldProperty != null) {
- System.setProperty(systemKey, oldProperty);
- }
- else {
- System.clearProperty(systemKey);
- }
- }
+ // Set the system property temporarily
+ String oldProperty = System.getProperty(systemKey);
+ System.setProperty(systemKey, "xacml.pap.properties");
+
+ assertNotNull(XACMLPapServlet.getConfigHome());
+ assertNotNull(XACMLPapServlet.getActionHome());
+ assertEquals(XACMLPapServlet.getPersistenceUnit(), "XACML-PAP-REST");
+
+ //assertNull(XACMLPapServlet.getEmf());
+ //assertNull(XACMLPapServlet.getPDPFile());
+ //assertNull(XACMLPapServlet.getPAPEngine());
+ //assertNull(servlet.getIa());
+
+ XACMLPapServlet.setPapDbDriver(testVal);
+ assertEquals(XACMLPapServlet.getPapDbDriver(), testVal);
+ XACMLPapServlet.setPapDbUrl(testVal);
+ assertEquals(XACMLPapServlet.getPapDbUrl(), testVal);
+ XACMLPapServlet.setPapDbUser(testVal);
+ assertEquals(XACMLPapServlet.getPapDbUser(), testVal);
+ XACMLPapServlet.setPapDbPassword(testVal);
+ assertEquals(XACMLPapServlet.getPapDbPassword(), testVal);
+ XACMLPapServlet.setMsOnapName(testVal);
+ assertEquals(XACMLPapServlet.getMsOnapName(), testVal);
+ XACMLPapServlet.setMsPolicyName(testVal);
+ assertEquals(XACMLPapServlet.getMsPolicyName(), testVal);
+
+ // Restore the original system property
+ if (oldProperty != null) {
+ System.setProperty(systemKey, oldProperty);
+ }
+ else {
+ System.clearProperty(systemKey);
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java
index 839af2fdc..841ba28fc 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java
@@ -24,33 +24,33 @@ import static org.junit.Assert.*;
import org.junit.Test;
public class SearchDataTest {
-
-
- @Test
- public void testSearchData(){
- String data = "Test";
- SearchData searchData = new SearchData();
- searchData.setQuery(data);
- searchData.setPolicyType(data);
- searchData.setOnapName(data);
- searchData.setDescriptiveScope(data);
- searchData.setClosedLooppolicyType(data);
- searchData.setD2Service(data);
- searchData.setVnfType(data);
- searchData.setPolicyStatus(data);
- searchData.setVproAction(data);
- searchData.setServiceType(data);
- searchData.setBindTextSearch(data);
- assertEquals(data, searchData.getQuery());
- assertEquals(data, searchData.getPolicyType());
- assertEquals(data, searchData.getDescriptiveScope());
- assertEquals(data, searchData.getClosedLooppolicyType());
- assertEquals(data, searchData.getOnapName());
- assertEquals(data, searchData.getD2Service());
- assertEquals(data, searchData.getVnfType());
- assertEquals(data, searchData.getPolicyStatus());
- assertEquals(data, searchData.getVproAction());
- assertEquals(data, searchData.getServiceType());
- assertEquals(data, searchData.getBindTextSearch());
- }
+
+
+ @Test
+ public void testSearchData(){
+ String data = "Test";
+ SearchData searchData = new SearchData();
+ searchData.setQuery(data);
+ searchData.setPolicyType(data);
+ searchData.setOnapName(data);
+ searchData.setDescriptiveScope(data);
+ searchData.setClosedLooppolicyType(data);
+ searchData.setD2Service(data);
+ searchData.setVnfType(data);
+ searchData.setPolicyStatus(data);
+ searchData.setVproAction(data);
+ searchData.setServiceType(data);
+ searchData.setBindTextSearch(data);
+ assertEquals(data, searchData.getQuery());
+ assertEquals(data, searchData.getPolicyType());
+ assertEquals(data, searchData.getDescriptiveScope());
+ assertEquals(data, searchData.getClosedLooppolicyType());
+ assertEquals(data, searchData.getOnapName());
+ assertEquals(data, searchData.getD2Service());
+ assertEquals(data, searchData.getVnfType());
+ assertEquals(data, searchData.getPolicyStatus());
+ assertEquals(data, searchData.getVproAction());
+ assertEquals(data, searchData.getServiceType());
+ assertEquals(data, searchData.getBindTextSearch());
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java
index 2c1bc1c53..094994e41 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java
@@ -24,16 +24,16 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class UpdateObjectDataTest {
-
- @Test
- public void testClosedLoopFaultTrapDatas(){
- UpdateObjectData updateObject = new UpdateObjectData();
- updateObject.setAction("Rename");
- assertTrue("Rename".equals(updateObject.getAction()));
- updateObject.setNewPolicyName("com.Config_test1.1.json");
- assertTrue("com.Config_test1.1.json".equals(updateObject.getNewPolicyName()));
- updateObject.setOldPolicyName("com.Config_test.1.json");
- assertTrue("com.Config_test.1.json".equals(updateObject.getOldPolicyName()));
- }
-
+
+ @Test
+ public void testClosedLoopFaultTrapDatas(){
+ UpdateObjectData updateObject = new UpdateObjectData();
+ updateObject.setAction("Rename");
+ assertTrue("Rename".equals(updateObject.getAction()));
+ updateObject.setNewPolicyName("com.Config_test1.1.json");
+ assertTrue("com.Config_test1.1.json".equals(updateObject.getNewPolicyName()));
+ updateObject.setOldPolicyName("com.Config_test.1.json");
+ assertTrue("com.Config_test.1.json".equals(updateObject.getOldPolicyName()));
+ }
+
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java
index cb09becf3..a04859b27 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java
@@ -40,102 +40,102 @@ import com.att.research.xacml.util.XACMLProperties;
public class ActionPolicyTest {
-
- private static Logger logger = FlexLogger.getLogger(ActionPolicyTest.class);
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
- List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
- Map<String, String> attributeMap = new HashMap<>();
- ActionPolicy component = null;
-
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
-
- dynamicRuleAlgorithmLabels.add("test");
- dynamicRuleAlgorithmField1.add("testField1");
- dynamicRuleAlgorithmCombo.add("testCombo");
- dynamicRuleAlgorithmField2.add("testField2");
-
- policyAdapter.setPolicyName("Test.Action_junitTest");
- policyAdapter.setPolicyDescription("test");
- policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
- policyAdapter.setPolicyType("Action");
- policyAdapter.setEditPolicy(false);
- policyAdapter.setDomainDir("Test");
- policyAdapter.setNewFileName("Test.Action_junitTest.1.xml");
- policyAdapter.setHighestVersion(1);
- policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
-
- policyAdapter.setActionDictHeader("");
- policyAdapter.setActionDictType("REST");
- policyAdapter.setActionDictUrl("onap.org");
- policyAdapter.setActionDictMethod("GET");
- policyAdapter.setActionAttribute("test");
- policyAdapter.setActionBody("test");
-
- policyAdapter.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
- policyAdapter.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
- policyAdapter.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
- policyAdapter.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
-
- attributeMap.put("java", "test");
- policyAdapter.setDynamicFieldConfigAttributes(attributeMap);
-
- component = new ActionPolicy(policyAdapter, null);
+
+ private static Logger logger = FlexLogger.getLogger(ActionPolicyTest.class);
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
+ Map<String, String> attributeMap = new HashMap<>();
+ ActionPolicy component = null;
+
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
+
+ dynamicRuleAlgorithmLabels.add("test");
+ dynamicRuleAlgorithmField1.add("testField1");
+ dynamicRuleAlgorithmCombo.add("testCombo");
+ dynamicRuleAlgorithmField2.add("testField2");
+
+ policyAdapter.setPolicyName("Test.Action_junitTest");
+ policyAdapter.setPolicyDescription("test");
+ policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
+ policyAdapter.setPolicyType("Action");
+ policyAdapter.setEditPolicy(false);
+ policyAdapter.setDomainDir("Test");
+ policyAdapter.setNewFileName("Test.Action_junitTest.1.xml");
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
+
+ policyAdapter.setActionDictHeader("");
+ policyAdapter.setActionDictType("REST");
+ policyAdapter.setActionDictUrl("onap.org");
+ policyAdapter.setActionDictMethod("GET");
+ policyAdapter.setActionAttribute("test");
+ policyAdapter.setActionBody("test");
+
+ policyAdapter.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ policyAdapter.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
+ policyAdapter.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ policyAdapter.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+
+ attributeMap.put("java", "test");
+ policyAdapter.setDynamicFieldConfigAttributes(attributeMap);
+
+ component = new ActionPolicy(policyAdapter, null);
logger.info("setUp: exit");
- }
+ }
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {
- }
+ /**
+ * @throws java.lang.Exception
+ */
+ @After
+ public void tearDown() throws Exception {
+ }
/* *//**
- * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#savePolicies()}.
- */
- @Test
- public void testSavePolicies() {
+ * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#savePolicies()}.
+ */
+ @Test
+ public void testSavePolicies() {
ActionPolicy mockAction = Mockito.mock(component.getClass());
-
+
Map<String, String> successMap = new HashMap<>();
- successMap.put("success", "success");
+ successMap.put("success", "success");
try {
- when(mockAction.savePolicies()).thenReturn(successMap);
- successMap = mockAction.savePolicies();
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- }
- assertEquals(successMap.get("success"),"success");
- }
-
- /**
- * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#prepareToSave()}.
- */
- @Test
- public void testPrepareToSave() {
- logger.debug("test PrepareToSave Policy: enter");
- boolean response = true;
-
- try {
- response = component.prepareToSave();
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- }
- assertTrue(response);
-
- }
+ when(mockAction.savePolicies()).thenReturn(successMap);
+ successMap = mockAction.savePolicies();
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ }
+ assertEquals(successMap.get("success"),"success");
+ }
+
+ /**
+ * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#prepareToSave()}.
+ */
+ @Test
+ public void testPrepareToSave() {
+ logger.debug("test PrepareToSave Policy: enter");
+ boolean response = true;
+
+ try {
+ response = component.prepareToSave();
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ }
+ assertTrue(response);
+
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java
index 9c5f71f55..542d45e3e 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java
@@ -31,38 +31,38 @@ import com.att.research.xacml.api.pap.PAPException;
import java.nio.charset.StandardCharsets;
public class ClosedLoopPolicyTest {
- @Rule
+ @Rule
public ExpectedException thrown = ExpectedException.none();
- @Test
- public void testConstructor1() {
- thrown.expect(NullPointerException.class);
- ClosedLoopPolicy policy = new ClosedLoopPolicy();
- policy.getCorrectPolicyDataObject();
- }
-
- @Test
- public void testConstructor2() {
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- ClosedLoopPolicy policy = new ClosedLoopPolicy(policyAdapter);
- assertNull(policy.getCorrectPolicyDataObject());
- }
-
- @Test
- public void testReadFile() throws IOException {
- thrown.expect(IOException.class);
- String read = ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8);
- fail("Expecting an exception.");
- }
-
- @Test
- public void testPrepareToSave() throws PAPException {
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- ClosedLoopPolicy policy = new ClosedLoopPolicy(policyAdapter);
- policyAdapter.setHighestVersion(1);
- policyAdapter.setPolicyType("Config");
- policyAdapter.setNewFileName("foo.xml");
- policy.prepareToSave();
- assertEquals(policy.isPreparedToSave(), true);
- }
+ @Test
+ public void testConstructor1() {
+ thrown.expect(NullPointerException.class);
+ ClosedLoopPolicy policy = new ClosedLoopPolicy();
+ policy.getCorrectPolicyDataObject();
+ }
+
+ @Test
+ public void testConstructor2() {
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ ClosedLoopPolicy policy = new ClosedLoopPolicy(policyAdapter);
+ assertNull(policy.getCorrectPolicyDataObject());
+ }
+
+ @Test
+ public void testReadFile() throws IOException {
+ thrown.expect(IOException.class);
+ String read = ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8);
+ fail("Expecting an exception.");
+ }
+
+ @Test
+ public void testPrepareToSave() throws PAPException {
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ ClosedLoopPolicy policy = new ClosedLoopPolicy(policyAdapter);
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyType("Config");
+ policyAdapter.setNewFileName("foo.xml");
+ policy.prepareToSave();
+ assertEquals(policy.isPreparedToSave(), true);
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java
index e16dd9889..3cf3128dd 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java
@@ -41,104 +41,104 @@ import com.att.research.xacml.util.XACMLProperties;
public class DecisionPolicyTest {
- private static Logger logger = FlexLogger.getLogger(DecisionPolicyTest.class);
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- RainyDayParams rainyday = new RainyDayParams();
- Map<String, String> attributeMap = new HashMap<>();
- Map<String, String> treatmentMap = new HashMap<>();
- Map<String, String> settingsMap = new HashMap<>();
- List<String> errorCodeList = new LinkedList<>();
- List<String> treatmentList = new LinkedList<>();
- 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<>();
- DecisionPolicy component = null;
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
-
- policyAdapter.setPolicyName("Test.Decision_junitTest.1.xml");
- policyAdapter.setPolicyDescription("testing");
- policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
- policyAdapter.setPolicyType("Decision");
- policyAdapter.setEditPolicy(false);
- policyAdapter.setDomainDir("Test");
- policyAdapter.setNewFileName("/src/test/resources/Test/client.properties");
- policyAdapter.setHighestVersion(1);
- policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
- policyAdapter.setOnapName("MSO");
-
- //rainy day attributes
- attributeMap.put("ServiceType", "S");
- attributeMap.put("VNFType", "V");
- attributeMap.put("BB_ID", "testBB");
- attributeMap.put("WorkStep", "1");
-
- dynamicRuleAlgorithmLabels.add("test1");
- dynamicRuleAlgorithmField1.add("testField1");
- dynamicRuleAlgorithmCombo.add("testruleCombo");
- dynamicRuleAlgorithmField2.add("testField2");
-
- policyAdapter.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
- policyAdapter.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
- policyAdapter.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
- policyAdapter.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
- policyAdapter.setDynamicVariableList(dynamicVariableList);
- policyAdapter.setDynamicSettingsMap(settingsMap);
- policyAdapter.setDataTypeList(dataTypeList);
-
- policyAdapter.setDynamicFieldConfigAttributes(attributeMap);
- policyAdapter.setRainydayMap(treatmentMap);
- policyAdapter.setRainyday(rainyday);
-
- component = new DecisionPolicy(policyAdapter, null);
+ private static Logger logger = FlexLogger.getLogger(DecisionPolicyTest.class);
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ RainyDayParams rainyday = new RainyDayParams();
+ Map<String, String> attributeMap = new HashMap<>();
+ Map<String, String> treatmentMap = new HashMap<>();
+ Map<String, String> settingsMap = new HashMap<>();
+ List<String> errorCodeList = new LinkedList<>();
+ List<String> treatmentList = new LinkedList<>();
+ 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<>();
+ DecisionPolicy component = null;
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
+
+ policyAdapter.setPolicyName("Test.Decision_junitTest.1.xml");
+ policyAdapter.setPolicyDescription("testing");
+ policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
+ policyAdapter.setPolicyType("Decision");
+ policyAdapter.setEditPolicy(false);
+ policyAdapter.setDomainDir("Test");
+ policyAdapter.setNewFileName("/src/test/resources/Test/client.properties");
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
+ policyAdapter.setOnapName("MSO");
+
+ //rainy day attributes
+ attributeMap.put("ServiceType", "S");
+ attributeMap.put("VNFType", "V");
+ attributeMap.put("BB_ID", "testBB");
+ attributeMap.put("WorkStep", "1");
+
+ dynamicRuleAlgorithmLabels.add("test1");
+ dynamicRuleAlgorithmField1.add("testField1");
+ dynamicRuleAlgorithmCombo.add("testruleCombo");
+ dynamicRuleAlgorithmField2.add("testField2");
+
+ policyAdapter.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ policyAdapter.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
+ policyAdapter.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ policyAdapter.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+ policyAdapter.setDynamicVariableList(dynamicVariableList);
+ policyAdapter.setDynamicSettingsMap(settingsMap);
+ policyAdapter.setDataTypeList(dataTypeList);
+
+ policyAdapter.setDynamicFieldConfigAttributes(attributeMap);
+ policyAdapter.setRainydayMap(treatmentMap);
+ policyAdapter.setRainyday(rainyday);
+
+ component = new DecisionPolicy(policyAdapter, null);
logger.info("setUp: exit");
- }
+ }
- /**
- * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy#savePolicies()}.
- */
- @Test
- public void testSavePolicies() {
+ /**
+ * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy#savePolicies()}.
+ */
+ @Test
+ public void testSavePolicies() {
DecisionPolicy mockDecision = Mockito.mock(component.getClass());
Map<String, String> successMap = new HashMap<>();
- successMap.put("success", "success");
-
+ successMap.put("success", "success");
+
+ try {
+ when(mockDecision.savePolicies()).thenReturn(successMap);
+ successMap = mockDecision.savePolicies();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ assertEquals(successMap.get("success"),"success");
+ }
+
+ /**
+ * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy#prepareToSave()}.
+ */
+ @Test
+ public void testPrepareToSaveRainyDay() {
+ logger.debug("test PrepareToSave Policy: enter");
+ policyAdapter.setRuleProvider("Rainy_Day");
+ component = new DecisionPolicy(policyAdapter, null);
+ boolean response = false;
+
try {
- when(mockDecision.savePolicies()).thenReturn(successMap);
- successMap = mockDecision.savePolicies();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- assertEquals(successMap.get("success"),"success");
- }
-
- /**
- * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy#prepareToSave()}.
- */
- @Test
- public void testPrepareToSaveRainyDay() {
- logger.debug("test PrepareToSave Policy: enter");
- policyAdapter.setRuleProvider("Rainy_Day");
- component = new DecisionPolicy(policyAdapter, null);
- boolean response = false;
-
- try {
- response = component.prepareToSave();
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- }
- assertTrue(response);
- }
+ response = component.prepareToSave();
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ }
+ assertTrue(response);
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java
index 0dd919a35..7f3ebb3b4 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java
@@ -42,103 +42,103 @@ import com.att.research.xacml.util.XACMLProperties;
public class FirewallConfigPolicyTest {
-
- private static Logger logger = FlexLogger.getLogger(FirewallConfigPolicyTest.class);
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- Map<String, String> attributeMap = new HashMap<>();
- FirewallConfigPolicy component = null;
+
+ private static Logger logger = FlexLogger.getLogger(FirewallConfigPolicyTest.class);
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ Map<String, String> attributeMap = new HashMap<>();
+ FirewallConfigPolicy component = null;
FirewallConfigPolicy mockFWConfig = null;
private XACMLPAPTest papTest;
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- logger.info("setup: enter");
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
-
- policyAdapter.setPolicyName("FWjunitTest");
- policyAdapter.setPolicyDescription("test");
- policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
- policyAdapter.setPolicyType("Config");
- policyAdapter.setConfigPolicyType("Firewall Config");
- policyAdapter.setEditPolicy(false);
- policyAdapter.setDomainDir("Test");
- policyAdapter.setNewFileName("Test.Config_FW_junitTest.1.xml");
- policyAdapter.setHighestVersion(1);
- policyAdapter.setVersion(String.valueOf(1));
- policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
- policyAdapter.setRuleID("");
- policyAdapter.setConfigName("testname");
- policyAdapter.setGuard("True");
- policyAdapter.setRiskLevel("3");
- policyAdapter.setRiskType("RiskTest");
- policyAdapter.setSecurityZone("CraigSecurityZone");
- policyAdapter.setUserId("API");
-
- attributeMap.put("testJunits", "test");
- policyAdapter.setDynamicFieldConfigAttributes(attributeMap);
-
- component = new FirewallConfigPolicy(policyAdapter);
- mockFWConfig = Mockito.mock(FirewallConfigPolicy.class);
- papTest = new XACMLPAPTest();
- papTest.setDBDao();
+ /**
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setup: enter");
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
+
+ policyAdapter.setPolicyName("FWjunitTest");
+ policyAdapter.setPolicyDescription("test");
+ policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
+ policyAdapter.setPolicyType("Config");
+ policyAdapter.setConfigPolicyType("Firewall Config");
+ policyAdapter.setEditPolicy(false);
+ policyAdapter.setDomainDir("Test");
+ policyAdapter.setNewFileName("Test.Config_FW_junitTest.1.xml");
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setVersion(String.valueOf(1));
+ policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
+ policyAdapter.setRuleID("");
+ policyAdapter.setConfigName("testname");
+ policyAdapter.setGuard("True");
+ policyAdapter.setRiskLevel("3");
+ policyAdapter.setRiskType("RiskTest");
+ policyAdapter.setSecurityZone("CraigSecurityZone");
+ policyAdapter.setUserId("API");
+
+ attributeMap.put("testJunits", "test");
+ policyAdapter.setDynamicFieldConfigAttributes(attributeMap);
+
+ component = new FirewallConfigPolicy(policyAdapter);
+ mockFWConfig = Mockito.mock(FirewallConfigPolicy.class);
+ papTest = new XACMLPAPTest();
+ papTest.setDBDao();
logger.info("setUp: exit");
-
- }
-
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {
- }
-
- /**
- * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy#savePolicies()}.
- */
- @Test
- public void testSavePolicies() {
+
+ }
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @After
+ public void tearDown() throws Exception {
+ }
+
+ /**
+ * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy#savePolicies()}.
+ */
+ @Test
+ public void testSavePolicies() {
Map<String, String> successMap = new HashMap<>();
successMap.put("success", "success");
- try {
- when(mockFWConfig.savePolicies()).thenReturn(successMap);
- successMap = mockFWConfig.savePolicies();
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- }
- }
-
- /**
- * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy#prepareToSave()}.
- */
- @Test
- public void testPrepareToSave() {
- logger.debug("test prepareToSave Policy: enter");
-
- boolean response = false;
- try {
- when(mockFWConfig.prepareToSave()).thenReturn(true);
- response = mockFWConfig.prepareToSave();
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- }
- assertTrue(response);
-
- }
-
- @Test
- public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
- FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy();
- Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class , String.class);
- method.setAccessible(true);
- String jsonBody= "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}";
- String prevJsonBody = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\",\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\",\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\",\"enabled\":true,\"log\":true}]}";
+ try {
+ when(mockFWConfig.savePolicies()).thenReturn(successMap);
+ successMap = mockFWConfig.savePolicies();
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ }
+ }
+
+ /**
+ * Test method for {@link org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy#prepareToSave()}.
+ */
+ @Test
+ public void testPrepareToSave() {
+ logger.debug("test prepareToSave Policy: enter");
+
+ boolean response = false;
+ try {
+ when(mockFWConfig.prepareToSave()).thenReturn(true);
+ response = mockFWConfig.prepareToSave();
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ }
+ assertTrue(response);
+
+ }
+
+ @Test
+ public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
+ FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy();
+ Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class , String.class);
+ method.setAccessible(true);
+ String jsonBody= "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}";
+ String prevJsonBody = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\",\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\",\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\",\"enabled\":true,\"log\":true}]}";
assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody, prevJsonBody));
- }
-
- @Test
+ }
+
+ @Test
public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy();
Method method = firewallConfigPolicy.getClass().getDeclaredMethod("insertFirewallDicionaryData", String.class);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
index a47c2be58..f698bc0c0 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
@@ -41,71 +41,71 @@ import java.util.Collections;
@RunWith(PowerMockRunner.class)
public class MicroServicePolicyTest {
- @Rule
+ @Rule
public ExpectedException thrown = ExpectedException.none();
- @Test
- public void testConstructor1() {
- thrown.expect(NullPointerException.class);
- MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy();
- policy.getCorrectPolicyDataObject();
- fail("Expected an exception");
- }
-
- @Test
- public void testConstructor2() {
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
- assertNull(policy.getCorrectPolicyDataObject());
- }
-
- @PrepareForTest({MicroServiceConfigPolicy.class})
- @Test
- public void testPrepareToSave() throws Exception {
- // Need to mock internal dictionary retrieval
- CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl);
- when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null);
-
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
- policyAdapter.setHighestVersion(1);
- policyAdapter.setPolicyType("Config");
- policyAdapter.setNewFileName("foo.xml");
- policyAdapter.setJsonBody("{ \"version\": \"1.0\"}");
- policyAdapter.setServiceType("foo");
- policy.prepareToSave();
- assertEquals(policy.isPreparedToSave(), true);
- }
-
- @Test
- public void testCreateConstructor1() {
- CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null);
- assertNotNull(model);
- }
-
- @PrepareForTest({CreateNewMicroServiceModel.class})
- @Test
- public void testCreateModel() throws Exception {
- // Mock file retrieval
- File testFile = new File("testFile");
- File[] testList = new File[1];
- testList[0] = testFile;
- File impl = Mockito.mock(File.class);
- PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
- when(impl.listFiles()).thenReturn(testList);
- when(impl.isFile()).thenReturn(true);
+ @Test
+ public void testConstructor1() {
+ thrown.expect(NullPointerException.class);
+ MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy();
+ policy.getCorrectPolicyDataObject();
+ fail("Expected an exception");
+ }
- // Mock internal dictionary retrieval
- CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
- when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+ @Test
+ public void testConstructor2() {
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
+ assertNull(policy.getCorrectPolicyDataObject());
+ }
- // Test create methods
- String testFileName = "testFile.zip";
- String testVal = "testVal";
- CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal);
- model.addValuesToNewModel(".xmi");
- model.saveImportService();
- }
+ @PrepareForTest({MicroServiceConfigPolicy.class})
+ @Test
+ public void testPrepareToSave() throws Exception {
+ // Need to mock internal dictionary retrieval
+ CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class);
+ PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl);
+ when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null);
+
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyType("Config");
+ policyAdapter.setNewFileName("foo.xml");
+ policyAdapter.setJsonBody("{ \"version\": \"1.0\"}");
+ policyAdapter.setServiceType("foo");
+ policy.prepareToSave();
+ assertEquals(policy.isPreparedToSave(), true);
+ }
+
+ @Test
+ public void testCreateConstructor1() {
+ CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null);
+ assertNotNull(model);
+ }
+
+ @PrepareForTest({CreateNewMicroServiceModel.class})
+ @Test
+ public void testCreateModel() throws Exception {
+ // Mock file retrieval
+ File testFile = new File("testFile");
+ File[] testList = new File[1];
+ testList[0] = testFile;
+ File impl = Mockito.mock(File.class);
+ PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
+ when(impl.listFiles()).thenReturn(testList);
+ when(impl.isFile()).thenReturn(true);
+
+ // Mock internal dictionary retrieval
+ CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
+ PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
+ when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+
+ // Test create methods
+ String testFileName = "testFile.zip";
+ String testVal = "testVal";
+ CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal);
+ model.addValuesToNewModel(".xmi");
+ model.saveImportService();
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java
index 7b9be6891..25e94c1a2 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java
@@ -41,65 +41,65 @@ import java.util.Collections;
@RunWith(PowerMockRunner.class)
public class OptimizationConfigPolicyTest {
- @Rule
+ @Rule
public ExpectedException thrown = ExpectedException.none();
- @Test
- public void testConstructor1() {
- thrown.expect(NullPointerException.class);
- OptimizationConfigPolicy policy = new OptimizationConfigPolicy();
- policy.getCorrectPolicyDataObject();
- fail("Expected an exception");
- }
-
- @Test
- public void testConstructor2() {
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
- assertNull(policy.getCorrectPolicyDataObject());
- }
-
- @PrepareForTest({OptimizationConfigPolicy.class})
- @Test
- public void testPrepareToSave() throws Exception {
- // Need to mock internal dictionary retrieval
- CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl);
- when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null);
-
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
- policyAdapter.setHighestVersion(1);
- policyAdapter.setPolicyType("Config");
- policyAdapter.setNewFileName("foo.xml");
- policyAdapter.setJsonBody("{ \"version\": \"1.0\"}");
- policyAdapter.setServiceType("foo");
- policy.prepareToSave();
- assertEquals(true, policy.isPreparedToSave());
- }
-
- @PrepareForTest({CreateNewOptimizationModel.class})
- @Test
- public void testCreateModel() throws Exception {
- // Mock file retrieval
- File testFile = new File("testFile");
- File[] testList = new File[1];
- testList[0] = testFile;
- File impl = Mockito.mock(File.class);
- PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
- when(impl.listFiles()).thenReturn(testList);
- when(impl.isFile()).thenReturn(true);
+ @Test
+ public void testConstructor1() {
+ thrown.expect(NullPointerException.class);
+ OptimizationConfigPolicy policy = new OptimizationConfigPolicy();
+ policy.getCorrectPolicyDataObject();
+ fail("Expected an exception");
+ }
- // Mock internal dictionary retrieval
- CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
- when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+ @Test
+ public void testConstructor2() {
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
+ assertNull(policy.getCorrectPolicyDataObject());
+ }
- // Test create methods
- String testFileName = "testFile.zip";
- String testVal = "testVal";
- CreateNewOptimizationModel model = new CreateNewOptimizationModel(testFileName, testVal, testVal, testVal, testVal);
- model.addValuesToNewModel();
- model.saveImportService();
- }
+ @PrepareForTest({OptimizationConfigPolicy.class})
+ @Test
+ public void testPrepareToSave() throws Exception {
+ // Need to mock internal dictionary retrieval
+ CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class);
+ PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl);
+ when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null);
+
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyType("Config");
+ policyAdapter.setNewFileName("foo.xml");
+ policyAdapter.setJsonBody("{ \"version\": \"1.0\"}");
+ policyAdapter.setServiceType("foo");
+ policy.prepareToSave();
+ assertEquals(true, policy.isPreparedToSave());
+ }
+
+ @PrepareForTest({CreateNewOptimizationModel.class})
+ @Test
+ public void testCreateModel() throws Exception {
+ // Mock file retrieval
+ File testFile = new File("testFile");
+ File[] testList = new File[1];
+ testList[0] = testFile;
+ File impl = Mockito.mock(File.class);
+ PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
+ when(impl.listFiles()).thenReturn(testList);
+ when(impl.isFile()).thenReturn(true);
+
+ // Mock internal dictionary retrieval
+ CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
+ PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
+ when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+
+ // Test create methods
+ String testFileName = "testFile.zip";
+ String testVal = "testVal";
+ CreateNewOptimizationModel model = new CreateNewOptimizationModel(testFileName, testVal, testVal, testVal, testVal);
+ model.addValuesToNewModel();
+ model.saveImportService();
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java
index c098bf4fa..bdfd8db33 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java
@@ -65,538 +65,538 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
public class PolicyDBDaoTest extends Mockito{
- private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class);
-
- PolicyDBDaoTestClass d;
- PolicyDBDao dbd;
- PolicyDBDao dbd2;
- EntityManagerFactory emf;
- private Path repository;
- StdEngine stdEngine = null;
-
- @Before
- public void init() throws PAPException, IOException{
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
- emf = Persistence.createEntityManagerFactory("testPapPU");
- EntityManager em = emf.createEntityManager();
- em.getTransaction().begin();
- try{
- em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
- em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
- em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
- em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
- em.createQuery("DELETE FROM PdpEntity").executeUpdate();
- em.createQuery("DELETE FROM GroupEntity").executeUpdate();
-
- em.getTransaction().commit();
- } catch(Exception e){
- logger.error("Exception Occured"+e);
- em.getTransaction().rollback();
- }
- em.close();
- try {
- dbd = PolicyDBDao.getPolicyDBDaoInstance(emf);
- dbd2 = PolicyDBDao.getPolicyDBDaoInstance(emf);
- } catch (Exception e) {
- Assert.fail();
- }
-
- d = PolicyDBDao.getPolicyDBDaoTestClass();
- PolicyDBDao.setJunit(true);
- repository = Paths.get("src/test/resources/pdps");
+ private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class);
+
+ PolicyDBDaoTestClass d;
+ PolicyDBDao dbd;
+ PolicyDBDao dbd2;
+ EntityManagerFactory emf;
+ private Path repository;
+ StdEngine stdEngine = null;
+
+ @Before
+ public void init() throws PAPException, IOException{
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
+ emf = Persistence.createEntityManagerFactory("testPapPU");
+ EntityManager em = emf.createEntityManager();
+ em.getTransaction().begin();
+ try{
+ em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
+ em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
+ em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
+ em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
+ em.createQuery("DELETE FROM PdpEntity").executeUpdate();
+ em.createQuery("DELETE FROM GroupEntity").executeUpdate();
+
+ em.getTransaction().commit();
+ } catch(Exception e){
+ logger.error("Exception Occured"+e);
+ em.getTransaction().rollback();
+ }
+ em.close();
+ try {
+ dbd = PolicyDBDao.getPolicyDBDaoInstance(emf);
+ dbd2 = PolicyDBDao.getPolicyDBDaoInstance(emf);
+ } catch (Exception e) {
+ Assert.fail();
+ }
+
+ d = PolicyDBDao.getPolicyDBDaoTestClass();
+ PolicyDBDao.setJunit(true);
+ repository = Paths.get("src/test/resources/pdps");
stdEngine = new StdEngine(repository);
dbd.setPapEngine(stdEngine);
- }
-
- @After
- public void cleanUp(){
- PolicyDBDao.setJunit(false);
- EntityManager em = emf.createEntityManager();
- em.getTransaction().begin();
- try{
- em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
- em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
- em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
- em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
- em.createQuery("DELETE FROM PdpEntity").executeUpdate();
- em.createQuery("DELETE FROM GroupEntity").executeUpdate();
-
- em.getTransaction().commit();
- } catch(Exception e){
- em.getTransaction().rollback();
- }
- em.close();
- try {
- FileUtils.forceDelete(new File("src/test/resources/junitTestCreatedDirectory"));
- } catch (IOException e) {
- //could not delete
- }
- }
-
- @Test
- public void getConfigFileTest(){
- PolicyRestAdapter pra = new PolicyRestAdapter();
- pra.setConfigType(ConfigPolicy.JSON_CONFIG);
- String configFile = d.getConfigFile("Config_mypolicy.xml", "org.onap", pra);
- Assert.assertEquals("org.onap.Config_mypolicy.json", configFile);
- //yes, we can do action files too even though they don't have configs
- configFile = d.getConfigFile("Action_mypolicy.xml", "org.onap", pra);
- Assert.assertEquals("org.onap.Action_mypolicy.json", configFile);
- }
-
- @Test
- public void createFromPolicyObject(){
- Policy policyObject = new ConfigPolicy();
- policyObject.policyAdapter = new PolicyRestAdapter();
- policyObject.policyAdapter.setConfigName("testpolicy1");
- 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");
- PolicyType policyTypeObject = new PolicyType();
- policyObject.policyAdapter.setPolicyData(policyTypeObject);
- ClassLoader classLoader = getClass().getClassLoader();
- PolicyType policyConfig = new PolicyType();
+ }
+
+ @After
+ public void cleanUp(){
+ PolicyDBDao.setJunit(false);
+ EntityManager em = emf.createEntityManager();
+ em.getTransaction().begin();
+ try{
+ em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
+ em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
+ em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
+ em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
+ em.createQuery("DELETE FROM PdpEntity").executeUpdate();
+ em.createQuery("DELETE FROM GroupEntity").executeUpdate();
+
+ em.getTransaction().commit();
+ } catch(Exception e){
+ em.getTransaction().rollback();
+ }
+ em.close();
+ try {
+ FileUtils.forceDelete(new File("src/test/resources/junitTestCreatedDirectory"));
+ } catch (IOException e) {
+ //could not delete
+ }
+ }
+
+ @Test
+ public void getConfigFileTest(){
+ PolicyRestAdapter pra = new PolicyRestAdapter();
+ pra.setConfigType(ConfigPolicy.JSON_CONFIG);
+ String configFile = d.getConfigFile("Config_mypolicy.xml", "org.onap", pra);
+ Assert.assertEquals("org.onap.Config_mypolicy.json", configFile);
+ //yes, we can do action files too even though they don't have configs
+ configFile = d.getConfigFile("Action_mypolicy.xml", "org.onap", pra);
+ Assert.assertEquals("org.onap.Action_mypolicy.json", configFile);
+ }
+
+ @Test
+ public void createFromPolicyObject(){
+ Policy policyObject = new ConfigPolicy();
+ policyObject.policyAdapter = new PolicyRestAdapter();
+ policyObject.policyAdapter.setConfigName("testpolicy1");
+ 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");
+ PolicyType policyTypeObject = new PolicyType();
+ policyObject.policyAdapter.setPolicyData(policyTypeObject);
+ ClassLoader classLoader = getClass().getClassLoader();
+ PolicyType policyConfig = new PolicyType();
policyConfig.setVersion(Integer.toString(1));
policyConfig.setPolicyId("");
policyConfig.setTarget(new TargetType());
policyObject.policyAdapter.setData(policyConfig);
- mock(XACMLPolicyWriter.class);
- 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();
- }
-
- EntityManager getData = emf.createEntityManager();
- Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name");
- getDataQuery.setParameter("scope", "com");
- getDataQuery.setParameter("name","Config_SampleTest1206.1.xml");
- PolicyEntity result = null;
- try{
- result = (PolicyEntity)getDataQuery.getSingleResult();
- } catch(Exception e){
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- String expectedData;
- try {
- expectedData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
- } catch (IOException e1) {
- expectedData = "";
- }
- Assert.assertEquals(expectedData, result.getPolicyData());
- getData.close();
- result = null;
-
- transaction.commitTransaction();
- Assert.assertFalse(transaction.isTransactionOpen());
- }
-
- @Test
- public void groupTransactions(){
- PolicyDBDaoTransaction group = dbd.getNewTransaction();
- String groupName = "test group 1";
- try{
- group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group","testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- EntityManager em = emf.createEntityManager();
- Query getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
- getGroup.setParameter("deleted", false);
- List<?> groups = getGroup.getResultList();
- if(groups.size() != 1){
- Assert.fail();
- }
- GroupEntity groupEntity = (GroupEntity)groups.get(0);
- em.close();
- Assert.assertEquals(groupName, groupEntity.getgroupName());
- Assert.assertEquals("this is a test group", groupEntity.getDescription());
- group = dbd.getNewTransaction();
- try{
- OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName),Paths.get("/"));
- group.deleteGroup(groupToDelete, null,"testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- em = emf.createEntityManager();
- getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
- getGroup.setParameter("deleted", false);
- groups = getGroup.getResultList();
- if(groups.size() != 0){
- System.out.println("Group size: "+groups.size());
- Assert.fail();
- }
- em.close();
- //add a pdp to a group
- group = dbd.getNewTransaction();
- try{
- group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- group = dbd.getNewTransaction();
- try{
- group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", "the main pdp", 3232, "testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- em = emf.createEntityManager();
- Query getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
- getPdp.setParameter("pdpId", "http://localhost:4344/pdp/");
- getPdp.setParameter("deleted", false);
- List<?> pdps = getPdp.getResultList();
- if(pdps.size() != 1){
- System.out.println("Group size: "+pdps.size());
- Assert.fail();
- }
- PdpEntity pdp = (PdpEntity)pdps.get(0);
- Assert.assertEquals(groupName, pdp.getGroup().getgroupName());
- Assert.assertEquals(pdp.getPdpName(), "primary");
- em.close();
- group = dbd.getNewTransaction();
- try{
- group.removePdpFromGroup("http://localhost:4344/pdp/","testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- em = emf.createEntityManager();
- getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
- getPdp.setParameter("pdpId", "http://localhost:4344/pdp/");
- getPdp.setParameter("deleted", false);
- pdps = getPdp.getResultList();
- if(pdps.size() != 0){
- System.out.println("Group size: "+pdps.size());
- Assert.fail();
- }
- em.close();
-
- //add some pdps to groups
- group = dbd.getNewTransaction();
- try{
- group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- group = dbd.getNewTransaction();
- try{
- group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
-
- group = dbd.getNewTransaction();
- try{
- group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- group = dbd.getNewTransaction();
- try{
- group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- em = emf.createEntityManager();
- getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted");
- getPdp.setParameter("deleted", false);
- pdps = getPdp.getResultList();
- for(Object o : pdps){
- Assert.assertEquals("testgroup1",((PdpEntity)o).getGroup().getgroupName());
- }
- em.close();
-
- group = dbd.getNewTransaction();
- try{
- OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"),Paths.get("/"));
- OnapPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/"));
- group.deleteGroup(groupToDelete, groupToMoveTo,"testuser");
- group.commitTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
- em = emf.createEntityManager();
- getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup.setParameter("groupId", "testgroup1");
- getGroup.setParameter("deleted", false);
- groups = getGroup.getResultList();
- if(groups.size() != 0){
- System.out.println("Group size: "+groups.size());
- Assert.fail();
- }
- em.close();
-
- em = emf.createEntityManager();
- getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted");
- getPdp.setParameter("deleted", false);
- pdps = getPdp.getResultList();
- for(Object o : pdps){
- Assert.assertEquals("testgroup2",((PdpEntity)o).getGroup().getgroupName());
- }
- em.close();
-
- group = dbd.getNewTransaction();
- try{
- OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/"));
- OnapPDPGroup groupToMoveTo = null;
- group.deleteGroup(groupToDelete, groupToMoveTo,"testuser");
- group.commitTransaction();
- Assert.fail();
- } catch(PolicyDBException pe){
- //good, can't delete group with pdps
- group.rollbackTransaction();
- } catch(Exception e){
- group.rollbackTransaction();
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
-
- //update group
- OnapPDPGroup pdpGroup = new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/"));
- group = dbd.getNewTransaction();
- try{
- group.updateGroup(pdpGroup, "testuser");
- group.commitTransaction();
- }catch (Exception e){
- logger.error("Exception Occured"+e);
- group.rollbackTransaction();
- Assert.fail();
- }
- em = emf.createEntityManager();
- getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup.setParameter("groupId", "newtestgroup2");
- getGroup.setParameter("deleted", false);
- groups = getGroup.getResultList();
- if(groups.size() != 1){
- System.out.println("Group size: "+groups.size());
- Assert.fail();
- }
- em.close();
- em = emf.createEntityManager();
- getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup.setParameter("groupId", "testgroup2");
- getGroup.setParameter("deleted", false);
- groups = getGroup.getResultList();
- if(groups.size() != 0){
- System.out.println("Group size: "+groups.size());
- Assert.fail();
- }
- em.close();
- }
-
- @Ignore
- @Test
- public void threadingStabilityTest(){
- if(logger.isDebugEnabled()){
- logger.debug("\n\n****************************"
- + "threadingStabilityTest() entry"
- + "******************************\n\n");
- }
-
- PolicyDBDaoTransaction t = dbd.getNewTransaction();
- Assert.assertTrue(t.isTransactionOpen());
- try {
- //Add 1000 ms to the timeout just to be sure it actually times out
- int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000;
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n sleepTime = " + sleepTime
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) {
- logger.error("Exception Occured"+e);
- }
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Assert.assertFalse(t.isTransactionOpen() = " + t.isTransactionOpen() + ")"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Assert.assertFalse(t.isTransactionOpen());
-
-
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n a = dbd.getNewTransaction() "
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- PolicyDBDaoTransaction a = dbd.getNewTransaction();
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Assert.assertTrue(a.isTransactionOpen() = " + a.isTransactionOpen() + ")"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Assert.assertTrue(a.isTransactionOpen());
-
- try {
- //Add 1000 ms to the timeout just to be sure it actually times out
- int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000;
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n sleepTime = " + sleepTime
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) {
- logger.error("Exception Occured"+e);
- }
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n b = dbd.getNewTransaction() "
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- PolicyDBDaoTransaction b = dbd.getNewTransaction();
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Assert.assertFalse(a.isTransactionOpen() = " + a.isTransactionOpen() + ")"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Assert.assertFalse(a.isTransactionOpen());
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Assert.assertTrue(b.isTransactionOpen() = " + b.isTransactionOpen() + ")"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Assert.assertTrue(b.isTransactionOpen());
- b.close();
-
-
-
- //Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms
- System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT,"1000");
- //And let's lengthen the transaction timeout to 5000 ms
- System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT,"5000");
- //get a transacton
- PolicyDBDaoTransaction t1 = dbd.getNewTransaction();
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Assert.assertTrue(t1.isTransactionOpen());
- //while it is open, get another from a different DB Dao so it will not collide on the synchronized code segment
- //but will collide at the DB. Remember that the wait time is only 1000 ms
- try {
- //Now the 2nd transaction has a wait timeout in 1000 ms
- PolicyDBDaoTransaction t2 = dbd2.getNewTransaction();
- /*
- * Give it plenty of time to time out the second transaction
- * It will actually hang right here until it either gets the lock from the DB or the
- * request for the DB lock times out. The timers are very sloppy so, I have given
- * this plenty of leeway.
- */
-
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Thread.sleep(3000)"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- Thread.sleep(3000);
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")"
- + "\n Assert.assertFalse(t2.isTransactionOpen() = " + t2.isTransactionOpen() + ")"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- //Assert.assertTrue(t1.isTransactionOpen());
- //Assert.assertFalse(t2.isTransactionOpen());
-
- Assert.fail("\n\nTransaction timeout of 1000 ms exceeded without a PersistenceException\n\n");
- } catch (PersistenceException e) {
- //success
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
- + "\n SUCCESS! Transaction Wait Timeout worked!"
- + "\n Caught PersistenceException = " + e
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- } catch (Exception e) {
- // failure due to some other reason
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE"
- + "\n Caught Exception = " + e
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- logger.error("Exception Occured"+e);
- Assert.fail();
- }
-
- if(logger.isDebugEnabled()){
- Date date= new java.util.Date();
- logger.debug("\n\nthreadingStabilityTest() exit"
- + "\n TimeStamp = " + date.getTime()
- + "\n\n");
- }
- }
+ mock(XACMLPolicyWriter.class);
+ 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();
+ }
+
+ EntityManager getData = emf.createEntityManager();
+ Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name");
+ getDataQuery.setParameter("scope", "com");
+ getDataQuery.setParameter("name","Config_SampleTest1206.1.xml");
+ PolicyEntity result = null;
+ try{
+ result = (PolicyEntity)getDataQuery.getSingleResult();
+ } catch(Exception e){
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ String expectedData;
+ try {
+ expectedData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
+ } catch (IOException e1) {
+ expectedData = "";
+ }
+ Assert.assertEquals(expectedData, result.getPolicyData());
+ getData.close();
+ result = null;
+
+ transaction.commitTransaction();
+ Assert.assertFalse(transaction.isTransactionOpen());
+ }
+
+ @Test
+ public void groupTransactions(){
+ PolicyDBDaoTransaction group = dbd.getNewTransaction();
+ String groupName = "test group 1";
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group","testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ EntityManager em = emf.createEntityManager();
+ Query getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
+ getGroup.setParameter("deleted", false);
+ List<?> groups = getGroup.getResultList();
+ if(groups.size() != 1){
+ Assert.fail();
+ }
+ GroupEntity groupEntity = (GroupEntity)groups.get(0);
+ em.close();
+ Assert.assertEquals(groupName, groupEntity.getgroupName());
+ Assert.assertEquals("this is a test group", groupEntity.getDescription());
+ group = dbd.getNewTransaction();
+ try{
+ OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName),Paths.get("/"));
+ group.deleteGroup(groupToDelete, null,"testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 0){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+ //add a pdp to a group
+ group = dbd.getNewTransaction();
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ group = dbd.getNewTransaction();
+ try{
+ group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", "the main pdp", 3232, "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ Query getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
+ getPdp.setParameter("pdpId", "http://localhost:4344/pdp/");
+ getPdp.setParameter("deleted", false);
+ List<?> pdps = getPdp.getResultList();
+ if(pdps.size() != 1){
+ System.out.println("Group size: "+pdps.size());
+ Assert.fail();
+ }
+ PdpEntity pdp = (PdpEntity)pdps.get(0);
+ Assert.assertEquals(groupName, pdp.getGroup().getgroupName());
+ Assert.assertEquals(pdp.getPdpName(), "primary");
+ em.close();
+ group = dbd.getNewTransaction();
+ try{
+ group.removePdpFromGroup("http://localhost:4344/pdp/","testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
+ getPdp.setParameter("pdpId", "http://localhost:4344/pdp/");
+ getPdp.setParameter("deleted", false);
+ pdps = getPdp.getResultList();
+ if(pdps.size() != 0){
+ System.out.println("Group size: "+pdps.size());
+ Assert.fail();
+ }
+ em.close();
+
+ //add some pdps to groups
+ group = dbd.getNewTransaction();
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ group = dbd.getNewTransaction();
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+
+ group = dbd.getNewTransaction();
+ try{
+ group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ group = dbd.getNewTransaction();
+ try{
+ group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted");
+ getPdp.setParameter("deleted", false);
+ pdps = getPdp.getResultList();
+ for(Object o : pdps){
+ Assert.assertEquals("testgroup1",((PdpEntity)o).getGroup().getgroupName());
+ }
+ em.close();
+
+ group = dbd.getNewTransaction();
+ try{
+ OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"),Paths.get("/"));
+ OnapPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/"));
+ group.deleteGroup(groupToDelete, groupToMoveTo,"testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", "testgroup1");
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 0){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+
+ em = emf.createEntityManager();
+ getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted");
+ getPdp.setParameter("deleted", false);
+ pdps = getPdp.getResultList();
+ for(Object o : pdps){
+ Assert.assertEquals("testgroup2",((PdpEntity)o).getGroup().getgroupName());
+ }
+ em.close();
+
+ group = dbd.getNewTransaction();
+ try{
+ OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/"));
+ OnapPDPGroup groupToMoveTo = null;
+ group.deleteGroup(groupToDelete, groupToMoveTo,"testuser");
+ group.commitTransaction();
+ Assert.fail();
+ } catch(PolicyDBException pe){
+ //good, can't delete group with pdps
+ group.rollbackTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+
+ //update group
+ OnapPDPGroup pdpGroup = new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/"));
+ group = dbd.getNewTransaction();
+ try{
+ group.updateGroup(pdpGroup, "testuser");
+ group.commitTransaction();
+ }catch (Exception e){
+ logger.error("Exception Occured"+e);
+ group.rollbackTransaction();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", "newtestgroup2");
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 1){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", "testgroup2");
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 0){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+ }
+
+ @Ignore
+ @Test
+ public void threadingStabilityTest(){
+ if(logger.isDebugEnabled()){
+ logger.debug("\n\n****************************"
+ + "threadingStabilityTest() entry"
+ + "******************************\n\n");
+ }
+
+ PolicyDBDaoTransaction t = dbd.getNewTransaction();
+ Assert.assertTrue(t.isTransactionOpen());
+ try {
+ //Add 1000 ms to the timeout just to be sure it actually times out
+ int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000;
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n sleepTime = " + sleepTime
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ logger.error("Exception Occured"+e);
+ }
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertFalse(t.isTransactionOpen() = " + t.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertFalse(t.isTransactionOpen());
+
+
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n a = dbd.getNewTransaction() "
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ PolicyDBDaoTransaction a = dbd.getNewTransaction();
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(a.isTransactionOpen() = " + a.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertTrue(a.isTransactionOpen());
+
+ try {
+ //Add 1000 ms to the timeout just to be sure it actually times out
+ int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000;
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n sleepTime = " + sleepTime
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ logger.error("Exception Occured"+e);
+ }
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n b = dbd.getNewTransaction() "
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ PolicyDBDaoTransaction b = dbd.getNewTransaction();
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertFalse(a.isTransactionOpen() = " + a.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertFalse(a.isTransactionOpen());
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(b.isTransactionOpen() = " + b.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertTrue(b.isTransactionOpen());
+ b.close();
+
+
+
+ //Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms
+ System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT,"1000");
+ //And let's lengthen the transaction timeout to 5000 ms
+ System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT,"5000");
+ //get a transacton
+ PolicyDBDaoTransaction t1 = dbd.getNewTransaction();
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertTrue(t1.isTransactionOpen());
+ //while it is open, get another from a different DB Dao so it will not collide on the synchronized code segment
+ //but will collide at the DB. Remember that the wait time is only 1000 ms
+ try {
+ //Now the 2nd transaction has a wait timeout in 1000 ms
+ PolicyDBDaoTransaction t2 = dbd2.getNewTransaction();
+ /*
+ * Give it plenty of time to time out the second transaction
+ * It will actually hang right here until it either gets the lock from the DB or the
+ * request for the DB lock times out. The timers are very sloppy so, I have given
+ * this plenty of leeway.
+ */
+
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Thread.sleep(3000)"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Thread.sleep(3000);
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")"
+ + "\n Assert.assertFalse(t2.isTransactionOpen() = " + t2.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ //Assert.assertTrue(t1.isTransactionOpen());
+ //Assert.assertFalse(t2.isTransactionOpen());
+
+ Assert.fail("\n\nTransaction timeout of 1000 ms exceeded without a PersistenceException\n\n");
+ } catch (PersistenceException e) {
+ //success
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n SUCCESS! Transaction Wait Timeout worked!"
+ + "\n Caught PersistenceException = " + e
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ } catch (Exception e) {
+ // failure due to some other reason
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE"
+ + "\n Caught Exception = " + e
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ logger.error("Exception Occured"+e);
+ Assert.fail();
+ }
+
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nthreadingStabilityTest() exit"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java
index 6fa480c72..efb13b5a0 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java
@@ -46,117 +46,117 @@ import org.springframework.mock.web.MockHttpServletResponse;
public class ActionPolicyDictionaryControllerTest {
- private static Logger logger = FlexLogger.getLogger(ActionPolicyDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private ActionPolicyDictionaryController controller = null;
- private MockHttpServletResponse response = null;
+ private static Logger logger = FlexLogger.getLogger(ActionPolicyDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private ActionPolicyDictionaryController controller = null;
+ private MockHttpServletResponse response = null;
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
- List<String> data = new ArrayList<>();
- List<Object> objectData = new ArrayList<>();
- data.add("Test");
-
- UserInfo userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
-
- ActionPolicyDict actionData = new ActionPolicyDict();
- actionData.setAttributeName("Test");
- assertTrue("Test".equals(actionData.getAttributeName()));
- actionData.setBody("Test");
- assertTrue("Test".equals(actionData.getBody()));
- actionData.setCreatedDate(new Date());
- assertTrue(actionData.getCreatedDate()!= null);
- actionData.setModifiedDate(new Date());
- assertTrue(actionData.getModifiedDate()!= null);
- actionData.setHeader("Test");
- assertTrue("Test".equals(actionData.getHeader()));
- actionData.setMethod("POST");
- assertTrue("POST".equals(actionData.getMethod()));
- actionData.setType("Test");
- assertTrue("Test".equals(actionData.getType()));
- actionData.setUrl("http://test.com");
- assertTrue("http://test.com".equals(actionData.getUrl()));
- actionData.setUserCreatedBy(userInfo);
- assertTrue(actionData.getUserCreatedBy()!= null);
- actionData.setUserModifiedBy(userInfo);
- assertTrue(actionData.getUserModifiedBy()!= null);
-
- objectData.add(actionData);
- when(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName")).thenReturn(data);
- when(commonClassDao.getData(ActionPolicyDict.class)).thenReturn(objectData);
- doNothing().when(commonClassDao).delete(new ActionPolicyDict());
- doNothing().when(commonClassDao).save(new ActionPolicyDict());
- controller = new ActionPolicyDictionaryController();
- controller.setCommonClassDao(commonClassDao);
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- new DictionaryUtils(commonClassDao);
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+ List<String> data = new ArrayList<>();
+ List<Object> objectData = new ArrayList<>();
+ data.add("Test");
+
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+
+ ActionPolicyDict actionData = new ActionPolicyDict();
+ actionData.setAttributeName("Test");
+ assertTrue("Test".equals(actionData.getAttributeName()));
+ actionData.setBody("Test");
+ assertTrue("Test".equals(actionData.getBody()));
+ actionData.setCreatedDate(new Date());
+ assertTrue(actionData.getCreatedDate()!= null);
+ actionData.setModifiedDate(new Date());
+ assertTrue(actionData.getModifiedDate()!= null);
+ actionData.setHeader("Test");
+ assertTrue("Test".equals(actionData.getHeader()));
+ actionData.setMethod("POST");
+ assertTrue("POST".equals(actionData.getMethod()));
+ actionData.setType("Test");
+ assertTrue("Test".equals(actionData.getType()));
+ actionData.setUrl("http://test.com");
+ assertTrue("http://test.com".equals(actionData.getUrl()));
+ actionData.setUserCreatedBy(userInfo);
+ assertTrue(actionData.getUserCreatedBy()!= null);
+ actionData.setUserModifiedBy(userInfo);
+ assertTrue(actionData.getUserModifiedBy()!= null);
+
+ objectData.add(actionData);
+ when(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName")).thenReturn(data);
+ when(commonClassDao.getData(ActionPolicyDict.class)).thenReturn(objectData);
+ doNothing().when(commonClassDao).delete(new ActionPolicyDict());
+ doNothing().when(commonClassDao).save(new ActionPolicyDict());
+ controller = new ActionPolicyDictionaryController();
+ controller.setCommonClassDao(commonClassDao);
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
- logger.info("setUp: exit");
- }
-
- @Test
- public void testGetActionEntitybyName(){
- controller.getActionEntitybyName(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetActionPolicyDictionaryEntityData(){
- controller.getActionPolicyDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testSaveActionPolicyDictionary(){
- jsonString = "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveActionPolicyDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateActionPolicyDictionary(){
- jsonString = "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveActionPolicyDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveActionPolicyDictionary(){
- jsonString = "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\",\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"}}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeActionPolicyDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
+ logger.info("setUp: exit");
+ }
+
+ @Test
+ public void testGetActionEntitybyName(){
+ controller.getActionEntitybyName(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetActionPolicyDictionaryEntityData(){
+ controller.getActionPolicyDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testSaveActionPolicyDictionary(){
+ jsonString = "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveActionPolicyDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateActionPolicyDictionary(){
+ jsonString = "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveActionPolicyDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveActionPolicyDictionary(){
+ jsonString = "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\",\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"}}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeActionPolicyDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java
index 0a60e1831..d34e505ba 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java
@@ -46,217 +46,217 @@ import org.springframework.mock.web.MockHttpServletResponse;
public class BRMSDictionaryControllerTest {
- private static Logger logger = FlexLogger.getLogger(BRMSDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private BRMSDictionaryController controller = null;
- private MockHttpServletResponse response = null;
+ private static Logger logger = FlexLogger.getLogger(BRMSDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private BRMSDictionaryController controller = null;
+ private MockHttpServletResponse response = null;
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
- UserInfo userInfo = new UserInfo();
- userInfo.setUserLoginId("testUserId");
- userInfo.setUserName("John");
- when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo);
- List<String> brms = new ArrayList<String>();
- brms.add("BRMS-Model");
- when(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "name")).thenReturn(brms);
- doNothing().when(commonClassDao).delete(new BRMSParamTemplate());
- doNothing().when(commonClassDao).save(new BRMSParamTemplate());
- controller = new BRMSDictionaryController();
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- new DictionaryUtils(commonClassDao);
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("testUserId");
+ userInfo.setUserName("John");
+ when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo);
+ List<String> brms = new ArrayList<String>();
+ brms.add("BRMS-Model");
+ when(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "name")).thenReturn(brms);
+ doNothing().when(commonClassDao).delete(new BRMSParamTemplate());
+ doNothing().when(commonClassDao).save(new BRMSParamTemplate());
+ controller = new BRMSDictionaryController();
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
- logger.info("setUp: exit");
- }
+ logger.info("setUp: exit");
+ }
- @Test
- public void testGetBRMSParamDictionaryByNameEntityData(){
- logger.info("testGetBRMSParamDictionaryByNameEntityData: Entering");
- BRMSDictionaryController.setCommonClassDao(commonClassDao);
- controller.getBRMSParamDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
- logger.info("testGetBRMSParamDictionaryByNameEntityData: exit");
- }
+ @Test
+ public void testGetBRMSParamDictionaryByNameEntityData(){
+ logger.info("testGetBRMSParamDictionaryByNameEntityData: Entering");
+ BRMSDictionaryController.setCommonClassDao(commonClassDao);
+ controller.getBRMSParamDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testGetBRMSParamDictionaryByNameEntityData: exit");
+ }
- @Test
- public void testGetBRMSParamDictionaryEntityData() {
- logger.info("testGetBRMSParamDictionaryEntityData: Entering");
- controller.getBRMSParamDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
- logger.info("testGetBRMSParamDictionaryEntityData: exit");
- }
+ @Test
+ public void testGetBRMSParamDictionaryEntityData() {
+ logger.info("testGetBRMSParamDictionaryEntityData: Entering");
+ controller.getBRMSParamDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testGetBRMSParamDictionaryEntityData: exit");
+ }
- @Test
- public void testSaveBRMSParamDictionary() {
- logger.info("testSaveBRMSParamDictionary: Entering");
- jsonString = "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveBRMSParamDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryData"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- logger.info("testSaveBRMSParamDictionary: exit");
- }
+ @Test
+ public void testSaveBRMSParamDictionary() {
+ logger.info("testSaveBRMSParamDictionary: Entering");
+ jsonString = "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveBRMSParamDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryData"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ logger.info("testSaveBRMSParamDictionary: exit");
+ }
- @Test
- public void testRemoveBRMSParamDictionary() {
- logger.info("testRemoveBRMSParamDictionary: Entering");
- jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeBRMSParamDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
- } catch (Exception e) {
- fail("Exception: " + e);
- }
- logger.info("testRemoveBRMSParamDictionary: exit");
- }
+ @Test
+ public void testRemoveBRMSParamDictionary() {
+ logger.info("testRemoveBRMSParamDictionary: Entering");
+ jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeBRMSParamDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testRemoveBRMSParamDictionary: exit");
+ }
- @Test
- public void testGetBRMSDependencyDictionaryByNameEntityData(){
- logger.info("testGetBRMSDependencyDictionaryByNameEntityData: Entering");
- BRMSDictionaryController.setCommonClassDao(commonClassDao);
- controller.getBRMSDependencyDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
- logger.info("testGetBRMSDependencyDictionaryByNameEntityData: exit");
- }
+ @Test
+ public void testGetBRMSDependencyDictionaryByNameEntityData(){
+ logger.info("testGetBRMSDependencyDictionaryByNameEntityData: Entering");
+ BRMSDictionaryController.setCommonClassDao(commonClassDao);
+ controller.getBRMSDependencyDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testGetBRMSDependencyDictionaryByNameEntityData: exit");
+ }
- @Test
- public void testGetBRMSDependencyDictionaryEntityData(){
- logger.info("testGetBRMSDependencyDictionaryEntityData: Entering");
- BRMSDictionaryController.setCommonClassDao(commonClassDao);
- controller.getBRMSDependencyDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
+ @Test
+ public void testGetBRMSDependencyDictionaryEntityData(){
+ logger.info("testGetBRMSDependencyDictionaryEntityData: Entering");
+ BRMSDictionaryController.setCommonClassDao(commonClassDao);
+ controller.getBRMSDependencyDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
- logger.info("testGetBRMSDependencyDictionaryEntityData: exit");
- }
+ logger.info("testGetBRMSDependencyDictionaryEntityData: exit");
+ }
- @Test
- public void testSaveBRMSDependencyDictionary() {
- logger.info("testSaveBRMSDependencyDictionary: Entering");
- jsonString = "{\"brmsDependencyDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveBRMSDependencyDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryData"));
- } catch (Exception e) {
- fail("Exception: " + e);
- }
- logger.info("testSaveBRMSDependencyDictionary: exit");
- }
+ @Test
+ public void testSaveBRMSDependencyDictionary() {
+ logger.info("testSaveBRMSDependencyDictionary: Entering");
+ jsonString = "{\"brmsDependencyDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveBRMSDependencyDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryData"));
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testSaveBRMSDependencyDictionary: exit");
+ }
- @Test
- public void testRemoveBRMSDependencyDictionary() {
- logger.info("testRemoveBRMSDependencyDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
- jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeBRMSDependencyDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
- } catch (Exception e) {
- fail("Exception: " + e);
- }
- logger.info("testRemoveBRMSDependencyDictionary: exit");
- }
+ @Test
+ public void testRemoveBRMSDependencyDictionary() {
+ logger.info("testRemoveBRMSDependencyDictionary: Entering");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+ jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeBRMSDependencyDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testRemoveBRMSDependencyDictionary: exit");
+ }
- @Test
- public void testGetBRMSControllerDictionaryByNameEntityData(){
- logger.info("testGetBRMSControllerDictionaryByNameEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
- BRMSDictionaryController.setCommonClassDao(commonClassDao);
- controller.getBRMSControllerDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
- logger.info("testGetBRMSControllerDictionaryByNameEntityData: exit");
- }
+ @Test
+ public void testGetBRMSControllerDictionaryByNameEntityData(){
+ logger.info("testGetBRMSControllerDictionaryByNameEntityData: Entering");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ BRMSDictionaryController.setCommonClassDao(commonClassDao);
+ controller.getBRMSControllerDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testGetBRMSControllerDictionaryByNameEntityData: exit");
+ }
- @Test
- public void testGetBRMSControllerDictionaryEntityData(){
- logger.info("testGetBRMSControllerDictionaryEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
- BRMSDictionaryController.setCommonClassDao(commonClassDao);
- controller.getBRMSControllerDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
- logger.info("testGetBRMSControllerDictionaryEntityData: exit");
- }
+ @Test
+ public void testGetBRMSControllerDictionaryEntityData(){
+ logger.info("testGetBRMSControllerDictionaryEntityData: Entering");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ BRMSDictionaryController.setCommonClassDao(commonClassDao);
+ controller.getBRMSControllerDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testGetBRMSControllerDictionaryEntityData: exit");
+ }
- @Test
- public void testSaveBRMSControllerDictionary() {
- logger.info("testSaveBRMSControllerDictionary: Entering");
+ @Test
+ public void testSaveBRMSControllerDictionary() {
+ logger.info("testSaveBRMSControllerDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
- jsonString = "{\"brmsControllerDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveBRMSControllerDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryData"));
- } catch (Exception e) {
- fail("Exception: " + e);
- }
- logger.info("testSaveBRMSControllerDictionary: exit");
- }
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+ jsonString = "{\"brmsControllerDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveBRMSControllerDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryData"));
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testSaveBRMSControllerDictionary: exit");
+ }
- @Test
- public void testRemoveBRMSControllerDictionary() {
- logger.info("testRemoveBRMSControllerDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
- jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeBRMSControllerDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
+ @Test
+ public void testRemoveBRMSControllerDictionary() {
+ logger.info("testRemoveBRMSControllerDictionary: Entering");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+ jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeBRMSControllerDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
- } catch (Exception e) {
- fail("Exception: " + e);
- }
- logger.info("testRemoveBRMSControllerDictionary: exit");
- }
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+ logger.info("testRemoveBRMSControllerDictionary: exit");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java
index ea1ea3b88..f530b4c62 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java
@@ -49,399 +49,399 @@ import org.onap.policy.rest.jpa.VarbindDictionary;
import org.springframework.mock.web.MockHttpServletResponse;
public class ClosedLoopDictionaryControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(ClosedLoopDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private ClosedLoopDictionaryController controller = null;
- private MockHttpServletResponse response = null;
- private UserInfo userInfo;
- private List<String> data;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
-
- data = new ArrayList<>();
- data.add("Test");
-
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
-
- doNothing().when(commonClassDao).delete(new VSCLAction());
- doNothing().when(commonClassDao).save(new VSCLAction());
-
- controller = new ClosedLoopDictionaryController();
- controller.setCommonClassDao(commonClassDao);
-
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- new DictionaryUtils(commonClassDao);
+
+ private static Logger logger = FlexLogger.getLogger(ClosedLoopDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private ClosedLoopDictionaryController controller = null;
+ private MockHttpServletResponse response = null;
+ private UserInfo userInfo;
+ private List<String> data;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+
+ data = new ArrayList<>();
+ data.add("Test");
+
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+
+ doNothing().when(commonClassDao).delete(new VSCLAction());
+ doNothing().when(commonClassDao).save(new VSCLAction());
+
+ controller = new ClosedLoopDictionaryController();
+ controller.setCommonClassDao(commonClassDao);
+
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
- logger.info("setUp: exit");
- }
-
- @Test
- public void testGetVSCLActionDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction")).thenReturn(data);
- controller.getVSCLActionDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetVSCLActionDictionaryEntityData(){
- when(commonClassDao.getData(VSCLAction.class)).thenReturn(new ArrayList<>());
- controller.getVSCLActionDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetVNFTypeDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(VNFType.class, "vnftype")).thenReturn(data);
- controller.getVNFTypeDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetVNFTypeDictionaryEntityData(){
- when(commonClassDao.getData(VNFType.class)).thenReturn(new ArrayList<>());
- controller.getVNFTypeDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPEPOptionsDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(PEPOptions.class, "pepName")).thenReturn(data);
- controller.getPEPOptionsDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPEPOptionsDictionaryEntityData(){
- when(commonClassDao.getData(PEPOptions.class)).thenReturn(new ArrayList<>());
- controller.getPEPOptionsDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetVarbindDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName")).thenReturn(data);
- controller.getVarbindDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetVarbindDictionaryEntityData(){
- when(commonClassDao.getData(VarbindDictionary.class)).thenReturn(new ArrayList<>());
- controller.getVarbindDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetClosedLoopServiceDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName")).thenReturn(data);
- controller.getClosedLoopServiceDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetClosedLoopServiceDictionaryEntityData(){
- when(commonClassDao.getData(ClosedLoopD2Services.class)).thenReturn(new ArrayList<>());
- controller.getClosedLoopServiceDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetClosedLoopSiteDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName")).thenReturn(data);
- controller.getClosedLoopSiteDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetClosedLoopSiteDictionaryEntityData(){
- when(commonClassDao.getData(ClosedLoopSite.class)).thenReturn(new ArrayList<>());
- controller.getClosedLoopSiteDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testSaveVSCLAction(){
- jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveVSCLAction(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateVSCLAction(){
- jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveVSCLAction(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveVSCLAction(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeVSCLAction(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSaveVnfType(){
- jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"description\":\"test\",\"vnftype\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveVnfType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateVnfType(){
- jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveVnfType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveVnfType(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeVnfType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSavePEPOptions(){
- jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePEPOptions(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdatePEPOptions(){
- jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePEPOptions(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemovePEPOptions(){
- jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removePEPOptions(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSaveServiceType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveServiceType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateServiceType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveServiceType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveServiceType(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeServiceType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSaveSiteType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveSiteType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateSiteType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveSiteType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveSiteType(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeSiteType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSaveVarbind(){
- jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveVarbind(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateVarbind(){
- jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveVarbind(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveVarbind(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeVarbind(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
+ logger.info("setUp: exit");
+ }
+
+ @Test
+ public void testGetVSCLActionDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction")).thenReturn(data);
+ controller.getVSCLActionDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetVSCLActionDictionaryEntityData(){
+ when(commonClassDao.getData(VSCLAction.class)).thenReturn(new ArrayList<>());
+ controller.getVSCLActionDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetVNFTypeDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(VNFType.class, "vnftype")).thenReturn(data);
+ controller.getVNFTypeDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetVNFTypeDictionaryEntityData(){
+ when(commonClassDao.getData(VNFType.class)).thenReturn(new ArrayList<>());
+ controller.getVNFTypeDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPEPOptionsDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(PEPOptions.class, "pepName")).thenReturn(data);
+ controller.getPEPOptionsDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPEPOptionsDictionaryEntityData(){
+ when(commonClassDao.getData(PEPOptions.class)).thenReturn(new ArrayList<>());
+ controller.getPEPOptionsDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetVarbindDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName")).thenReturn(data);
+ controller.getVarbindDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetVarbindDictionaryEntityData(){
+ when(commonClassDao.getData(VarbindDictionary.class)).thenReturn(new ArrayList<>());
+ controller.getVarbindDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetClosedLoopServiceDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName")).thenReturn(data);
+ controller.getClosedLoopServiceDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetClosedLoopServiceDictionaryEntityData(){
+ when(commonClassDao.getData(ClosedLoopD2Services.class)).thenReturn(new ArrayList<>());
+ controller.getClosedLoopServiceDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetClosedLoopSiteDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName")).thenReturn(data);
+ controller.getClosedLoopSiteDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetClosedLoopSiteDictionaryEntityData(){
+ when(commonClassDao.getData(ClosedLoopSite.class)).thenReturn(new ArrayList<>());
+ controller.getClosedLoopSiteDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testSaveVSCLAction(){
+ jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveVSCLAction(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateVSCLAction(){
+ jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveVSCLAction(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveVSCLAction(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeVSCLAction(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSaveVnfType(){
+ jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"description\":\"test\",\"vnftype\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveVnfType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateVnfType(){
+ jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveVnfType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveVnfType(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeVnfType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSavePEPOptions(){
+ jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePEPOptions(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdatePEPOptions(){
+ jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePEPOptions(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemovePEPOptions(){
+ jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removePEPOptions(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSaveServiceType(){
+ jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveServiceType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateServiceType(){
+ jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveServiceType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveServiceType(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeServiceType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSaveSiteType(){
+ jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveSiteType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateSiteType(){
+ jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveSiteType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveSiteType(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeSiteType(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSaveVarbind(){
+ jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveVarbind(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateVarbind(){
+ jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveVarbind(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveVarbind(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeVarbind(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java
index 2e8c63cf8..7910aed11 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java
@@ -40,26 +40,26 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.springframework.mock.web.MockHttpServletResponse;
public class DecisionPolicyDictionaryControllerTest {
- private static Logger logger = FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private DecisionPolicyDictionaryController controller = null;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
+ private static Logger logger = FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private DecisionPolicyDictionaryController controller = null;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
commonClassDao = Mockito.mock(CommonClassDao.class);
- HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- jsonString = "{\"attributeDictionaryDatas\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ jsonString = "{\"attributeDictionaryDatas\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
BufferedReader br = new BufferedReader(new StringReader(jsonString));
@@ -71,206 +71,206 @@ public class DecisionPolicyDictionaryControllerTest {
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
logger.info("setUp: exit");
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testGetSettingsDictionaryByNameEntityData() {
- logger.info("testGetSettingsDictionaryByNameEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getSettingsDictionaryByNameEntityData(request, response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testGetSettingsDictionaryByNameEntityData: exit");
-
- }
-
- @Test
- public void testGetSettingsDictionaryEntityData() {
- logger.info("testGetSettingsDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getSettingsDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testGetSettingsDictionaryEntityData: exit");
-
- }
-
- @Test
- public void testSaveSettingsDictionary() {
- logger.info("testSaveSettingsDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ }
+
+ @Test
+ public void testGetSettingsDictionaryByNameEntityData() {
+ logger.info("testGetSettingsDictionaryByNameEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getSettingsDictionaryByNameEntityData(request, response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetSettingsDictionaryByNameEntityData: exit");
+
+ }
+
+ @Test
+ public void testGetSettingsDictionaryEntityData() {
+ logger.info("testGetSettingsDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getSettingsDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetSettingsDictionaryEntityData: exit");
+
+ }
+
+ @Test
+ public void testSaveSettingsDictionary() {
+ logger.info("testSaveSettingsDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
- try {
- // mock the getReader() call
- jsonString = "{\"settingsDictionaryData\":{\"xacmlId\":\"testMMRestAPI1\",\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"test\",\"priority\":\"High\"}, \"userid\":\"test\"}";
-
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveSettingsDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
-
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testSaveSettingsDictionary: exit");
-
- }
-
- @Test
- public void testRemoveSettingsDictionary() {
- logger.info("testRemoveSettingsDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeSettingsDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
-
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveSettingsDictionary: exit");
-
- }
-
- @Test
- public void testGetRainyDayDictionaryByNameEntityData() {
- logger.info("testGetRainyDayDictionaryByNameEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getRainyDayDictionaryByNameEntityData(request, response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testGetRainyDayDictionaryByNameEntityData: exit");
-
- }
-
- @Test
- public void testGetRainyDayDictionaryEntityData() {
- logger.info("testGetRainyDayDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getRainyDayDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testGetRainyDayDictionaryEntityData: exit");
-
- }
-
- @Test
- public void testSaveRainyDayDictionary() {
- logger.info("testSaveRainyDayDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
+ try {
+ // mock the getReader() call
+ jsonString = "{\"settingsDictionaryData\":{\"xacmlId\":\"testMMRestAPI1\",\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"test\",\"priority\":\"High\"}, \"userid\":\"test\"}";
+
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveSettingsDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
+
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveSettingsDictionary: exit");
+
+ }
+
+ @Test
+ public void testRemoveSettingsDictionary() {
+ logger.info("testRemoveSettingsDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeSettingsDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("settingsDictionaryDatas"));
+
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveSettingsDictionary: exit");
+
+ }
+
+ @Test
+ public void testGetRainyDayDictionaryByNameEntityData() {
+ logger.info("testGetRainyDayDictionaryByNameEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getRainyDayDictionaryByNameEntityData(request, response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetRainyDayDictionaryByNameEntityData: exit");
+
+ }
+
+ @Test
+ public void testGetRainyDayDictionaryEntityData() {
+ logger.info("testGetRainyDayDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getRainyDayDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetRainyDayDictionaryEntityData: exit");
+
+ }
+
+ @Test
+ public void testSaveRainyDayDictionary() {
+ logger.info("testSaveRainyDayDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
- try {
- // mock the getReader() call
- jsonString = "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\",\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}";
-
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveRainyDayDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
-
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testSaveRainyDayDictionary: exit");
-
- }
-
- @Test
- public void testRemoveRainyDayDictionary() {
- logger.info("testRemoveRainyDayDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeRainyDayDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
-
- } catch (Exception e) {
- logger.error("Exception Occured"+e);
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveRainyDayDictionary: exit");
-
- }
+ try {
+ // mock the getReader() call
+ jsonString = "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\",\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}";
+
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveRainyDayDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
+
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveRainyDayDictionary: exit");
+
+ }
+
+ @Test
+ public void testRemoveRainyDayDictionary() {
+ logger.info("testRemoveRainyDayDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeRainyDayDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rainyDayDictionaryDatas"));
+
+ } catch (Exception e) {
+ logger.error("Exception Occured"+e);
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveRainyDayDictionary: exit");
+
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java
index 5310ddc93..0950b1cfd 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java
@@ -45,124 +45,124 @@ import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.mock.web.MockHttpServletResponse;
public class DescriptiveDictionaryControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(DescriptiveDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private DescriptiveDictionaryController controller = null;
- private MockHttpServletResponse response = null;
- private UserInfo userInfo;
- private List<String> data;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
-
- data = new ArrayList<>();
- data.add("Test");
-
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
-
- doNothing().when(commonClassDao).delete(new DescriptiveScope());
- doNothing().when(commonClassDao).save(new DescriptiveScope());
-
- controller = new DescriptiveDictionaryController();
- controller.setCommonClassDao(commonClassDao);
-
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- new DictionaryUtils(commonClassDao);
+
+ private static Logger logger = FlexLogger.getLogger(DescriptiveDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private DescriptiveDictionaryController controller = null;
+ private MockHttpServletResponse response = null;
+ private UserInfo userInfo;
+ private List<String> data;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+
+ data = new ArrayList<>();
+ data.add("Test");
+
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+
+ doNothing().when(commonClassDao).delete(new DescriptiveScope());
+ doNothing().when(commonClassDao).save(new DescriptiveScope());
+
+ controller = new DescriptiveDictionaryController();
+ controller.setCommonClassDao(commonClassDao);
+
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
- logger.info("setUp: exit");
- }
-
- public List<Object> testDescriptiveScope(){
- List<Object> objectData = new ArrayList<>();
-
- DescriptiveScope data = new DescriptiveScope();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setScopeName("Test");
- assertTrue("Test".equals(data.getScopeName()));
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- data.setSearch("Test");
- assertTrue("Test".equals(data.getSearch()));
- data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
- data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
- data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
- data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
- objectData.add(data);
-
- return objectData;
- }
-
- @Test
- public void testGetDescriptiveDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")).thenReturn(data);
- controller.getDescriptiveDictionaryByNameEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetDescriptiveDictionaryEntityData(){
- when(commonClassDao.getData(DescriptiveScope.class)).thenReturn(testDescriptiveScope());
- controller.getDescriptiveDictionaryEntityData(response);
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testSaveDescriptiveDictionary(){
- jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveDescriptiveDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateDescriptiveDictionary(){
- jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveDescriptiveDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveDescriptiveDictionary(){
- jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeDescriptiveDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
+ logger.info("setUp: exit");
+ }
+
+ public List<Object> testDescriptiveScope(){
+ List<Object> objectData = new ArrayList<>();
+
+ DescriptiveScope data = new DescriptiveScope();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setScopeName("Test");
+ assertTrue("Test".equals(data.getScopeName()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ data.setSearch("Test");
+ assertTrue("Test".equals(data.getSearch()));
+ data.setCreatedDate(new Date());
+ assertTrue(data.getCreatedDate()!= null);
+ data.setModifiedDate(new Date());
+ assertTrue(data.getModifiedDate()!= null);
+ data.setUserCreatedBy(userInfo);
+ assertTrue(data.getUserCreatedBy()!= null);
+ data.setUserModifiedBy(userInfo);
+ assertTrue(data.getUserModifiedBy()!= null);
+ objectData.add(data);
+
+ return objectData;
+ }
+
+ @Test
+ public void testGetDescriptiveDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")).thenReturn(data);
+ controller.getDescriptiveDictionaryByNameEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetDescriptiveDictionaryEntityData(){
+ when(commonClassDao.getData(DescriptiveScope.class)).thenReturn(testDescriptiveScope());
+ controller.getDescriptiveDictionaryEntityData(response);
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testSaveDescriptiveDictionary(){
+ jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveDescriptiveDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateDescriptiveDictionary(){
+ jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveDescriptiveDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveDescriptiveDictionary(){
+ jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeDescriptiveDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java
index e76ebdf12..89be75f52 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java
@@ -57,16 +57,16 @@ import org.springframework.mock.web.MockHttpServletResponse;
* tasks.
*/
public class DictionaryControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(DictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private DictionaryController controller = null;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
+
+ private static Logger logger = FlexLogger.getLogger(DictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private DictionaryController controller = null;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
commonClassDao = Mockito.mock(CommonClassDao.class);
MicroServiceModels testData = new MicroServiceModels();
@@ -86,173 +86,173 @@ public class DictionaryControllerTest {
when(commonClassDao.getData(Attribute.class)).thenReturn(listId);
- request = mock(HttpServletRequest.class);
+ request = mock(HttpServletRequest.class);
controller = new DictionaryController(commonClassDao);
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
logger.info("setUp: exit");
- }
-
- @Test
- public void testGetAttributeDictionaryEntityDatabyAttributeName() {
- logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getAttributeDictionaryEntityDatabyAttributeName(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: exit");
- }
-
- @Test
- public void testGetAttributeDictionaryEntityData() {
- logger.info("testGetAttributeDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getAttributeDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetAttributeDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveAttributeDictionary() {
- logger.info("testSaveAttributeDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
+ }
+
+ @Test
+ public void testGetAttributeDictionaryEntityDatabyAttributeName() {
+ logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getAttributeDictionaryEntityDatabyAttributeName(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: exit");
+ }
+
+ @Test
+ public void testGetAttributeDictionaryEntityData() {
+ logger.info("testGetAttributeDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getAttributeDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetAttributeDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveAttributeDictionary() {
+ logger.info("testSaveAttributeDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
- try {
- jsonString = "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":\"Qwerty\"},\"userid\":\"demo\"}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveAttributeDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveAttributeDictionary: exit");
- }
-
- @Test
- public void testRemoveAttributeDictionary() {
- logger.info("testRemoveAttributeDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"xacmlId\":\"Test\"}}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeAttributeDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveAttributeDictionary: exit");
- }
-
- @Test
- public void testGetOnapNameDictionaryByNameEntityData() {
- logger.info("testGetOnapNameDictionaryByNameEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getOnapNameDictionaryByNameEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetOnapNameDictionaryByNameEntityData: exit");
- }
-
- @Test
- public void testGetOnapNameDictionaryEntityData() {
- logger.info("testGetOnapNameDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getOnapNameDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetOnapNameDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveOnapDictionary() {
-
- logger.info("testSaveOnapDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
+ try {
+ jsonString = "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":\"Qwerty\"},\"userid\":\"demo\"}";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveAttributeDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveAttributeDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveAttributeDictionary() {
+ logger.info("testRemoveAttributeDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"xacmlId\":\"Test\"}}";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeAttributeDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveAttributeDictionary: exit");
+ }
+
+ @Test
+ public void testGetOnapNameDictionaryByNameEntityData() {
+ logger.info("testGetOnapNameDictionaryByNameEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getOnapNameDictionaryByNameEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetOnapNameDictionaryByNameEntityData: exit");
+ }
+
+ @Test
+ public void testGetOnapNameDictionaryEntityData() {
+ logger.info("testGetOnapNameDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getOnapNameDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetOnapNameDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveOnapDictionary() {
+
+ logger.info("testSaveOnapDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
- try {
- jsonString = "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveOnapDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveOnapDictionary: exit");
- }
-
- @Test
- public void testRemoveOnapDictionary() {
- logger.info("testRemoveOnapDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"onapName\":\"Test\"}}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeOnapDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveOnapDictionary: exit");
- }
+ try {
+ jsonString = "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveOnapDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveOnapDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveOnapDictionary() {
+ logger.info("testRemoveOnapDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"onapName\":\"Test\"}}";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeOnapDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveOnapDictionary: exit");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java
index 6a28c271a..7ab1b170e 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java
@@ -43,98 +43,98 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.springframework.mock.web.MockHttpServletResponse;
public class DictionaryImportControllerTest extends Mockito{
-
- private static Logger logger = FlexLogger.getLogger(DictionaryImportController.class);
-
- private static CommonClassDao commonClassDao;
- private HttpServletRequest request = null;
- private HttpServletResponse response = null;
- private DictionaryImportController controller = null;
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
- doNothing().when(commonClassDao).save(new Object());
- controller = new DictionaryImportController();
- new DictionaryImportController(commonClassDao);
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- }
-
- @Test
- public void testIsValidDictionaryName(){
- DictionaryImportController cotroller = new DictionaryImportController();
- //test invalid name
- assertTrue(!cotroller.isValidDictionaryName("wrong-name"));
- //test valid name
- assertTrue(cotroller.isValidDictionaryName("ActionList"));
- }
+ private static Logger logger = FlexLogger.getLogger(DictionaryImportController.class);
- @Test
- public void testImportDictionaryData() throws ServletException, IOException{
- List<String> fileNames = new ArrayList<>();
- fileNames.add("Attribute.csv");
- fileNames.add("ActionPolicyDictionary.csv");
- fileNames.add("OnapName.csv");
- fileNames.add("MSPolicyDictionary.csv");
- fileNames.add("OptimizationPolicyDictionary.csv");
- fileNames.add("ClosedLoopService.csv");
- fileNames.add("ClosedLoopSite.csv");
- fileNames.add("VarbindDictionary.csv");
- fileNames.add("BRMSParamDictionary.csv");
- fileNames.add("BRMSControllerDictionary.csv");
- fileNames.add("BRMSDependencyDictionary.csv");
- fileNames.add("PrefixList.csv");
- fileNames.add("SecurityZone.csv");
- fileNames.add("ServiceList.csv");
- fileNames.add("ServiceGroup.csv");
- fileNames.add("AddressGroup.csv");
- fileNames.add("ProtocolList.csv");
- fileNames.add("TermList.csv");
- fileNames.add("SearchCriteria.csv");
- fileNames.add("VNFType.csv");
- fileNames.add("VSCLAction.csv");
- fileNames.add("PEPOptions.csv");
- fileNames.add("Settings.csv");
- fileNames.add("Zone.csv");
- fileNames.add("ActionList.csv");
- for(int i =0; i < fileNames.size(); i++){
- File file = new File("src/test/resources/dictionaryImport/"+fileNames.get(i));
- try(FileInputStream targetStream = new FileInputStream(file)){
- PushPolicyControllerTest pushController = new PushPolicyControllerTest();
- when(request.getInputStream()).thenReturn(pushController.getInputStream(getBytes(targetStream)));
- when(request.getParameter("userId")).thenReturn("demo");
- when(request.getParameter("dictionaryName")).thenReturn(fileNames.get(i));
- controller.importDictionaryData(request, response);
- assertTrue(HttpServletResponse.SC_OK == response.getStatus());
- } catch (IOException e) {
- fail();
- }
- }
- when(request.getParameter("dictionaryName")).thenReturn("WrongName");
- controller.importDictionaryData(request, response);
- assertTrue(HttpServletResponse.SC_BAD_REQUEST == response.getStatus());
-
- when(request.getParameter("dictionaryName")).thenReturn("");
- controller.importDictionaryData(request, response);
- assertTrue(HttpServletResponse.SC_BAD_REQUEST == response.getStatus());
-
- when(request.getInputStream()).thenReturn(null);
- when(request.getParameter("dictionaryName")).thenReturn("Attribute.csv");
- controller.importDictionaryData(request, response);
- assertTrue(HttpServletResponse.SC_INTERNAL_SERVER_ERROR == response.getStatus());
- }
-
- public static byte[] getBytes(InputStream is) throws IOException {
- int len;
- int size = 1024;
- byte[] buf;
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- buf = new byte[size];
- while ((len = is.read(buf, 0, size)) != -1)
- bos.write(buf, 0, len);
- buf = bos.toByteArray();
- return buf;
- }
+ private static CommonClassDao commonClassDao;
+ private HttpServletRequest request = null;
+ private HttpServletResponse response = null;
+ private DictionaryImportController controller = null;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+ doNothing().when(commonClassDao).save(new Object());
+ controller = new DictionaryImportController();
+ new DictionaryImportController(commonClassDao);
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ }
+
+ @Test
+ public void testIsValidDictionaryName(){
+ DictionaryImportController cotroller = new DictionaryImportController();
+ //test invalid name
+ assertTrue(!cotroller.isValidDictionaryName("wrong-name"));
+ //test valid name
+ assertTrue(cotroller.isValidDictionaryName("ActionList"));
+ }
+
+ @Test
+ public void testImportDictionaryData() throws ServletException, IOException{
+ List<String> fileNames = new ArrayList<>();
+ fileNames.add("Attribute.csv");
+ fileNames.add("ActionPolicyDictionary.csv");
+ fileNames.add("OnapName.csv");
+ fileNames.add("MSPolicyDictionary.csv");
+ fileNames.add("OptimizationPolicyDictionary.csv");
+ fileNames.add("ClosedLoopService.csv");
+ fileNames.add("ClosedLoopSite.csv");
+ fileNames.add("VarbindDictionary.csv");
+ fileNames.add("BRMSParamDictionary.csv");
+ fileNames.add("BRMSControllerDictionary.csv");
+ fileNames.add("BRMSDependencyDictionary.csv");
+ fileNames.add("PrefixList.csv");
+ fileNames.add("SecurityZone.csv");
+ fileNames.add("ServiceList.csv");
+ fileNames.add("ServiceGroup.csv");
+ fileNames.add("AddressGroup.csv");
+ fileNames.add("ProtocolList.csv");
+ fileNames.add("TermList.csv");
+ fileNames.add("SearchCriteria.csv");
+ fileNames.add("VNFType.csv");
+ fileNames.add("VSCLAction.csv");
+ fileNames.add("PEPOptions.csv");
+ fileNames.add("Settings.csv");
+ fileNames.add("Zone.csv");
+ fileNames.add("ActionList.csv");
+ for(int i =0; i < fileNames.size(); i++){
+ File file = new File("src/test/resources/dictionaryImport/"+fileNames.get(i));
+ try(FileInputStream targetStream = new FileInputStream(file)){
+ PushPolicyControllerTest pushController = new PushPolicyControllerTest();
+ when(request.getInputStream()).thenReturn(pushController.getInputStream(getBytes(targetStream)));
+ when(request.getParameter("userId")).thenReturn("demo");
+ when(request.getParameter("dictionaryName")).thenReturn(fileNames.get(i));
+ controller.importDictionaryData(request, response);
+ assertTrue(HttpServletResponse.SC_OK == response.getStatus());
+ } catch (IOException e) {
+ fail();
+ }
+ }
+ when(request.getParameter("dictionaryName")).thenReturn("WrongName");
+ controller.importDictionaryData(request, response);
+ assertTrue(HttpServletResponse.SC_BAD_REQUEST == response.getStatus());
+
+ when(request.getParameter("dictionaryName")).thenReturn("");
+ controller.importDictionaryData(request, response);
+ assertTrue(HttpServletResponse.SC_BAD_REQUEST == response.getStatus());
+
+ when(request.getInputStream()).thenReturn(null);
+ when(request.getParameter("dictionaryName")).thenReturn("Attribute.csv");
+ controller.importDictionaryData(request, response);
+ assertTrue(HttpServletResponse.SC_INTERNAL_SERVER_ERROR == response.getStatus());
+ }
+
+ public static byte[] getBytes(InputStream is) throws IOException {
+ int len;
+ int size = 1024;
+ byte[] buf;
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ buf = new byte[size];
+ while ((len = is.read(buf, 0, size)) != -1)
+ bos.write(buf, 0, len);
+ buf = bos.toByteArray();
+ return buf;
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java
index e305b1221..45d8466b6 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java
@@ -62,617 +62,617 @@ import org.springframework.mock.web.MockHttpServletResponse;
public class FirewallDictionaryControllerTest {
- private static Logger logger = FlexLogger.getLogger(FirewallDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private FirewallDictionaryController controller = null;
- private MockHttpServletResponse response = null;
- private UserInfo userInfo;
- private List<String> data;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
-
- data = new ArrayList<>();
- data.add("Test");
-
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
-
- doNothing().when(commonClassDao).delete(any(Term.class));
- doNothing().when(commonClassDao).save(any(Term.class));
-
- controller = new FirewallDictionaryController();
- FirewallDictionaryController.setCommonClassDao(commonClassDao);
-
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- new DictionaryUtils(commonClassDao);
- DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
- mock(DictionaryUtils.class);
- logger.info("setUp: exit");
- }
-
- @Test
- public void testGetPrefixListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
- () -> controller.getPrefixListDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetPrefixListDictionaryEntityData() {
- test_WithGetData(PrefixList.class, "prefixListDictionaryDatas",
- () -> controller.getPrefixListDictionaryEntityData(response));
- }
-
- @Test
- public void testGetPortListDictionaryEntityData() {
- test_WithGetData(PortList.class, "portListDictionaryDatas",
- () -> controller.getPortListDictionaryEntityData(response));
- }
-
- @Test
- public void testGetProtocolListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
- () -> controller.getProtocolListDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetProtocolListDictionaryEntityData() {
- test_WithGetData(ProtocolList.class, "protocolListDictionaryDatas",
- () -> controller.getProtocolListDictionaryEntityData(response));
- }
-
- @Test
- public void testGetAddressGroupDictionaryEntityDataByName() {
- test_WithGetDataByColumn(AddressGroup.class, "addressGroupDictionaryDatas", "name",
- () -> controller.getAddressGroupDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetAddressGroupDictionaryEntityData() {
- test_WithGetData(AddressGroup.class, "addressGroupDictionaryDatas",
- () -> controller.getAddressGroupDictionaryEntityData(response));
- }
-
- @Test
- public void testGetActionListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(ActionList.class, "actionListDictionaryDatas", "actionName",
- () -> controller.getActionListDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetActionListDictionaryEntityData() {
- test_WithGetData(ActionList.class, "actionListDictionaryDatas",
- () -> controller.getActionListDictionaryEntityData(response));
- }
-
- @Test
- public void testGetServiceGroupDictionaryEntityDataByName() {
- test_WithGetDataByColumn(GroupServiceList.class, "serviceGroupDictionaryDatas", "name",
- () -> controller.getServiceGroupDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetServiceGroupDictionaryEntityData() {
- test_WithGetData(GroupServiceList.class, "serviceGroupDictionaryDatas",
- () -> controller.getServiceGroupDictionaryEntityData(response));
- }
-
- @Test
- public void testGetSecurityZoneDictionaryEntityDataByName() {
- test_WithGetDataByColumn(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
- () -> controller.getSecurityZoneDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetSecurityZoneDictionaryEntityData() {
- test_WithGetData(SecurityZone.class, "securityZoneDictionaryDatas",
- () -> controller.getSecurityZoneDictionaryEntityData(response));
- }
-
- @Test
- public void testGetServiceListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
- () -> controller.getServiceListDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetServiceListDictionaryEntityData() {
- test_WithGetData(ServiceList.class, "serviceListDictionaryDatas",
- () -> controller.getServiceListDictionaryEntityData(response));
- }
-
- @Test
- public void testGetZoneDictionaryEntityDataByName() {
- test_WithGetDataByColumn(Zone.class, "zoneDictionaryDatas", "zoneName",
- () -> controller.getZoneDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetZoneDictionaryEntityData() {
- test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> controller.getZoneDictionaryEntityData(response));
- }
-
- @Test
- public void testGetTermListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(TermList.class, "termListDictionaryDatas", "termName",
- () -> controller.getTermListDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetTermListDictionaryEntityData() {
- test_WithGetData(TermList.class, "termListDictionaryDatas",
- () -> controller.getTermListDictionaryEntityData(response));
- }
-
- @Test
- public void testGetFWDictListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
- () -> controller.getFWDictListDictionaryEntityDataByName(response));
- }
-
- @Test
- public void testGetFWDictionaryListEntityData() {
- test_WithGetData(FirewallDictionaryList.class, "fwDictListDictionaryDatas",
- () -> controller.getFWDictionaryListEntityData(response));
- }
-
- @Test
- public void testGetTagPickerNameEntityDataByName() {
- test_WithGetDataByColumn(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
- () -> controller.getTagPickerNameEntityDataByName(response));
- }
-
- @Test
- public void testGetTagPickerDictionaryEntityData() {
- test_WithGetData(FWTagPicker.class, "fwTagPickerDictionaryDatas",
- () -> controller.getTagPickerDictionaryEntityData(response));
- }
-
- @Test
- public void testGetTagNameEntityDataByName() {
- test_WithGetDataByColumn(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
- () -> controller.getTagNameEntityDataByName(response));
- }
-
- @Test
- public void testGetTagDictionaryEntityData() {
- test_WithGetData(FWTag.class, "fwTagDictionaryDatas", () -> controller.getTagDictionaryEntityData(response));
- }
-
- @Test
- public void testSavePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"description\":\"test\",\"prefixListName\":\"Test\"}}";
- testSave(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
- () -> controller.savePrefixListDictionary(request, response));
- }
-
- @Test
- public void testUpdatePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}";
- testUpdate(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
- () -> controller.savePrefixListDictionary(request, response));
- }
-
- @Test
- public void testRemovePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}";
- testRemove(PrefixList.class, "prefixListDictionaryDatas",
- () -> controller.removePrefixListDictionary(request, response));
- }
-
- @Test
- public void testValidatePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}";
- testValidate(PrefixList.class, "result", () -> controller.validatePrefixListDictionary(request, response));
- }
-
- @Test
- public void testSavePortListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}";
- testSave(PortList.class, "portListDictionaryDatas", "portName",
- () -> controller.savePortListDictionary(request, response));
- }
-
- @Test
- public void testUpdatePortListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}";
- testUpdate(PortList.class, "portListDictionaryDatas", "portName",
- () -> controller.savePortListDictionary(request, response));
- }
-
- @Test
- public void testRemovePortListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}";
- testRemove(PortList.class, "portListDictionaryDatas",
- () -> controller.removePortListDictionary(request, response));
- }
-
- @Test
- public void testSaveProtocolListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":\"Test\"}}";
- testSave(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
- () -> controller.saveProtocolListDictionary(request, response));
- }
-
- @Test
- public void testUpdateProtocolListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}";
- testUpdate(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
- () -> controller.saveProtocolListDictionary(request, response));
- }
-
- @Test
- public void testRemoveProtocolListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}";
- testRemove(ProtocolList.class, "protocolListDictionaryDatas",
- () -> controller.removeProtocolListDictionary(request, response));
- }
-
- @Test
- public void testSaveAddressGroupDictionary() {
- jsonString = "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}";
- testSave(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test",
- () -> controller.saveAddressGroupDictionary(request, response));
- }
-
- @Test
- public void testUpdateAddressGroupDictionary() {
- jsonString = "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}";
- testUpdate(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test",
- () -> controller.saveAddressGroupDictionary(request, response));
- }
-
- @Test
- public void testRemoveAddressGroupDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- testRemove(AddressGroup.class, "addressGroupDictionaryDatas",
- () -> controller.removeAddressGroupDictionary(request, response));
- }
-
- @Test
- public void testSaveActionListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":\"Test\"}}";
- testSave(ActionList.class, "actionListDictionaryDatas", "actionName",
- () -> controller.saveActionListDictionary(request, response));
- }
-
- @Test
- public void testUpdateActionListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}";
- testUpdate(ActionList.class, "actionListDictionaryDatas", "actionName",
- () -> controller.saveActionListDictionary(request, response));
- }
-
- @Test
- public void testRemoveActionListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}";
- testRemove(ActionList.class, "actionListDictionaryDatas",
- () -> controller.removeActionListDictionary(request, response));
- }
-
- @Test
- public void testSaveServiceGroupDictionary() {
- jsonString = "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
- testSave(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test",
- () -> controller.saveServiceGroupDictionary(request, response));
- }
-
- @Test
- public void testUpdateServiceGroupDictionary() {
- jsonString = "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
- testUpdate(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test",
- () -> controller.saveServiceGroupDictionary(request, response));
- }
-
- @Test
- public void testRemoveServiceGroupDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- testRemove(GroupServiceList.class, "serviceGroupDictionaryDatas",
- () -> controller.removeServiceGroupDictionary(request, response));
- }
-
- @Test
- public void testSaveSecurityZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":\"Test\"}}";
- testSave(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
- () -> controller.saveSecurityZoneDictionary(request, response));
- }
-
- @Test
- public void testUpdateSecurityZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}";
- testUpdate(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
- () -> controller.saveSecurityZoneDictionary(request, response));
- }
-
- @Test
- public void testRemoveSecurityZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}";
- testRemove(SecurityZone.class, "securityZoneDictionaryDatas",
- () -> controller.removeSecurityZoneDictionary(request, response));
- }
-
- @Test
- public void testSaveServiceListDictionary() {
- jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testSave(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
- () -> controller.saveServiceListDictionary(request, response));
- }
-
- @Test
- public void testUpdateServiceListDictionary() {
- jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testUpdate(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
- () -> controller.saveServiceListDictionary(request, response));
- }
-
- @Test
- public void testRemoveServiceListDictionary() {
- jsonString = "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testRemove(ServiceList.class, "serviceListDictionaryDatas",
- () -> controller.removeServiceListDictionary(request, response));
- }
-
- @Test
- public void testSaveZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
- testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response));
- }
-
- @Test
- public void testUpdateZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
- testUpdate(Zone.class, "zoneDictionaryDatas", "zoneName",
- () -> controller.saveZoneDictionary(request, response));
- }
-
- @Test
- public void testRemoveZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
- testRemove(Zone.class, "zoneDictionaryDatas", () -> controller.removeZoneDictionary(request, response));
- }
-
- @Test
- public void testSaveTermListDictionary() {
- jsonString = "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testSave(TermList.class, "termListDictionaryDatas", "termName",
- () -> controller.saveTermListDictionary(request, response));
- }
-
- @Test
- public void testUpdateTermListDictionary() {
- jsonString = "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testUpdate(TermList.class, "termListDictionaryDatas", "termName",
- () -> controller.saveTermListDictionary(request, response));
- }
-
- @Test
- public void testRemoveTermListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"termDescription\":\"test\",\"termName\":\"Test\"}}";
- testRemove(TermList.class, "termListDictionaryDatas",
- () -> controller.removeTermListDictionary(request, response));
- }
-
- @Test
- public void testSaveFWDictionaryList() {
- jsonString = "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}";
- testSave(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
- () -> controller.saveFWDictionaryList(request, response));
- }
-
- @Test
- public void testUpdateFWDictionaryList() {
- jsonString = "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}";
- testUpdate(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
- () -> controller.saveFWDictionaryList(request, response));
- }
-
- @Test
- public void testRemoveFWDictionaryList() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"parentItemName\":\"Test\"}}";
- testRemove(FirewallDictionaryList.class, "fwDictListDictionaryDatas",
- () -> controller.removeFWDictionaryList(request, response));
- }
-
- @Test
- public void testSaveFirewallTagPickerDictionary() {
- jsonString = "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testSave(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
- () -> controller.saveFirewallTagPickerDictionary(request, response));
- }
-
- @Test
- public void testUpdateFirewallTagPickerDictionary() {
- jsonString = "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testUpdate(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
- () -> controller.saveFirewallTagPickerDictionary(request, response));
- }
-
- @Test
- public void testRemoveFirewallTagPickerDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"tagPickerName\":\"Test\"}}";
- testRemove(FWTagPicker.class, "fwTagPickerDictionaryDatas",
- () -> controller.removeFirewallTagPickerDictionary(request, response));
- }
-
- @Test
- public void testSaveFirewallTagDictionary() {
- jsonString = "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
- testSave(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
- () -> controller.saveFirewallTagDictionary(request, response));
- }
-
- @Test
- public void testUpdateFirewallTagDictionary() {
- jsonString = "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
- testUpdate(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
- () -> controller.saveFirewallTagDictionary(request, response));
- }
-
- @Test
- public void testRemoveFirewallTagDictionary() {
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\"}}";
- testRemove(FWTag.class, "fwTagDictionaryDatas",
- () -> controller.removeFirewallTagDictionary(request, response));
- }
-
- /**
- * Tests a "get" function that uses commonClassDao.getDataByColumn().
- *
- * @param clazz
- * @param contentData
- * @param contentName
- * @param func
- */
- private void test_WithGetDataByColumn(Class<?> clazz, String contentData, String contentName, VoidFunc func) {
- when(commonClassDao.getDataByColumn(clazz, contentName)).thenReturn(data);
- try {
- func.apply();
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
- verify(commonClassDao).getDataByColumn(clazz, contentName);
- } catch (Exception e) {
- fail("get " + clazz.getName() + e);
- }
- }
-
- /**
- * Tests a "get" function that uses commonClassDao.getData().
- *
- * @param clazz
- * @param contentData
- * @param contentName
- * @param func
- */
- private void test_WithGetData(Class<?> clazz, String contentData, VoidFunc func) {
- when(commonClassDao.getData(clazz)).thenReturn(new ArrayList<>());
- try {
- func.apply();
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
- verify(commonClassDao).getData(clazz);
- } catch (Exception e) {
- fail("get " + clazz.getName() + e);
- }
- }
-
- /**
- * Tests a function that uses commonClassDao.save().
- *
- * @param clazz
- * @param contentData
- * @param contentName
- * @param func
- */
- private void testSave(Class<?> clazz, String contentData, String contentName, VoidFunc func) {
- testSave(clazz, contentData, contentName, "Test", func);
- }
-
- /**
- * Tests a function that uses commonClassDao.save().
- *
- * @param clazz
- * @param contentData
- * @param contentName
- * @param testName
- * @param func
- */
- private void testSave(Class<?> clazz, String contentData, String contentName, String testName, VoidFunc func) {
- try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
- when(request.getReader()).thenReturn(br);
- func.apply();
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
- verify(commonClassDao).checkDuplicateEntry(testName, contentName, clazz);
- verify(commonClassDao).save(any());
- verify(commonClassDao, never()).update(any());
- verify(commonClassDao).getData(clazz);
-
- } catch (IOException e) {
- fail("save " + clazz.getName() + e);
- }
- }
-
- /**
- * Tests a function that uses commonClassDao.update().
- *
- * @param clazz
- * @param contentData
- * @param contentName
- * @param func
- */
- private void testUpdate(Class<?> clazz, String contentData, String contentName, VoidFunc func) {
- testUpdate(clazz, contentData, contentName, "Test", func);
- }
-
- /**
- * Tests a function that uses commonClassDao.update().
- *
- * @param clazz
- * @param contentData
- * @param contentName
- * @param testName
- * @param func
- */
- private void testUpdate(Class<?> clazz, String contentData, String contentName, String testName, VoidFunc func) {
- try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
- when(request.getReader()).thenReturn(br);
- func.apply();
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
- verify(commonClassDao).checkDuplicateEntry(testName, contentName, clazz);
- verify(commonClassDao, never()).save(any());
- verify(commonClassDao).update(any());
- verify(commonClassDao).getData(clazz);
-
- } catch (IOException e) {
- fail("update " + clazz.getName() + e);
- }
- }
-
- /**
- * Tests a function that uses commonClassDao.delete() and
- * commonClassDao.getData().
- *
- * @param clazz
- * @param contentData
- * @param func
- */
- private void testRemove(Class<?> clazz, String contentData, VoidFunc func) {
- try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
- when(request.getReader()).thenReturn(br);
- func.apply();
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
- verify(commonClassDao).delete(any());
- verify(commonClassDao).getData(clazz);
-
- } catch (IOException e) {
- fail("remove " + clazz.getName() + e);
- }
- }
-
- /**
- * Tests a "validate" function.
- *
- * @param clazz
- * @param contentData
- * @param func
- */
- private void testValidate(Class<?> clazz, String contentData, VoidFunc func) {
- try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
- when(request.getReader()).thenReturn(br);
- func.apply();
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
-
- } catch (IOException e) {
- fail("save " + clazz.getName() + e);
- }
- }
-
- @FunctionalInterface
- private static interface VoidFunc {
- public void apply() throws IOException;
- }
+ private static Logger logger = FlexLogger.getLogger(FirewallDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private FirewallDictionaryController controller = null;
+ private MockHttpServletResponse response = null;
+ private UserInfo userInfo;
+ private List<String> data;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+
+ data = new ArrayList<>();
+ data.add("Test");
+
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+
+ doNothing().when(commonClassDao).delete(any(Term.class));
+ doNothing().when(commonClassDao).save(any(Term.class));
+
+ controller = new FirewallDictionaryController();
+ FirewallDictionaryController.setCommonClassDao(commonClassDao);
+
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ new DictionaryUtils(commonClassDao);
+ DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
+ mock(DictionaryUtils.class);
+ logger.info("setUp: exit");
+ }
+
+ @Test
+ public void testGetPrefixListDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
+ () -> controller.getPrefixListDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetPrefixListDictionaryEntityData() {
+ test_WithGetData(PrefixList.class, "prefixListDictionaryDatas",
+ () -> controller.getPrefixListDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetPortListDictionaryEntityData() {
+ test_WithGetData(PortList.class, "portListDictionaryDatas",
+ () -> controller.getPortListDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetProtocolListDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
+ () -> controller.getProtocolListDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetProtocolListDictionaryEntityData() {
+ test_WithGetData(ProtocolList.class, "protocolListDictionaryDatas",
+ () -> controller.getProtocolListDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetAddressGroupDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(AddressGroup.class, "addressGroupDictionaryDatas", "name",
+ () -> controller.getAddressGroupDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetAddressGroupDictionaryEntityData() {
+ test_WithGetData(AddressGroup.class, "addressGroupDictionaryDatas",
+ () -> controller.getAddressGroupDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetActionListDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(ActionList.class, "actionListDictionaryDatas", "actionName",
+ () -> controller.getActionListDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetActionListDictionaryEntityData() {
+ test_WithGetData(ActionList.class, "actionListDictionaryDatas",
+ () -> controller.getActionListDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetServiceGroupDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(GroupServiceList.class, "serviceGroupDictionaryDatas", "name",
+ () -> controller.getServiceGroupDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetServiceGroupDictionaryEntityData() {
+ test_WithGetData(GroupServiceList.class, "serviceGroupDictionaryDatas",
+ () -> controller.getServiceGroupDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetSecurityZoneDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
+ () -> controller.getSecurityZoneDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetSecurityZoneDictionaryEntityData() {
+ test_WithGetData(SecurityZone.class, "securityZoneDictionaryDatas",
+ () -> controller.getSecurityZoneDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetServiceListDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
+ () -> controller.getServiceListDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetServiceListDictionaryEntityData() {
+ test_WithGetData(ServiceList.class, "serviceListDictionaryDatas",
+ () -> controller.getServiceListDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetZoneDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(Zone.class, "zoneDictionaryDatas", "zoneName",
+ () -> controller.getZoneDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetZoneDictionaryEntityData() {
+ test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> controller.getZoneDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetTermListDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(TermList.class, "termListDictionaryDatas", "termName",
+ () -> controller.getTermListDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetTermListDictionaryEntityData() {
+ test_WithGetData(TermList.class, "termListDictionaryDatas",
+ () -> controller.getTermListDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetFWDictListDictionaryEntityDataByName() {
+ test_WithGetDataByColumn(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
+ () -> controller.getFWDictListDictionaryEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetFWDictionaryListEntityData() {
+ test_WithGetData(FirewallDictionaryList.class, "fwDictListDictionaryDatas",
+ () -> controller.getFWDictionaryListEntityData(response));
+ }
+
+ @Test
+ public void testGetTagPickerNameEntityDataByName() {
+ test_WithGetDataByColumn(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
+ () -> controller.getTagPickerNameEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetTagPickerDictionaryEntityData() {
+ test_WithGetData(FWTagPicker.class, "fwTagPickerDictionaryDatas",
+ () -> controller.getTagPickerDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testGetTagNameEntityDataByName() {
+ test_WithGetDataByColumn(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
+ () -> controller.getTagNameEntityDataByName(response));
+ }
+
+ @Test
+ public void testGetTagDictionaryEntityData() {
+ test_WithGetData(FWTag.class, "fwTagDictionaryDatas", () -> controller.getTagDictionaryEntityData(response));
+ }
+
+ @Test
+ public void testSavePrefixListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"description\":\"test\",\"prefixListName\":\"Test\"}}";
+ testSave(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
+ () -> controller.savePrefixListDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdatePrefixListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}";
+ testUpdate(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
+ () -> controller.savePrefixListDictionary(request, response));
+ }
+
+ @Test
+ public void testRemovePrefixListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}";
+ testRemove(PrefixList.class, "prefixListDictionaryDatas",
+ () -> controller.removePrefixListDictionary(request, response));
+ }
+
+ @Test
+ public void testValidatePrefixListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}";
+ testValidate(PrefixList.class, "result", () -> controller.validatePrefixListDictionary(request, response));
+ }
+
+ @Test
+ public void testSavePortListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}";
+ testSave(PortList.class, "portListDictionaryDatas", "portName",
+ () -> controller.savePortListDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdatePortListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}";
+ testUpdate(PortList.class, "portListDictionaryDatas", "portName",
+ () -> controller.savePortListDictionary(request, response));
+ }
+
+ @Test
+ public void testRemovePortListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}";
+ testRemove(PortList.class, "portListDictionaryDatas",
+ () -> controller.removePortListDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveProtocolListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":\"Test\"}}";
+ testSave(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
+ () -> controller.saveProtocolListDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateProtocolListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}";
+ testUpdate(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
+ () -> controller.saveProtocolListDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveProtocolListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}";
+ testRemove(ProtocolList.class, "protocolListDictionaryDatas",
+ () -> controller.removeProtocolListDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveAddressGroupDictionary() {
+ jsonString = "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ testSave(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test",
+ () -> controller.saveAddressGroupDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateAddressGroupDictionary() {
+ jsonString = "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ testUpdate(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test",
+ () -> controller.saveAddressGroupDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveAddressGroupDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ testRemove(AddressGroup.class, "addressGroupDictionaryDatas",
+ () -> controller.removeAddressGroupDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveActionListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":\"Test\"}}";
+ testSave(ActionList.class, "actionListDictionaryDatas", "actionName",
+ () -> controller.saveActionListDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateActionListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}";
+ testUpdate(ActionList.class, "actionListDictionaryDatas", "actionName",
+ () -> controller.saveActionListDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveActionListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}";
+ testRemove(ActionList.class, "actionListDictionaryDatas",
+ () -> controller.removeActionListDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveServiceGroupDictionary() {
+ jsonString = "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ testSave(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test",
+ () -> controller.saveServiceGroupDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateServiceGroupDictionary() {
+ jsonString = "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ testUpdate(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test",
+ () -> controller.saveServiceGroupDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveServiceGroupDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ testRemove(GroupServiceList.class, "serviceGroupDictionaryDatas",
+ () -> controller.removeServiceGroupDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveSecurityZoneDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":\"Test\"}}";
+ testSave(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
+ () -> controller.saveSecurityZoneDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateSecurityZoneDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}";
+ testUpdate(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
+ () -> controller.saveSecurityZoneDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveSecurityZoneDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}";
+ testRemove(SecurityZone.class, "securityZoneDictionaryDatas",
+ () -> controller.removeSecurityZoneDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveServiceListDictionary() {
+ jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testSave(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
+ () -> controller.saveServiceListDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateServiceListDictionary() {
+ jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testUpdate(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
+ () -> controller.saveServiceListDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveServiceListDictionary() {
+ jsonString = "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testRemove(ServiceList.class, "serviceListDictionaryDatas",
+ () -> controller.removeServiceListDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveZoneDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
+ testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateZoneDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
+ testUpdate(Zone.class, "zoneDictionaryDatas", "zoneName",
+ () -> controller.saveZoneDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveZoneDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
+ testRemove(Zone.class, "zoneDictionaryDatas", () -> controller.removeZoneDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveTermListDictionary() {
+ jsonString = "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testSave(TermList.class, "termListDictionaryDatas", "termName",
+ () -> controller.saveTermListDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateTermListDictionary() {
+ jsonString = "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testUpdate(TermList.class, "termListDictionaryDatas", "termName",
+ () -> controller.saveTermListDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveTermListDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"termDescription\":\"test\",\"termName\":\"Test\"}}";
+ testRemove(TermList.class, "termListDictionaryDatas",
+ () -> controller.removeTermListDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveFWDictionaryList() {
+ jsonString = "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}";
+ testSave(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
+ () -> controller.saveFWDictionaryList(request, response));
+ }
+
+ @Test
+ public void testUpdateFWDictionaryList() {
+ jsonString = "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}";
+ testUpdate(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
+ () -> controller.saveFWDictionaryList(request, response));
+ }
+
+ @Test
+ public void testRemoveFWDictionaryList() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"parentItemName\":\"Test\"}}";
+ testRemove(FirewallDictionaryList.class, "fwDictListDictionaryDatas",
+ () -> controller.removeFWDictionaryList(request, response));
+ }
+
+ @Test
+ public void testSaveFirewallTagPickerDictionary() {
+ jsonString = "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testSave(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
+ () -> controller.saveFirewallTagPickerDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateFirewallTagPickerDictionary() {
+ jsonString = "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testUpdate(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
+ () -> controller.saveFirewallTagPickerDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveFirewallTagPickerDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"tagPickerName\":\"Test\"}}";
+ testRemove(FWTagPicker.class, "fwTagPickerDictionaryDatas",
+ () -> controller.removeFirewallTagPickerDictionary(request, response));
+ }
+
+ @Test
+ public void testSaveFirewallTagDictionary() {
+ jsonString = "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
+ testSave(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
+ () -> controller.saveFirewallTagDictionary(request, response));
+ }
+
+ @Test
+ public void testUpdateFirewallTagDictionary() {
+ jsonString = "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
+ testUpdate(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
+ () -> controller.saveFirewallTagDictionary(request, response));
+ }
+
+ @Test
+ public void testRemoveFirewallTagDictionary() {
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\"}}";
+ testRemove(FWTag.class, "fwTagDictionaryDatas",
+ () -> controller.removeFirewallTagDictionary(request, response));
+ }
+
+ /**
+ * Tests a "get" function that uses commonClassDao.getDataByColumn().
+ *
+ * @param clazz
+ * @param contentData
+ * @param contentName
+ * @param func
+ */
+ private void test_WithGetDataByColumn(Class<?> clazz, String contentData, String contentName, VoidFunc func) {
+ when(commonClassDao.getDataByColumn(clazz, contentName)).thenReturn(data);
+ try {
+ func.apply();
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
+ verify(commonClassDao).getDataByColumn(clazz, contentName);
+ } catch (Exception e) {
+ fail("get " + clazz.getName() + e);
+ }
+ }
+
+ /**
+ * Tests a "get" function that uses commonClassDao.getData().
+ *
+ * @param clazz
+ * @param contentData
+ * @param contentName
+ * @param func
+ */
+ private void test_WithGetData(Class<?> clazz, String contentData, VoidFunc func) {
+ when(commonClassDao.getData(clazz)).thenReturn(new ArrayList<>());
+ try {
+ func.apply();
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
+ verify(commonClassDao).getData(clazz);
+ } catch (Exception e) {
+ fail("get " + clazz.getName() + e);
+ }
+ }
+
+ /**
+ * Tests a function that uses commonClassDao.save().
+ *
+ * @param clazz
+ * @param contentData
+ * @param contentName
+ * @param func
+ */
+ private void testSave(Class<?> clazz, String contentData, String contentName, VoidFunc func) {
+ testSave(clazz, contentData, contentName, "Test", func);
+ }
+
+ /**
+ * Tests a function that uses commonClassDao.save().
+ *
+ * @param clazz
+ * @param contentData
+ * @param contentName
+ * @param testName
+ * @param func
+ */
+ private void testSave(Class<?> clazz, String contentData, String contentName, String testName, VoidFunc func) {
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
+ when(request.getReader()).thenReturn(br);
+ func.apply();
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
+ verify(commonClassDao).checkDuplicateEntry(testName, contentName, clazz);
+ verify(commonClassDao).save(any());
+ verify(commonClassDao, never()).update(any());
+ verify(commonClassDao).getData(clazz);
+
+ } catch (IOException e) {
+ fail("save " + clazz.getName() + e);
+ }
+ }
+
+ /**
+ * Tests a function that uses commonClassDao.update().
+ *
+ * @param clazz
+ * @param contentData
+ * @param contentName
+ * @param func
+ */
+ private void testUpdate(Class<?> clazz, String contentData, String contentName, VoidFunc func) {
+ testUpdate(clazz, contentData, contentName, "Test", func);
+ }
+
+ /**
+ * Tests a function that uses commonClassDao.update().
+ *
+ * @param clazz
+ * @param contentData
+ * @param contentName
+ * @param testName
+ * @param func
+ */
+ private void testUpdate(Class<?> clazz, String contentData, String contentName, String testName, VoidFunc func) {
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
+ when(request.getReader()).thenReturn(br);
+ func.apply();
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
+ verify(commonClassDao).checkDuplicateEntry(testName, contentName, clazz);
+ verify(commonClassDao, never()).save(any());
+ verify(commonClassDao).update(any());
+ verify(commonClassDao).getData(clazz);
+
+ } catch (IOException e) {
+ fail("update " + clazz.getName() + e);
+ }
+ }
+
+ /**
+ * Tests a function that uses commonClassDao.delete() and
+ * commonClassDao.getData().
+ *
+ * @param clazz
+ * @param contentData
+ * @param func
+ */
+ private void testRemove(Class<?> clazz, String contentData, VoidFunc func) {
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
+ when(request.getReader()).thenReturn(br);
+ func.apply();
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
+ verify(commonClassDao).delete(any());
+ verify(commonClassDao).getData(clazz);
+
+ } catch (IOException e) {
+ fail("remove " + clazz.getName() + e);
+ }
+ }
+
+ /**
+ * Tests a "validate" function.
+ *
+ * @param clazz
+ * @param contentData
+ * @param func
+ */
+ private void testValidate(Class<?> clazz, String contentData, VoidFunc func) {
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
+ when(request.getReader()).thenReturn(br);
+ func.apply();
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains(contentData));
+
+ } catch (IOException e) {
+ fail("save " + clazz.getName() + e);
+ }
+ }
+
+ @FunctionalInterface
+ private static interface VoidFunc {
+ public void apply() throws IOException;
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java
index ae71692c1..2e9df2592 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java
@@ -58,17 +58,17 @@ import org.springframework.mock.web.MockHttpServletResponse;
*/
public class MicroServiceDictionaryControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(MicroServiceDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private MicroServiceDictionaryController controller = null;
- BufferedReader br = null;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
+
+ private static Logger logger = FlexLogger.getLogger(MicroServiceDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private MicroServiceDictionaryController controller = null;
+ BufferedReader br = null;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
commonClassDao = Mockito.mock(CommonClassDao.class);
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId("testUserId");
@@ -89,21 +89,21 @@ public class MicroServiceDictionaryControllerTest {
MicroServiceModels microServiceModels = new MicroServiceModels();
doNothing().when(commonClassDao).delete(microServiceModels);
-
- MicroServiceDictionaryController.setCommonClassDao(commonClassDao);
-
- controller = new MicroServiceDictionaryController();
+
+ MicroServiceDictionaryController.setCommonClassDao(commonClassDao);
+
+ controller = new MicroServiceDictionaryController();
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- jsonString = "{\"microServiceModelsDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ jsonString = "{\"microServiceModelsDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
br = new BufferedReader(new StringReader(jsonString));
//--- mock the getReader() call
@@ -112,653 +112,653 @@ public class MicroServiceDictionaryControllerTest {
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
logger.info("setUp: exit");
- }
-
-
- @Test
- public void testSaveMicroServiceHeaderDefaultValues() {
- logger.info("testSaveMicroServiceHeaderDefaultValues: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"modelAttributeDictionaryData\": {\"onapName\": \"test\", \"guard\": false,\"priority\": \"3\","
- + " \"riskType\": \"test\", \"riskLevel\": \"7\", \"modelName\": \"testname\"}}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveMicroServiceHeaderDefaultValues(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveMicroServiceHeaderDefaultValues: exit");
- }
-
-
- @Test
- public void testGetMicroServiceHeaderDefaultsEntityDataByName() {
- logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceHeaderDefaultsEntityDataByName(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: exit");
- }
-
- @Test
- public void testGetMicroServiceHeaderDefaultsEntityData() {
- logger.info("testGetMicroServiceHeaderDefaultsEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceHeaderDefaultsEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceHeaderDefaultsEntityData: exit");
- }
-
- @Test
- public void testRemoveMicroServiceHeaderDefaults() {
- logger.info("testRemoveMicroServiceHeaderDefaults: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeMicroServiceHeaderDefaults(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveMicroServiceHeaderDefaults: exit");
- }
-
-
- @Test
- public void testGetDCAEUUIDDictionaryByNameEntityData() {
-
- logger.info("testGetDCAEUUIDDictionaryByNameEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getDCAEUUIDDictionaryByNameEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetDCAEUUIDDictionaryByNameEntityData: exit");
- }
-
- @Test
- public void testGetDCAEUUIDDictionaryEntityData() {
-
- logger.info("testGetDCAEUUIDDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getDCAEUUIDDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetDCAEUUIDDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveDCAEUUIDDictionary() {
- logger.info("testSaveDCAEUUIDDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"dcaeUUIDDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveDCAEUUIDDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveDCAEUUIDDictionary: exit");
- }
-
- @Test
- public void testRemoveDCAEUUIDDictionary() {
- logger.info("testRemoveDCAEUUIDDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeMicroServiceConfigNameDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveDCAEUUIDDictionary: exit");
- }
-
- @Test
- public void testGetMicroServiceConfigNameByNameDictionaryEntityData() {
- logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceConfigNameByNameDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: exit");
- }
-
- @Test
- public void testGetMicroServiceConfigNameDictionaryEntityData() {
- logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceConfigNameDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceConfigNameDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveMicroServiceConfigNameDictionary() {
- logger.info("testSaveMicroServiceConfigNameDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"microServiceConfigNameDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveMicroServiceConfigNameDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveMicroServiceConfigNameDictionary: exit");
- }
-
- @Test
- public void testRemoveMicroServiceConfigNameDictionary() {
- logger.info("testRemoveMicroServiceConfigNameDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeMicroServiceConfigNameDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveMicroServiceConfigNameDictionary: exit");
- }
-
- @Test
- public void testGetMicroServiceLocationByNameDictionaryEntityData() {
-
- logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceLocationByNameDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: exit");
- }
-
- @Test
- public void testGetMicroServiceLocationDictionaryEntityData() {
- logger.info("testGetMicroServiceLocationDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceLocationDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceLocationDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveMicroServiceLocationDictionary() {
- logger.info("testSaveMicroServiceLocationDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"microServiceLocationDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveMicroServiceLocationDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveMicroServiceLocationDictionary: exit");
- }
-
- @Test
- public void testRemoveMicroServiceLocationDictionary() {
- logger.info("testRemoveMicroServiceLocationDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
-
- when(request.getReader()).thenReturn(br);
- controller.removeMicroServiceLocationDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveMicroServiceLocationDictionary: exit");
- }
-
- @Test
- public void testGetMicroServiceAttributeByNameDictionaryEntityData() {
- logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceAttributeByNameDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: exit");
- }
-
- @Test
- public void testGetMicroServiceAttributeDictionaryEntityData() {
- logger.info("testGetMicroServiceAttributeDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceAttributeDictionaryEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceAttributeDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveMicroServiceAttributeDictionary() {
- logger.info("testSaveMicroServiceAttributeDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"modelAttributeDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.saveMicroServiceAttributeDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveMicroServiceAttributeDictionary: exit");
- }
-
- @Test
- public void testRemoveMicroServiceAttributeDictionary() {
- logger.info("testRemoveMicroServiceAttributeDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeMicroServiceAttributeDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveMicroServiceAttributeDictionary: exit");
- }
-
- @Test
- public void testGetMicroServiceModelsDictionaryByNameEntityData() {
- logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
-
- controller.getMicroServiceModelsDictionaryByNameEntityData(response);
-
- try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- } catch (UnsupportedEncodingException e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: exit");
- }
-
- @Test
- public void testGetMicroServiceModelsDictionaryByVersionEntityData() {
- logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
-
- BufferedReader br = new BufferedReader(new StringReader(msModelJson));
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.getMicroServiceModelsDictionaryByVersionEntityData(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("No model name given"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: exit");
- }
-
- @Test
- public void testGetMicroServiceModelsDictionaryEntityData() {
- logger.info("testGetMicroServiceModelsDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
-
- BufferedReader br = new BufferedReader(new StringReader(msModelJson));
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.getMicroServiceModelsDictionaryEntityData(response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceModelsDictionaryEntityData: exit");
- }
-
- @Test
- public void testGetMicroServiceModelsDictionaryEntityDataServiceVersion() {
- logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
-
- BufferedReader br = new BufferedReader(new StringReader(msModelJson));
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.getMicroServiceModelsDictionaryEntityDataServiceVersion(response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: exit");
- }
-
- @Test
- public void testGetMicroServiceModelsDictionaryClassEntityData() {
- logger.info("testGetMicroServiceModelsDictionaryClassEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
-
- BufferedReader br = new BufferedReader(new StringReader(msModelJson));
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.getMicroServiceModelsDictionaryClassEntityData(response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryClassDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetMicroServiceModelsDictionaryClassEntityData: exit");
- }
-
- @Test
- public void testSaveMicroServiceModelsDictionary() {
- logger.info("testSaveMicroServiceModelsDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.saveMicroServiceModelsDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveMicroServiceModelsDictionary: exit");
- }
-
- @Test
- public void testRemoveMicroServiceModelsDictionary() {
- logger.info("testRemoveMicroServiceModelsDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
-
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeMicroServiceModelsDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveMicroServiceModelsDictionary: exit");
- }
+ }
+
+
+ @Test
+ public void testSaveMicroServiceHeaderDefaultValues() {
+ logger.info("testSaveMicroServiceHeaderDefaultValues: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"modelAttributeDictionaryData\": {\"onapName\": \"test\", \"guard\": false,\"priority\": \"3\","
+ + " \"riskType\": \"test\", \"riskLevel\": \"7\", \"modelName\": \"testname\"}}";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveMicroServiceHeaderDefaultValues(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveMicroServiceHeaderDefaultValues: exit");
+ }
+
+
+ @Test
+ public void testGetMicroServiceHeaderDefaultsEntityDataByName() {
+ logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceHeaderDefaultsEntityDataByName(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceHeaderDefaultsEntityData() {
+ logger.info("testGetMicroServiceHeaderDefaultsEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceHeaderDefaultsEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceHeaderDefaultsEntityData: exit");
+ }
+
+ @Test
+ public void testRemoveMicroServiceHeaderDefaults() {
+ logger.info("testRemoveMicroServiceHeaderDefaults: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeMicroServiceHeaderDefaults(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceHeaderDefaultDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveMicroServiceHeaderDefaults: exit");
+ }
+
+
+ @Test
+ public void testGetDCAEUUIDDictionaryByNameEntityData() {
+
+ logger.info("testGetDCAEUUIDDictionaryByNameEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getDCAEUUIDDictionaryByNameEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetDCAEUUIDDictionaryByNameEntityData: exit");
+ }
+
+ @Test
+ public void testGetDCAEUUIDDictionaryEntityData() {
+
+ logger.info("testGetDCAEUUIDDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getDCAEUUIDDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetDCAEUUIDDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveDCAEUUIDDictionary() {
+ logger.info("testSaveDCAEUUIDDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"dcaeUUIDDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveDCAEUUIDDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveDCAEUUIDDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveDCAEUUIDDictionary() {
+ logger.info("testRemoveDCAEUUIDDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeMicroServiceConfigNameDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveDCAEUUIDDictionary: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceConfigNameByNameDictionaryEntityData() {
+ logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceConfigNameByNameDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceConfigNameDictionaryEntityData() {
+ logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceConfigNameDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceConfigNameDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveMicroServiceConfigNameDictionary() {
+ logger.info("testSaveMicroServiceConfigNameDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"microServiceConfigNameDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveMicroServiceConfigNameDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveMicroServiceConfigNameDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveMicroServiceConfigNameDictionary() {
+ logger.info("testRemoveMicroServiceConfigNameDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeMicroServiceConfigNameDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceConfigNameDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveMicroServiceConfigNameDictionary: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceLocationByNameDictionaryEntityData() {
+
+ logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceLocationByNameDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceLocationDictionaryEntityData() {
+ logger.info("testGetMicroServiceLocationDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceLocationDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceLocationDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveMicroServiceLocationDictionary() {
+ logger.info("testSaveMicroServiceLocationDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"microServiceLocationDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveMicroServiceLocationDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveMicroServiceLocationDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveMicroServiceLocationDictionary() {
+ logger.info("testRemoveMicroServiceLocationDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+
+ when(request.getReader()).thenReturn(br);
+ controller.removeMicroServiceLocationDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveMicroServiceLocationDictionary: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceAttributeByNameDictionaryEntityData() {
+ logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceAttributeByNameDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceAttributeDictionaryEntityData() {
+ logger.info("testGetMicroServiceAttributeDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceAttributeDictionaryEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceAttributeDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveMicroServiceAttributeDictionary() {
+ logger.info("testSaveMicroServiceAttributeDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"modelAttributeDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.saveMicroServiceAttributeDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveMicroServiceAttributeDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveMicroServiceAttributeDictionary() {
+ logger.info("testRemoveMicroServiceAttributeDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeMicroServiceAttributeDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveMicroServiceAttributeDictionary: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceModelsDictionaryByNameEntityData() {
+ logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ controller.getMicroServiceModelsDictionaryByNameEntityData(response);
+
+ try {
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ } catch (UnsupportedEncodingException e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceModelsDictionaryByVersionEntityData() {
+ logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
+
+ BufferedReader br = new BufferedReader(new StringReader(msModelJson));
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.getMicroServiceModelsDictionaryByVersionEntityData(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("No model name given"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceModelsDictionaryEntityData() {
+ logger.info("testGetMicroServiceModelsDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
+
+ BufferedReader br = new BufferedReader(new StringReader(msModelJson));
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.getMicroServiceModelsDictionaryEntityData(response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceModelsDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceModelsDictionaryEntityDataServiceVersion() {
+ logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
+
+ BufferedReader br = new BufferedReader(new StringReader(msModelJson));
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.getMicroServiceModelsDictionaryEntityDataServiceVersion(response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: exit");
+ }
+
+ @Test
+ public void testGetMicroServiceModelsDictionaryClassEntityData() {
+ logger.info("testGetMicroServiceModelsDictionaryClassEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}";
+
+ BufferedReader br = new BufferedReader(new StringReader(msModelJson));
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.getMicroServiceModelsDictionaryClassEntityData(response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryClassDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetMicroServiceModelsDictionaryClassEntityData: exit");
+ }
+
+ @Test
+ public void testSaveMicroServiceModelsDictionary() {
+ logger.info("testSaveMicroServiceModelsDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.saveMicroServiceModelsDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveMicroServiceModelsDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveMicroServiceModelsDictionary() {
+ logger.info("testRemoveMicroServiceModelsDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeMicroServiceModelsDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveMicroServiceModelsDictionary: exit");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java
index edc08f31b..dd355d948 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java
@@ -49,17 +49,17 @@ import org.springframework.mock.web.MockHttpServletResponse;
public class OptimizationDictionaryControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(OptimizationDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private OptimizationDictionaryController controller = null;
- BufferedReader br = null;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
+
+ private static Logger logger = FlexLogger.getLogger(OptimizationDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private OptimizationDictionaryController controller = null;
+ BufferedReader br = null;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
commonClassDao = Mockito.mock(CommonClassDao.class);
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId("testUserId");
@@ -69,21 +69,21 @@ public class OptimizationDictionaryControllerTest {
OptimizationModels optimziationModels = new OptimizationModels();
doNothing().when(commonClassDao).delete(optimziationModels);
-
+
OptimizationDictionaryController.setCommonClassDao(commonClassDao);
-
- controller = new OptimizationDictionaryController();
+
+ controller = new OptimizationDictionaryController();
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- jsonString = "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+ jsonString = "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
br = new BufferedReader(new StringReader(jsonString));
//--- mock the getReader() call
@@ -92,82 +92,82 @@ public class OptimizationDictionaryControllerTest {
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
logger.info("setUp: exit");
- }
-
- @Test
- public void testGetOptimizationModelsDictionaryEntityData() {
- logger.info("testGetOptimizationModelsDictionaryEntityData: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- String modelJson = "{\"optimizationModelsDictionaryData\":[\"modelName\"]}";
-
- BufferedReader br = new BufferedReader(new StringReader(modelJson));
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.getOptimizationModelsDictionaryEntityData(response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testGetOptimizationModelsDictionaryEntityData: exit");
- }
-
- @Test
- public void testSaveOptimizationModelsDictionary() {
- logger.info("testSaveOptimizationModelsDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- when(request.getReader()).thenReturn(br);
- controller.saveOptimizationModelsDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testSaveOptimizationModelsDictionary: exit");
- }
-
- @Test
- public void testRemoveOptimizationModelsDictionary() {
- logger.info("testRemoveOptimizationModelsDictionary: Entering");
-
- MockHttpServletResponse response = new MockHttpServletResponse();
- request = mock(HttpServletRequest.class);
-
- try {
- // mock the getReader() call
- jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
- + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
- + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
- + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
- + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
- + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
- + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
- + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
-
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
- when(request.getReader()).thenReturn(br);
- controller.removeOptimizationModelsDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
-
- } catch (Exception e) {
- fail("Exception: " + e);
- }
-
- logger.info("testRemoveOptimizationModelsDictionary: exit");
- }
+ }
+
+ @Test
+ public void testGetOptimizationModelsDictionaryEntityData() {
+ logger.info("testGetOptimizationModelsDictionaryEntityData: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String modelJson = "{\"optimizationModelsDictionaryData\":[\"modelName\"]}";
+
+ BufferedReader br = new BufferedReader(new StringReader(modelJson));
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.getOptimizationModelsDictionaryEntityData(response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testGetOptimizationModelsDictionaryEntityData: exit");
+ }
+
+ @Test
+ public void testSaveOptimizationModelsDictionary() {
+ logger.info("testSaveOptimizationModelsDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+ controller.saveOptimizationModelsDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testSaveOptimizationModelsDictionary: exit");
+ }
+
+ @Test
+ public void testRemoveOptimizationModelsDictionary() {
+ logger.info("testRemoveOptimizationModelsDictionary: Entering");
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ request = mock(HttpServletRequest.class);
+
+ try {
+ // mock the getReader() call
+ jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ when(request.getReader()).thenReturn(br);
+ controller.removeOptimizationModelsDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
+
+ } catch (Exception e) {
+ fail("Exception: " + e);
+ }
+
+ logger.info("testRemoveOptimizationModelsDictionary: exit");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java
index 40ec34831..9bf2ae590 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java
@@ -48,338 +48,338 @@ import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.mock.web.MockHttpServletResponse;
public class PolicyScopeDictionaryControllerTest {
- private static Logger logger = FlexLogger.getLogger(PolicyScopeDictionaryControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private PolicyScopeDictionaryController controller = null;
- private MockHttpServletResponse response = null;
- private UserInfo userInfo;
- private List<String> data;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
-
- data = new ArrayList<>();
- data.add("Test");
-
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
-
- doNothing().when(commonClassDao).delete(new GroupPolicyScopeList());
- doNothing().when(commonClassDao).save(new GroupPolicyScopeList());
-
- controller = new PolicyScopeDictionaryController();
- controller.setCommonClassDao(commonClassDao);
-
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- new DictionaryUtils(commonClassDao);
+ private static Logger logger = FlexLogger.getLogger(PolicyScopeDictionaryControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private PolicyScopeDictionaryController controller = null;
+ private MockHttpServletResponse response = null;
+ private UserInfo userInfo;
+ private List<String> data;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+
+ data = new ArrayList<>();
+ data.add("Test");
+
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+
+ doNothing().when(commonClassDao).delete(new GroupPolicyScopeList());
+ doNothing().when(commonClassDao).save(new GroupPolicyScopeList());
+
+ controller = new PolicyScopeDictionaryController();
+ controller.setCommonClassDao(commonClassDao);
+
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
- logger.info("setUp: exit");
- }
-
- @Test
- public void testGetGroupPolicyScopeEntityDataByName(){
- when(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name")).thenReturn(data);
- controller.getGroupPolicyScopeEntityDataByName(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetGroupPolicyScopeEntityData(){
- when(commonClassDao.getData(GroupPolicyScopeList.class)).thenReturn(new ArrayList<>());
- controller.getGroupPolicyScopeEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSClosedLoopEntityDataByName(){
- when(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name")).thenReturn(data);
- controller.getPSClosedLoopEntityDataByName(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSClosedLoopEntityData(){
- when(commonClassDao.getData(PolicyScopeClosedLoop.class)).thenReturn(new ArrayList<>());
- controller.getPSClosedLoopEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSServiceEntityDataByName(){
- when(commonClassDao.getDataByColumn(PolicyScopeService.class, "name")).thenReturn(data);
- controller.getPSServiceEntityDataByName(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSServiceEntityData(){
- when(commonClassDao.getData(PolicyScopeService.class)).thenReturn(new ArrayList<>());
- controller.getPSServiceEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSTypeEntityDataByName(){
- when(commonClassDao.getDataByColumn(PolicyScopeType.class, "name")).thenReturn(data);
- controller.getPSTypeEntityDataByName(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSTypeEntityData(){
- when(commonClassDao.getData(PolicyScopeType.class)).thenReturn(new ArrayList<>());
- controller.getPSTypeEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSResourceEntityDataByName(){
- when(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name")).thenReturn(data);
- controller.getPSResourceEntityDataByName(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetPSResourceEntityData(){
- when(commonClassDao.getData(PolicyScopeResource.class)).thenReturn(new ArrayList<>());
- controller.getPSResourceEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testSavePSGroupScopeDictionary(){
- jsonString = "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSGroupScopeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdatePSGroupScopeDictionary(){
- jsonString = "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSGroupScopeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemovePSGroupScopeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removePSGroupScopeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSavePSClosedLoopDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSClosedLoopDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdatePSClosedLoopDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSClosedLoopDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemovePSClosedLoopDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removePSClosedLoopDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSavePSServiceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSServiceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdatePSServiceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSServiceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemovePSServiceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removePSServiceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSavePSTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdatePSTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemovePSTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removePSTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSavePSResourceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSResourceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdatePSResourceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.savePSResourceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemovePSResourceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removePSResourceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
+ logger.info("setUp: exit");
+ }
+
+ @Test
+ public void testGetGroupPolicyScopeEntityDataByName(){
+ when(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name")).thenReturn(data);
+ controller.getGroupPolicyScopeEntityDataByName(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetGroupPolicyScopeEntityData(){
+ when(commonClassDao.getData(GroupPolicyScopeList.class)).thenReturn(new ArrayList<>());
+ controller.getGroupPolicyScopeEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSClosedLoopEntityDataByName(){
+ when(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name")).thenReturn(data);
+ controller.getPSClosedLoopEntityDataByName(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSClosedLoopEntityData(){
+ when(commonClassDao.getData(PolicyScopeClosedLoop.class)).thenReturn(new ArrayList<>());
+ controller.getPSClosedLoopEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSServiceEntityDataByName(){
+ when(commonClassDao.getDataByColumn(PolicyScopeService.class, "name")).thenReturn(data);
+ controller.getPSServiceEntityDataByName(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSServiceEntityData(){
+ when(commonClassDao.getData(PolicyScopeService.class)).thenReturn(new ArrayList<>());
+ controller.getPSServiceEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSTypeEntityDataByName(){
+ when(commonClassDao.getDataByColumn(PolicyScopeType.class, "name")).thenReturn(data);
+ controller.getPSTypeEntityDataByName(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSTypeEntityData(){
+ when(commonClassDao.getData(PolicyScopeType.class)).thenReturn(new ArrayList<>());
+ controller.getPSTypeEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSResourceEntityDataByName(){
+ when(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name")).thenReturn(data);
+ controller.getPSResourceEntityDataByName(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetPSResourceEntityData(){
+ when(commonClassDao.getData(PolicyScopeResource.class)).thenReturn(new ArrayList<>());
+ controller.getPSResourceEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testSavePSGroupScopeDictionary(){
+ jsonString = "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSGroupScopeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdatePSGroupScopeDictionary(){
+ jsonString = "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSGroupScopeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemovePSGroupScopeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removePSGroupScopeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSavePSClosedLoopDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSClosedLoopDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdatePSClosedLoopDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSClosedLoopDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemovePSClosedLoopDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removePSClosedLoopDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSavePSServiceDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSServiceDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdatePSServiceDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSServiceDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemovePSServiceDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removePSServiceDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSavePSTypeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSTypeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdatePSTypeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSTypeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemovePSTypeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removePSTypeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSavePSResourceDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSResourceDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdatePSResourceDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.savePSResourceDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemovePSResourceDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removePSResourceDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java
index 1f8cb6f90..dbddecc51 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java
@@ -54,22 +54,22 @@ import com.att.research.xacml.api.pap.PAPException;
public class PushPolicyControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private PushPolicyController controller = null;
- private HttpServletResponse response = null;
+
+ private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private PushPolicyController controller = null;
+ private HttpServletResponse response = null;
private List<String> headers = new ArrayList<>();
private ServletConfig servletConfig;
private XACMLPapServlet pap;
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- request = Mockito.mock(HttpServletRequest.class);
- response = Mockito.mock(HttpServletResponse.class);
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ request = Mockito.mock(HttpServletRequest.class);
+ response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headers));
Mockito.when(request.getAttributeNames()).thenReturn(Collections.enumeration(headers));
@@ -78,72 +78,72 @@ public class PushPolicyControllerTest {
Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("src/test/resources/xacml.pap.properties");
- commonClassDao = Mockito.mock(CommonClassDao.class);
- controller = new PushPolicyController();
- controller.setCommonClassDao(commonClassDao);
- logger.info("setUp: exit");
- }
-
- @Test
- public void testPushPolicy() throws ServletException, PAPException{
- PolicyVersion versionData = new PolicyVersion();
- versionData.setPolicyName("com"+File.separator+"Config_Test");
- versionData.setActiveVersion(1);
- versionData.setHigherVersion(1);
- List<Object> data = new ArrayList<>();
- data.add(versionData);
- when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(data);
- pap = new XACMLPapServlet();
- pap.init(servletConfig);
- callPushPolicy();
- when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(null);
- callPushPolicy();
- }
-
- public void callPushPolicy(){
- jsonString = "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- char[] charBuffer = new char[8 * 1024];
- StringBuilder builder = new StringBuilder();
- int numCharsRead;
- while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
- builder.append(charBuffer, 0, numCharsRead);
- }
- when(request.getInputStream()).thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)));
- controller.pushPolicy(request, response);
- assertTrue(response != null);
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- public ServletInputStream getInputStream(byte[] body) throws IOException {
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+ controller = new PushPolicyController();
+ controller.setCommonClassDao(commonClassDao);
+ logger.info("setUp: exit");
+ }
+
+ @Test
+ public void testPushPolicy() throws ServletException, PAPException{
+ PolicyVersion versionData = new PolicyVersion();
+ versionData.setPolicyName("com"+File.separator+"Config_Test");
+ versionData.setActiveVersion(1);
+ versionData.setHigherVersion(1);
+ List<Object> data = new ArrayList<>();
+ data.add(versionData);
+ when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(data);
+ pap = new XACMLPapServlet();
+ pap.init(servletConfig);
+ callPushPolicy();
+ when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(null);
+ callPushPolicy();
+ }
+
+ public void callPushPolicy(){
+ jsonString = "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ char[] charBuffer = new char[8 * 1024];
+ StringBuilder builder = new StringBuilder();
+ int numCharsRead;
+ while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
+ builder.append(charBuffer, 0, numCharsRead);
+ }
+ when(request.getInputStream()).thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)));
+ controller.pushPolicy(request, response);
+ assertTrue(response != null);
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ public ServletInputStream getInputStream(byte[] body) throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
- @Override
- public boolean isFinished() {
- return false;
- }
+ @Override
+ public boolean isFinished() {
+ return false;
+ }
- @Override
- public boolean isReady() {
- return false;
- }
+ @Override
+ public boolean isReady() {
+ return false;
+ }
- @Override
- public void setReadListener(ReadListener readListener) {
- }
+ @Override
+ public void setReadListener(ReadListener readListener) {
+ }
};
return servletInputStream;
}
-
- @After
- public void destroy(){
- if(pap!=null)
- pap.destroy();
- }
+
+ @After
+ public void destroy(){
+ if(pap!=null)
+ pap.destroy();
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java
index 7d23475a1..ae1840ebb 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java
@@ -45,158 +45,158 @@ import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.mock.web.MockHttpServletResponse;
public class SafePolicyControllerTest {
-
- private static Logger logger = FlexLogger.getLogger(SafePolicyControllerTest.class);
- private static CommonClassDao commonClassDao;
- private String jsonString = null;
- private HttpServletRequest request = null;
- private SafePolicyController controller = null;
- private MockHttpServletResponse response = null;
- private UserInfo userInfo;
- private List<String> data;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- commonClassDao = Mockito.mock(CommonClassDao.class);
-
- data = new ArrayList<>();
- data.add("Test");
-
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
-
- doNothing().when(commonClassDao).delete(new RiskType());
- doNothing().when(commonClassDao).save(new RiskType());
-
- controller = new SafePolicyController();
- controller.setCommonClassDao(commonClassDao);
- new DictionaryUtils(commonClassDao);
- DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
- mock(DictionaryUtils.class);
- request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
- logger.info("setUp: exit");
- }
-
- @Test
- public void testGetRiskTypeDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(RiskType.class, "name")).thenReturn(data);
- controller.getRiskTypeDictionaryByNameEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetRiskTypeDictionaryEntityData(){
- when(commonClassDao.getData(RiskType.class)).thenReturn(new ArrayList<>());
- controller.getRiskTypeDictionaryEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetSafePolicyWarningEntityDataByName(){
- when(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name")).thenReturn(data);
- controller.getSafePolicyWarningEntityDataByName(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testGetSafePolicyWarningeEntityData(){
- when(commonClassDao.getData(SafePolicyWarning.class)).thenReturn(new ArrayList<>());
- controller.getSafePolicyWarningeEntityData(response);
- try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- } catch (Exception e) {
- fail();
- logger.error(e.getMessage(),e);
- }
- }
-
- @Test
- public void testSaveRiskTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveRiskTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateRiskTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveRiskTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveRiskTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeRiskTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testSaveSafePolicyWarningDictionary(){
- jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveSafePolicyWarningDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testUpdateSafePolicyWarningDictionary(){
- jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveSafePolicyWarningDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
-
- @Test
- public void testRemoveSafePolicyWarningDictionary(){
- jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.removeSafePolicyWarningDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
- }
- }
+
+ private static Logger logger = FlexLogger.getLogger(SafePolicyControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private HttpServletRequest request = null;
+ private SafePolicyController controller = null;
+ private MockHttpServletResponse response = null;
+ private UserInfo userInfo;
+ private List<String> data;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ commonClassDao = Mockito.mock(CommonClassDao.class);
+
+ data = new ArrayList<>();
+ data.add("Test");
+
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+
+ doNothing().when(commonClassDao).delete(new RiskType());
+ doNothing().when(commonClassDao).save(new RiskType());
+
+ controller = new SafePolicyController();
+ controller.setCommonClassDao(commonClassDao);
+ new DictionaryUtils(commonClassDao);
+ DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
+ mock(DictionaryUtils.class);
+ request = Mockito.mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
+ logger.info("setUp: exit");
+ }
+
+ @Test
+ public void testGetRiskTypeDictionaryByNameEntityData(){
+ when(commonClassDao.getDataByColumn(RiskType.class, "name")).thenReturn(data);
+ controller.getRiskTypeDictionaryByNameEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetRiskTypeDictionaryEntityData(){
+ when(commonClassDao.getData(RiskType.class)).thenReturn(new ArrayList<>());
+ controller.getRiskTypeDictionaryEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetSafePolicyWarningEntityDataByName(){
+ when(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name")).thenReturn(data);
+ controller.getSafePolicyWarningEntityDataByName(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testGetSafePolicyWarningeEntityData(){
+ when(commonClassDao.getData(SafePolicyWarning.class)).thenReturn(new ArrayList<>());
+ controller.getSafePolicyWarningeEntityData(response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ } catch (Exception e) {
+ fail();
+ logger.error(e.getMessage(),e);
+ }
+ }
+
+ @Test
+ public void testSaveRiskTypeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveRiskTypeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateRiskTypeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveRiskTypeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveRiskTypeDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeRiskTypeDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testSaveSafePolicyWarningDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveSafePolicyWarningDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testUpdateSafePolicyWarningDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.saveSafePolicyWarningDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
+
+ @Test
+ public void testRemoveSafePolicyWarningDictionary(){
+ jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ when(request.getReader()).thenReturn(br);
+ controller.removeSafePolicyWarningDictionary(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ }catch(Exception e){
+ logger.error("Exception"+ e);
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java
index 2b1300cc4..da9c4e8f5 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java
@@ -40,28 +40,28 @@ import org.onap.policy.rest.jpa.ConfigurationDataEntity;
import org.onap.policy.rest.jpa.PolicyEntity;
public class ElasticSearchPolicyUpdateTest {
-
- private static Logger logger = FlexLogger.getLogger(ElasticSearchPolicyUpdateTest.class);
- private Object policyContent = "";
- private XACMLPAPTest papTest;
-
- @Before
- public void setUp() throws IOException, ServletException, SQLException{
- // Set the system property temporarily
- System.setProperty("PROPERTY_FILE", "src/test/resources/policyelk.properties");
+
+ private static Logger logger = FlexLogger.getLogger(ElasticSearchPolicyUpdateTest.class);
+ private Object policyContent = "";
+ private XACMLPAPTest papTest;
+
+ @Before
+ public void setUp() throws IOException, ServletException, SQLException{
+ // Set the system property temporarily
+ System.setProperty("PROPERTY_FILE", "src/test/resources/policyelk.properties");
try {
- ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
- } catch (Exception e1) {
- logger.error("Exception Occured"+e1);
- }
+ ClassLoader classLoader = getClass().getClassLoader();
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
+ } catch (Exception e1) {
+ logger.error("Exception Occured"+e1);
+ }
papTest = new XACMLPAPTest();
- papTest.setDBDao();
- }
-
- @Test
- public void testElasticSearchMainFunction() throws SQLException{
- ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity();
+ papTest.setDBDao();
+ }
+
+ @Test
+ public void testElasticSearchMainFunction() throws SQLException{
+ ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity();
configurationEntity.setConfigBody("Sample Test");
configurationEntity.setConfigType("OTHER");
configurationEntity.setConfigurationName("com.Config_SampleTest1206.1.txt");
@@ -70,7 +70,7 @@ public class ElasticSearchPolicyUpdateTest {
configurationEntity.setModifiedDate(new Date());
- PolicyEntity entity = new PolicyEntity();
+ PolicyEntity entity = new PolicyEntity();
entity.setPolicyName("Config_SampleTest.1.xml");
entity.setPolicyData(policyContent.toString());
entity.setScope("com");
@@ -84,14 +84,14 @@ public class ElasticSearchPolicyUpdateTest {
dao.save(configurationEntity);
dao.save(entity);
dao.delete(dao.getEntityItem(PolicyEntity.class, "policyName", "Config_SampleTest.1.xml"));
- ElasticSearchPolicyUpdate.main(null);
- StringBuilder policyDataString = new StringBuilder();
- ElasticSearchPolicyUpdate.constructPolicyData(policyContent, policyDataString);
- assertTrue(policyDataString.toString().contains("onapName"));
- }
-
- @After
- public void reset(){
- System.clearProperty("PROPERTY_FILE");
- }
+ ElasticSearchPolicyUpdate.main(null);
+ StringBuilder policyDataString = new StringBuilder();
+ ElasticSearchPolicyUpdate.constructPolicyData(policyContent, policyDataString);
+ assertTrue(policyDataString.toString().contains("onapName"));
+ }
+
+ @After
+ public void reset(){
+ System.clearProperty("PROPERTY_FILE");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java
index 853d75ce6..2f3d580f7 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java
@@ -39,108 +39,108 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter;
public class ElkConnectorImplTest {
- @Test
- public void isAlphaNumericTest() {
- try {
- Method method = ElkConnectorImpl.class.getDeclaredMethod("isAlphaNumeric", String.class);
- method.setAccessible(true);
- assertTrue((boolean) method.invoke(new ElkConnectorImpl(), "abc123"));
- assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123*"));
- assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123{}"));
- assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123\n"));
- assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123<"));
- assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123:"));
- } catch (Exception e) {
- fail();
- }
- }
-
- @Test
- public void searchTest(){
- JestResult r1=null, r2=null, r3=null, r4=null;
-
- // Should always work if the above test passes and ELK server is up
- try{
- r1 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123");
- } catch (Exception e) {
- // ELK server is down. Don't continue the test
- if(e instanceof IllegalStateException){
- return;
- }
- fail();
- }
-
- // Should always work
- try{
- r2 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The_quick_brown_fox_jumps_over_the_lazy_dog");
- } catch (Exception e) {
- fail();
- }
-
- // Should throw exception
- try{
- r3 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123{}");
- } catch (Exception e) {
- if(! (e instanceof IllegalArgumentException)){
- fail();
- }
- }
-
- // Should throw exception
- try{
- r4 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The quick brown fox jumps over the lazy dog");
- } catch (Exception e) {
- if(! (e instanceof IllegalArgumentException)){
- fail();
- }
- }
-
- assertNotNull(r1);
- assertNotNull(r2);
- assertNull(r3);
- assertNull(r4);
- }
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void testDelete() {
- thrown.expect(NullPointerException.class);
-
- ElkConnectorImpl impl = new ElkConnectorImpl();
- PolicyRestAdapter adapter = new PolicyRestAdapter();
- impl.delete(adapter);
- fail("Expected exception to be thrown");
- }
-
-
- @Test
- public void testPut() throws IOException {
- thrown.expect(NullPointerException.class);
-
- ElkConnectorImpl impl = new ElkConnectorImpl();
- PolicyRestAdapter adapter = new PolicyRestAdapter();
- impl.put(adapter);
- fail("Expected exception to be thrown");
- }
-
- @Test
- public void testUpdate() {
- thrown.expect(IllegalStateException.class);
-
- ElkConnectorImpl impl = new ElkConnectorImpl();
- PolicyRestAdapter adapter = new PolicyRestAdapter();
- impl.update(adapter);
- fail("Expected exception to be thrown");
- }
-
- @Test
- public void testSearchWithFilter() {
- thrown.expect(IllegalStateException.class);
-
- ElkConnectorImpl impl = new ElkConnectorImpl();
- impl.search(PolicyIndexType.config, "search", null);
- fail("Expected exception to be thrown");
- }
+ @Test
+ public void isAlphaNumericTest() {
+ try {
+ Method method = ElkConnectorImpl.class.getDeclaredMethod("isAlphaNumeric", String.class);
+ method.setAccessible(true);
+ assertTrue((boolean) method.invoke(new ElkConnectorImpl(), "abc123"));
+ assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123*"));
+ assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123{}"));
+ assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123\n"));
+ assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123<"));
+ assertFalse((boolean) method.invoke(new ElkConnectorImpl(), "abc123:"));
+ } catch (Exception e) {
+ fail();
+ }
+ }
+
+ @Test
+ public void searchTest(){
+ JestResult r1=null, r2=null, r3=null, r4=null;
+
+ // Should always work if the above test passes and ELK server is up
+ try{
+ r1 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123");
+ } catch (Exception e) {
+ // ELK server is down. Don't continue the test
+ if(e instanceof IllegalStateException){
+ return;
+ }
+ fail();
+ }
+
+ // Should always work
+ try{
+ r2 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The_quick_brown_fox_jumps_over_the_lazy_dog");
+ } catch (Exception e) {
+ fail();
+ }
+
+ // Should throw exception
+ try{
+ r3 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123{}");
+ } catch (Exception e) {
+ if(! (e instanceof IllegalArgumentException)){
+ fail();
+ }
+ }
+
+ // Should throw exception
+ try{
+ r4 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The quick brown fox jumps over the lazy dog");
+ } catch (Exception e) {
+ if(! (e instanceof IllegalArgumentException)){
+ fail();
+ }
+ }
+
+ assertNotNull(r1);
+ assertNotNull(r2);
+ assertNull(r3);
+ assertNull(r4);
+ }
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testDelete() {
+ thrown.expect(NullPointerException.class);
+
+ ElkConnectorImpl impl = new ElkConnectorImpl();
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ impl.delete(adapter);
+ fail("Expected exception to be thrown");
+ }
+
+
+ @Test
+ public void testPut() throws IOException {
+ thrown.expect(NullPointerException.class);
+
+ ElkConnectorImpl impl = new ElkConnectorImpl();
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ impl.put(adapter);
+ fail("Expected exception to be thrown");
+ }
+
+ @Test
+ public void testUpdate() {
+ thrown.expect(IllegalStateException.class);
+
+ ElkConnectorImpl impl = new ElkConnectorImpl();
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ impl.update(adapter);
+ fail("Expected exception to be thrown");
+ }
+
+ @Test
+ public void testSearchWithFilter() {
+ thrown.expect(IllegalStateException.class);
+
+ ElkConnectorImpl impl = new ElkConnectorImpl();
+ impl.search(PolicyIndexType.config, "search", null);
+ fail("Expected exception to be thrown");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java
index 68f1daa0b..0b8c86c1e 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java
@@ -25,20 +25,20 @@ import org.junit.Test;
import org.onap.policy.pap.xacml.rest.elk.client.Pair;
public class PairTest {
- @Test
- public void testPair() {
- String testLeft = "left";
- String testRight = "right";
-
- // Test constructor
- Pair<String, String> pair = new Pair<String, String>(testLeft, testRight);
- assertEquals(pair.left(), testLeft);
- assertEquals(pair.right(), testRight);
-
- // Test setters
- pair.left(testRight);
- pair.right(testLeft);
- assertEquals(pair.left(), testRight);
- assertEquals(pair.right(), testLeft);
- }
+ @Test
+ public void testPair() {
+ String testLeft = "left";
+ String testRight = "right";
+
+ // Test constructor
+ Pair<String, String> pair = new Pair<String, String>(testLeft, testRight);
+ assertEquals(pair.left(), testLeft);
+ assertEquals(pair.right(), testRight);
+
+ // Test setters
+ pair.left(testRight);
+ pair.right(testLeft);
+ assertEquals(pair.left(), testRight);
+ assertEquals(pair.right(), testLeft);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java
index a84e4a0cd..76c0ce788 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java
@@ -30,159 +30,159 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.adapter.YAMLParams;
public class PolicyElasticDataTest {
- @Test
- public void testSetAndGet() {
- String testKey = "testKey";
- String testVal = "testVal";
- LinkedHashMap<String, String> testMap = new LinkedHashMap<String, String>();
- testMap.put(testKey, testVal);
- ArrayList<Object> testArray = new ArrayList<Object>();
- testArray.add(testVal);
- List<String> testList = new ArrayList<String>();
- testList.add(testVal);
- List<Object> testObjectList = new ArrayList<Object>();
- testObjectList.add(testVal);
- YAMLParams testYaml = new YAMLParams();
-
- PolicyRestAdapter adapter = new PolicyRestAdapter();
- adapter.setConfigPolicyType(testVal);
-
- PolicyElasticData data = new PolicyElasticData(adapter);
- data.setScope(testVal);
- assertEquals(data.getScope(), testVal);
- data.setPolicyType(testVal);
- assertEquals(data.getPolicyType(), testVal);
- data.setConfigPolicyType(testVal);
- assertEquals(data.getConfigPolicyType(), testVal);
- data.setConfigBodyData(testVal);
- assertEquals(data.getConfigBodyData(), testVal);
- data.setPolicyName(testVal);
- assertEquals(data.getPolicyName(), testVal);
- data.setPolicyDescription(testVal);
- assertEquals(data.getPolicyDescription(), testVal);
- data.setOnapName(testVal);
- assertEquals(data.getOnapName(), testVal);
- data.setConfigName(testVal);
- assertEquals(data.getConfigName(), testVal);
- data.setConfigType(testVal);
- assertEquals(data.getConfigType(), testVal);
- data.setJsonBody(testVal);
- assertEquals(data.getJsonBody(), testVal);
- data.setServiceTypePolicyName(testMap);
- assertEquals(data.getServiceTypePolicyName(), testMap);
- data.setVerticaMetrics(testMap);
- assertEquals(data.getVerticaMetrics(), testMap);
- data.setDescription(testMap);
- assertEquals(data.getDescription(), testMap);
- data.setAttributeFields(testMap);
- assertEquals(data.getAttributeFields(), testMap);
- data.setPolicyScope(testVal);
- assertEquals(data.getPolicyScope(), testVal);
- data.setProviderComboBox(testVal);
- assertEquals(data.getProviderComboBox(), testVal);
- data.setRiskType(testVal);
- assertEquals(data.getRiskType(), testVal);
- data.setRiskLevel(testVal);
- assertEquals(data.getRiskLevel(), testVal);
- data.setGuard(testVal);
- assertEquals(data.getGuard(), testVal);
- data.setTtlDate(testVal);
- assertEquals(data.getTtlDate(), testVal);
- data.setMatching(testMap);
- assertEquals(data.getMatching(), testMap);
- data.setTriggerSignatures(testArray);
- assertEquals(data.getTriggerSignatures(), testArray);
- data.setSymptomSignatures(testArray);
- assertEquals(data.getSymptomSignatures(), testArray);
- data.setLogicalConnector(testVal);
- assertEquals(data.getLogicalConnector(), testVal);
- data.setPolicyStatus(testVal);
- assertEquals(data.getPolicyStatus(), testVal);
- data.setGocServerScope(testVal);
- assertEquals(data.getGocServerScope(), testVal);
- data.setSupressionType(testVal);
- assertEquals(data.getSupressionType(), testVal);
- data.setServiceType(testVal);
- assertEquals(data.getServiceType(),testVal);
- data.setUuid(testVal);
- assertEquals(data.getUuid(), testVal);
- data.setLocation(testVal);
- assertEquals(data.getLocation(), testVal);
- data.setPriority(testVal);
- assertEquals(data.getPriority(), testVal);
- data.setMsLocation(testVal);
- assertEquals(data.getMsLocation(),testVal);
- data.setRuleName(testVal);
- assertEquals(data.getRuleName(), testVal);
- data.setBrmsParamBody(testMap);
- assertEquals(data.getBrmsParamBody(), testMap);
- data.setBrmsController(testVal);
- assertEquals(data.getBrmsController(), testVal);
- data.setBrmsDependency(testList);
- assertEquals(data.getBrmsDependency(), testList);
- data.setRuleData(testMap);
- assertEquals(data.getRuleData(), testMap);
- data.setRuleListData(testMap);
- assertEquals(data.getRuleListData(), testMap);
- data.setDrlRuleAndUIParams(testMap);
- assertEquals(data.getDrlRuleAndUIParams(), testMap);
- data.setClearTimeOut(testVal);
- assertEquals(data.getClearTimeOut(), testVal);
- data.setTrapMaxAge(testVal);
- assertEquals(data.getTrapMaxAge(), testVal);
- data.setVerificationclearTimeOut(testVal);
- assertEquals(data.getVerificationclearTimeOut(), testVal);
- data.setDynamicLayoutMap(testMap);
- assertEquals(data.getDynamicLayoutMap(), testMap);
- data.setFwPolicyType(testVal);
- assertEquals(data.getFwPolicyType(), testVal);
- data.setFwattributes(testArray);
- assertEquals(data.getFwattributes(), testArray);
- data.setParentForChild(testVal);
- assertEquals(data.getParentForChild(), testVal);
- data.setSecurityZone(testVal);
- assertEquals(data.getSecurityZone(), testVal);
- data.setRuleCombiningAlgId(testVal);
- assertEquals(data.getRuleCombiningAlgId(), testVal);
- data.setDynamicFieldConfigAttributes(testMap);
- assertEquals(data.getDynamicFieldConfigAttributes(), testMap);
- data.setDynamicSettingsMap(testMap);
- assertEquals(data.getDynamicSettingsMap(), testMap);
- data.setDropDownMap(testMap);
- assertEquals(data.getDropDownMap(), testMap);
- data.setActionPerformer(testVal);
- assertEquals(data.getActionPerformer(), testVal);
- data.setActionAttribute(testVal);
- assertEquals(data.getActionAttribute(), testVal);
- data.setDynamicRuleAlgorithmLabels(testList);
- assertEquals(data.getDynamicRuleAlgorithmLabels(), testList);
- data.setDynamicRuleAlgorithmCombo(testList);
- assertEquals(data.getDynamicRuleAlgorithmCombo(), testList);
- data.setDynamicRuleAlgorithmField1(testList);
- assertEquals(data.getDynamicRuleAlgorithmField1(), testList);
- data.setDynamicRuleAlgorithmField2(testList);
- assertEquals(data.getDynamicRuleAlgorithmField2(), testList);
- data.setDynamicVariableList(testObjectList);
- assertEquals(data.getDynamicVariableList(), testObjectList);
- data.setDataTypeList(testList);
- assertEquals(data.getDataTypeList(), testList);
- data.setActionAttributeValue(testVal);
- assertEquals(data.getActionAttributeValue(), testVal);
- data.setRuleProvider(testVal);
- assertEquals(data.getRuleProvider(), testVal);
- data.setActionBody(testVal);
- assertEquals(data.getActionBody(), testVal);
- data.setActionDictHeader(testVal);
- assertEquals(data.getActionDictHeader(), testVal);
- data.setActionDictType(testVal);
- assertEquals(data.getActionDictType(), testVal);
- data.setActionDictUrl(testVal);
- assertEquals(data.getActionDictUrl(), testVal);
- data.setActionDictMethod(testVal);
- assertEquals(data.getActionDictMethod(), testVal);
- data.setYamlparams(testYaml);
- assertEquals(data.getYamlparams(), testYaml);
- data.setJsonBodyData(testVal);
- assertEquals(data.getJsonBodyData(), testVal);
- }
+ @Test
+ public void testSetAndGet() {
+ String testKey = "testKey";
+ String testVal = "testVal";
+ LinkedHashMap<String, String> testMap = new LinkedHashMap<String, String>();
+ testMap.put(testKey, testVal);
+ ArrayList<Object> testArray = new ArrayList<Object>();
+ testArray.add(testVal);
+ List<String> testList = new ArrayList<String>();
+ testList.add(testVal);
+ List<Object> testObjectList = new ArrayList<Object>();
+ testObjectList.add(testVal);
+ YAMLParams testYaml = new YAMLParams();
+
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setConfigPolicyType(testVal);
+
+ PolicyElasticData data = new PolicyElasticData(adapter);
+ data.setScope(testVal);
+ assertEquals(data.getScope(), testVal);
+ data.setPolicyType(testVal);
+ assertEquals(data.getPolicyType(), testVal);
+ data.setConfigPolicyType(testVal);
+ assertEquals(data.getConfigPolicyType(), testVal);
+ data.setConfigBodyData(testVal);
+ assertEquals(data.getConfigBodyData(), testVal);
+ data.setPolicyName(testVal);
+ assertEquals(data.getPolicyName(), testVal);
+ data.setPolicyDescription(testVal);
+ assertEquals(data.getPolicyDescription(), testVal);
+ data.setOnapName(testVal);
+ assertEquals(data.getOnapName(), testVal);
+ data.setConfigName(testVal);
+ assertEquals(data.getConfigName(), testVal);
+ data.setConfigType(testVal);
+ assertEquals(data.getConfigType(), testVal);
+ data.setJsonBody(testVal);
+ assertEquals(data.getJsonBody(), testVal);
+ data.setServiceTypePolicyName(testMap);
+ assertEquals(data.getServiceTypePolicyName(), testMap);
+ data.setVerticaMetrics(testMap);
+ assertEquals(data.getVerticaMetrics(), testMap);
+ data.setDescription(testMap);
+ assertEquals(data.getDescription(), testMap);
+ data.setAttributeFields(testMap);
+ assertEquals(data.getAttributeFields(), testMap);
+ data.setPolicyScope(testVal);
+ assertEquals(data.getPolicyScope(), testVal);
+ data.setProviderComboBox(testVal);
+ assertEquals(data.getProviderComboBox(), testVal);
+ data.setRiskType(testVal);
+ assertEquals(data.getRiskType(), testVal);
+ data.setRiskLevel(testVal);
+ assertEquals(data.getRiskLevel(), testVal);
+ data.setGuard(testVal);
+ assertEquals(data.getGuard(), testVal);
+ data.setTtlDate(testVal);
+ assertEquals(data.getTtlDate(), testVal);
+ data.setMatching(testMap);
+ assertEquals(data.getMatching(), testMap);
+ data.setTriggerSignatures(testArray);
+ assertEquals(data.getTriggerSignatures(), testArray);
+ data.setSymptomSignatures(testArray);
+ assertEquals(data.getSymptomSignatures(), testArray);
+ data.setLogicalConnector(testVal);
+ assertEquals(data.getLogicalConnector(), testVal);
+ data.setPolicyStatus(testVal);
+ assertEquals(data.getPolicyStatus(), testVal);
+ data.setGocServerScope(testVal);
+ assertEquals(data.getGocServerScope(), testVal);
+ data.setSupressionType(testVal);
+ assertEquals(data.getSupressionType(), testVal);
+ data.setServiceType(testVal);
+ assertEquals(data.getServiceType(),testVal);
+ data.setUuid(testVal);
+ assertEquals(data.getUuid(), testVal);
+ data.setLocation(testVal);
+ assertEquals(data.getLocation(), testVal);
+ data.setPriority(testVal);
+ assertEquals(data.getPriority(), testVal);
+ data.setMsLocation(testVal);
+ assertEquals(data.getMsLocation(),testVal);
+ data.setRuleName(testVal);
+ assertEquals(data.getRuleName(), testVal);
+ data.setBrmsParamBody(testMap);
+ assertEquals(data.getBrmsParamBody(), testMap);
+ data.setBrmsController(testVal);
+ assertEquals(data.getBrmsController(), testVal);
+ data.setBrmsDependency(testList);
+ assertEquals(data.getBrmsDependency(), testList);
+ data.setRuleData(testMap);
+ assertEquals(data.getRuleData(), testMap);
+ data.setRuleListData(testMap);
+ assertEquals(data.getRuleListData(), testMap);
+ data.setDrlRuleAndUIParams(testMap);
+ assertEquals(data.getDrlRuleAndUIParams(), testMap);
+ data.setClearTimeOut(testVal);
+ assertEquals(data.getClearTimeOut(), testVal);
+ data.setTrapMaxAge(testVal);
+ assertEquals(data.getTrapMaxAge(), testVal);
+ data.setVerificationclearTimeOut(testVal);
+ assertEquals(data.getVerificationclearTimeOut(), testVal);
+ data.setDynamicLayoutMap(testMap);
+ assertEquals(data.getDynamicLayoutMap(), testMap);
+ data.setFwPolicyType(testVal);
+ assertEquals(data.getFwPolicyType(), testVal);
+ data.setFwattributes(testArray);
+ assertEquals(data.getFwattributes(), testArray);
+ data.setParentForChild(testVal);
+ assertEquals(data.getParentForChild(), testVal);
+ data.setSecurityZone(testVal);
+ assertEquals(data.getSecurityZone(), testVal);
+ data.setRuleCombiningAlgId(testVal);
+ assertEquals(data.getRuleCombiningAlgId(), testVal);
+ data.setDynamicFieldConfigAttributes(testMap);
+ assertEquals(data.getDynamicFieldConfigAttributes(), testMap);
+ data.setDynamicSettingsMap(testMap);
+ assertEquals(data.getDynamicSettingsMap(), testMap);
+ data.setDropDownMap(testMap);
+ assertEquals(data.getDropDownMap(), testMap);
+ data.setActionPerformer(testVal);
+ assertEquals(data.getActionPerformer(), testVal);
+ data.setActionAttribute(testVal);
+ assertEquals(data.getActionAttribute(), testVal);
+ data.setDynamicRuleAlgorithmLabels(testList);
+ assertEquals(data.getDynamicRuleAlgorithmLabels(), testList);
+ data.setDynamicRuleAlgorithmCombo(testList);
+ assertEquals(data.getDynamicRuleAlgorithmCombo(), testList);
+ data.setDynamicRuleAlgorithmField1(testList);
+ assertEquals(data.getDynamicRuleAlgorithmField1(), testList);
+ data.setDynamicRuleAlgorithmField2(testList);
+ assertEquals(data.getDynamicRuleAlgorithmField2(), testList);
+ data.setDynamicVariableList(testObjectList);
+ assertEquals(data.getDynamicVariableList(), testObjectList);
+ data.setDataTypeList(testList);
+ assertEquals(data.getDataTypeList(), testList);
+ data.setActionAttributeValue(testVal);
+ assertEquals(data.getActionAttributeValue(), testVal);
+ data.setRuleProvider(testVal);
+ assertEquals(data.getRuleProvider(), testVal);
+ data.setActionBody(testVal);
+ assertEquals(data.getActionBody(), testVal);
+ data.setActionDictHeader(testVal);
+ assertEquals(data.getActionDictHeader(), testVal);
+ data.setActionDictType(testVal);
+ assertEquals(data.getActionDictType(), testVal);
+ data.setActionDictUrl(testVal);
+ assertEquals(data.getActionDictUrl(), testVal);
+ data.setActionDictMethod(testVal);
+ assertEquals(data.getActionDictMethod(), testVal);
+ data.setYamlparams(testYaml);
+ assertEquals(data.getYamlparams(), testYaml);
+ data.setJsonBodyData(testVal);
+ assertEquals(data.getJsonBodyData(), testVal);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java
index ec86996c1..bdbe1441d 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java
@@ -36,46 +36,46 @@ import org.mockito.Mockito;
import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
public class PolicyElasticSearchControllerTest {
-
- private PolicyElasticSearchController conroller;
- private HttpServletRequest request = null;
- private HttpServletResponse response = null;
-
- @Before
- public void setup(){
- conroller = new PolicyElasticSearchController();
- request = Mockito.mock(HttpServletRequest.class);
- response = Mockito.mock(HttpServletResponse.class);
- }
-
- @Test
- public void testSearchDictionary(){
- List<String> jsonString = new ArrayList<>();
- jsonString.add("{\"type\":\"attribute\",\"data\":{\"xacmlId\":\"Test\"}}");
- jsonString.add("{\"type\":\"onapName\",\"data\":{\"onapName\":\"Test\"}}");
- jsonString.add("{\"type\":\"actionPolicy\",\"data\":{\"attributeName\":\"Test\"}}");
- jsonString.add("{\"type\":\"brmsParam\",\"data\":{\"ruleName\":\"Test\"}}");
- jsonString.add("{\"type\":\"pepOptions\",\"data\":{\"pepName\":\"Test\"}}");
- jsonString.add("{\"type\":\"clSite\",\"data\":{\"siteName\":\"Test\"}}");
- jsonString.add("{\"type\":\"clService\",\"data\":{\"serviceName\":\"Test\"}}");
- jsonString.add("{\"type\":\"clVarbind\",\"data\":{\"varbindName\":\"Test\"}}");
- jsonString.add("{\"type\":\"clVnf\",\"data\":{\"vnftype\":\"Test\"}}");
- jsonString.add("{\"type\":\"clVSCL\",\"data\":{\"vsclaction\":\"Test\"}}");
- jsonString.add("{\"type\":\"decision\",\"data\":{\"xacmlId\":\"Test\"}}");
- jsonString.add("{\"type\":\"fwTerm\",\"data\":{\"termName\":\"Test\"}}");
- jsonString.add("{\"type\":\"msDCAEUUID\",\"data\":{\"name\":\"Test\"}}");
- jsonString.add("{\"type\":\"msLocation\",\"data\":{\"name\":\"Test\"}}");
- jsonString.add("{\"type\":\"msModels\",\"data\":{\"modelName\":\"Test\"}}");
- jsonString.add("{\"type\":\"psGroupPolicy\",\"data\":{\"name\":\"Test\"}}");
- jsonString.add("{\"type\":\"safeRisk\",\"data\":{\"name\":\"Test\"}}");
- jsonString.add("{\"type\":\"safePolicyWarning\",\"data\":{\"name\":\"Test\"}}");
- for(int i = 0; i < jsonString.size(); i++){
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)))) {
- when(request.getReader()).thenReturn(br);
- conroller.searchDictionary(request, response);
- } catch (Exception e) {
- assertEquals(NullPointerException.class, e.getClass());
- }
- }
- }
+
+ private PolicyElasticSearchController conroller;
+ private HttpServletRequest request = null;
+ private HttpServletResponse response = null;
+
+ @Before
+ public void setup(){
+ conroller = new PolicyElasticSearchController();
+ request = Mockito.mock(HttpServletRequest.class);
+ response = Mockito.mock(HttpServletResponse.class);
+ }
+
+ @Test
+ public void testSearchDictionary(){
+ List<String> jsonString = new ArrayList<>();
+ jsonString.add("{\"type\":\"attribute\",\"data\":{\"xacmlId\":\"Test\"}}");
+ jsonString.add("{\"type\":\"onapName\",\"data\":{\"onapName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"actionPolicy\",\"data\":{\"attributeName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"brmsParam\",\"data\":{\"ruleName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"pepOptions\",\"data\":{\"pepName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"clSite\",\"data\":{\"siteName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"clService\",\"data\":{\"serviceName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"clVarbind\",\"data\":{\"varbindName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"clVnf\",\"data\":{\"vnftype\":\"Test\"}}");
+ jsonString.add("{\"type\":\"clVSCL\",\"data\":{\"vsclaction\":\"Test\"}}");
+ jsonString.add("{\"type\":\"decision\",\"data\":{\"xacmlId\":\"Test\"}}");
+ jsonString.add("{\"type\":\"fwTerm\",\"data\":{\"termName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"msDCAEUUID\",\"data\":{\"name\":\"Test\"}}");
+ jsonString.add("{\"type\":\"msLocation\",\"data\":{\"name\":\"Test\"}}");
+ jsonString.add("{\"type\":\"msModels\",\"data\":{\"modelName\":\"Test\"}}");
+ jsonString.add("{\"type\":\"psGroupPolicy\",\"data\":{\"name\":\"Test\"}}");
+ jsonString.add("{\"type\":\"safeRisk\",\"data\":{\"name\":\"Test\"}}");
+ jsonString.add("{\"type\":\"safePolicyWarning\",\"data\":{\"name\":\"Test\"}}");
+ for(int i = 0; i < jsonString.size(); i++){
+ try(BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)))) {
+ when(request.getReader()).thenReturn(br);
+ conroller.searchDictionary(request, response);
+ } catch (Exception e) {
+ assertEquals(NullPointerException.class, e.getClass());
+ }
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java
index b648a318a..7df295382 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java
@@ -25,19 +25,19 @@ import org.junit.Test;
import org.onap.policy.pap.xacml.rest.elk.client.PolicyLocator;
public class PolicyLocatorTest {
- @Test
- public void testLocator() {
- String policyType = "type";
- String policyName = "name";
+ @Test
+ public void testLocator() {
+ String policyType = "type";
+ String policyName = "name";
String owner = "owner";
String scope = "scope";
String policyId = "id";
String version = "1.0";
- String testString = "[owner|scope|type|name|id|v1.0|]";
+ String testString = "[owner|scope|type|name|id|v1.0|]";
- PolicyLocator locator = new PolicyLocator(policyType, policyName, owner,
- scope, policyId, version);
- String locatorString = locator.toString();
- assertEquals(locatorString, testString);
- }
+ PolicyLocator locator = new PolicyLocator(policyType, policyName, owner,
+ scope, policyId, version);
+ String locatorString = locator.toString();
+ assertEquals(locatorString, testString);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
index 3941593e9..84f36aa63 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
@@ -47,68 +47,68 @@ import javax.persistence.EntityManager;
@RunWith(PowerMockRunner.class)
public class DeleteHandlerTest {
- @Test
- public void testGets() {
- DeleteHandler handler = new DeleteHandler();
- assertNotNull(handler);
- assertEquals(handler.preSafetyCheck(null), true);
- assertNull(handler.getDeletedGroup());
- }
-
- @Test
- public void testGetInstance() {
- DeleteHandler handler = DeleteHandler.getInstance();
- assertNotNull(handler);
- }
-
- @PrepareForTest({DeleteHandler.class, XACMLPapServlet.class})
- @Test
- public void testDeletes() throws Exception {
- // Mock request
- DeleteHandler handler = new DeleteHandler();
- MockHttpServletRequest request = new MockHttpServletRequest();
- request.setBodyContent("{\n\"PAPPolicyType\": \"StdPAPPolicy\"\n}\n");
-
- // Mock servlet
- PAPPolicyEngine engine = Mockito.mock(StdEngine.class);
- PowerMockito.mockStatic(XACMLPapServlet.class);
- when(XACMLPapServlet.getPAPEngine()).thenReturn(engine);
- when(engine.getGroup(any())).thenReturn(null);
-
- // Mock elastic search
- PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class);
- PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller);
-
- // Mock entity manager
- EntityManager em = Mockito.mock(EntityManager.class);
-
- // Test deletion from PAP
- MockHttpServletResponse response = new MockHttpServletResponse();
- try {
- handler.doAPIDeleteFromPAP(request, response);
- }
- catch (Exception ex) {
- fail("Not expecting an exception: " + ex);
- }
-
- // Test deletion from PDP
- ONAPLoggingContext loggingContext = Mockito.mock(ONAPLoggingContext.class);
- try {
- handler.doAPIDeleteFromPDP(request, response, loggingContext);
- }
- catch (Exception ex) {
- fail("Not expecting an exception: " + ex);
- }
-
- // Test delete entity
- PolicyEntity policyEntity = new PolicyEntity();
- policyEntity.setPolicyName("testVal");
- String result = DeleteHandler.deletePolicyEntityData(em, policyEntity);
- assertEquals(result, "success");
-
- // Test check entity
- Connection con = null;
- List<?> peResult = Collections.emptyList();
- assertEquals(DeleteHandler.checkPolicyGroupEntity(con, peResult), false);
- }
+ @Test
+ public void testGets() {
+ DeleteHandler handler = new DeleteHandler();
+ assertNotNull(handler);
+ assertEquals(handler.preSafetyCheck(null), true);
+ assertNull(handler.getDeletedGroup());
+ }
+
+ @Test
+ public void testGetInstance() {
+ DeleteHandler handler = DeleteHandler.getInstance();
+ assertNotNull(handler);
+ }
+
+ @PrepareForTest({DeleteHandler.class, XACMLPapServlet.class})
+ @Test
+ public void testDeletes() throws Exception {
+ // Mock request
+ DeleteHandler handler = new DeleteHandler();
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setBodyContent("{\n\"PAPPolicyType\": \"StdPAPPolicy\"\n}\n");
+
+ // Mock servlet
+ PAPPolicyEngine engine = Mockito.mock(StdEngine.class);
+ PowerMockito.mockStatic(XACMLPapServlet.class);
+ when(XACMLPapServlet.getPAPEngine()).thenReturn(engine);
+ when(engine.getGroup(any())).thenReturn(null);
+
+ // Mock elastic search
+ PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class);
+ PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller);
+
+ // Mock entity manager
+ EntityManager em = Mockito.mock(EntityManager.class);
+
+ // Test deletion from PAP
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ try {
+ handler.doAPIDeleteFromPAP(request, response);
+ }
+ catch (Exception ex) {
+ fail("Not expecting an exception: " + ex);
+ }
+
+ // Test deletion from PDP
+ ONAPLoggingContext loggingContext = Mockito.mock(ONAPLoggingContext.class);
+ try {
+ handler.doAPIDeleteFromPDP(request, response, loggingContext);
+ }
+ catch (Exception ex) {
+ fail("Not expecting an exception: " + ex);
+ }
+
+ // Test delete entity
+ PolicyEntity policyEntity = new PolicyEntity();
+ policyEntity.setPolicyName("testVal");
+ String result = DeleteHandler.deletePolicyEntityData(em, policyEntity);
+ assertEquals(result, "success");
+
+ // Test check entity
+ Connection con = null;
+ List<?> peResult = Collections.emptyList();
+ assertEquals(DeleteHandler.checkPolicyGroupEntity(con, peResult), false);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java
index 81fe8a7ab..6971ed706 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java
@@ -42,44 +42,44 @@ import javax.persistence.Query;
@RunWith(PowerMockRunner.class)
public class PushPolicyHandlerTest {
- @PrepareForTest({XACMLPapServlet.class})
- @Test
- public void testGetsAndChecks() {
- // Mock servlet, entity mgr, transaction, and query
- EntityManager em = Mockito.mock(EntityManager.class);
- EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class);
- PowerMockito.mockStatic(XACMLPapServlet.class);
- PowerMockito.when(XACMLPapServlet.getEmf()).thenReturn(emf);
- Mockito.when(emf.createEntityManager()).thenReturn(em);
- EntityTransaction transaction = Mockito.mock(EntityTransaction.class);
- Mockito.when(em.getTransaction()).thenReturn(transaction);
- Query query = Mockito.mock(Query.class);
- Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
-
- // Test constructor
- PushPolicyHandler handler = new PushPolicyHandler();
- assertNotNull(handler);
+ @PrepareForTest({XACMLPapServlet.class})
+ @Test
+ public void testGetsAndChecks() {
+ // Mock servlet, entity mgr, transaction, and query
+ EntityManager em = Mockito.mock(EntityManager.class);
+ EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class);
+ PowerMockito.mockStatic(XACMLPapServlet.class);
+ PowerMockito.when(XACMLPapServlet.getEmf()).thenReturn(emf);
+ Mockito.when(emf.createEntityManager()).thenReturn(em);
+ EntityTransaction transaction = Mockito.mock(EntityTransaction.class);
+ Mockito.when(em.getTransaction()).thenReturn(transaction);
+ Query query = Mockito.mock(Query.class);
+ Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
- // Test gets
- MockHttpServletRequest request = new MockHttpServletRequest();
- MockHttpServletResponse response = new MockHttpServletResponse();
- handler.getActiveVersion(request, response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
- request.setupAddParameter("gitPath", "testPath");
- handler.getSelectedURI(request, response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
-
- // Test check
- StdPDPPolicy policy = new StdPDPPolicy();
- OnapPDPGroup onapPolicy = new StdPDPGroup();
- String configHome = "testVal";
- assertEquals(handler.preSafetyCheck(policy, configHome), true);
- assertEquals(handler.preSafetyCheck(onapPolicy, configHome), true);
- }
-
- @Test
- public void testGetInstance() {
- PushPolicyHandler handler = PushPolicyHandler.getInstance();
- assertNotNull(handler);
- }
+ // Test constructor
+ PushPolicyHandler handler = new PushPolicyHandler();
+ assertNotNull(handler);
+
+ // Test gets
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ handler.getActiveVersion(request, response);
+ assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+ request.setupAddParameter("gitPath", "testPath");
+ handler.getSelectedURI(request, response);
+ assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+
+ // Test check
+ StdPDPPolicy policy = new StdPDPPolicy();
+ OnapPDPGroup onapPolicy = new StdPDPGroup();
+ String configHome = "testVal";
+ assertEquals(handler.preSafetyCheck(policy, configHome), true);
+ assertEquals(handler.preSafetyCheck(onapPolicy, configHome), true);
+ }
+
+ @Test
+ public void testGetInstance() {
+ PushPolicyHandler handler = PushPolicyHandler.getInstance();
+ assertNotNull(handler);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java
index 8b4c73abd..e7de8d0c4 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java
@@ -45,18 +45,18 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import java.util.Properties;
public class PolicyEntityTest {
-
- private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class);
-
+
+ private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class);
+
@Test
public void testAllOps(){
- Properties properties = new Properties();
- properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver");
- properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest");
- properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa");
- properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "");
- EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", properties);
- EntityManager em = emf.createEntityManager();
+ Properties properties = new Properties();
+ properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver");
+ properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest");
+ properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa");
+ properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "");
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", properties);
+ EntityManager em = emf.createEntityManager();
// Start a transaction
EntityTransaction et = em.getTransaction();
@@ -101,19 +101,19 @@ public class PolicyEntityTest {
logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********"
- + "\npolicyId1 = " + policyId1
- + "\npolicyName1 = " + policyName1
- + "\nversion1 = " + version1
- + "\npolicyData1 = " + policyData1
- + "\nconfigDataStr1 = " + configDataStr1
- + "\nactionBodyStr1 = " + actionBodyStr1
- + "\nscope = " + p1.getScope()
- + "\ncreatedBy1 = " + createdBy1
- + "\ncreatedDateStr1 = " + createdDateStr1
- + "\ndescription = " + description
- + "\nmodifiedBy1 = " + modifiedBy1
- + "\nmodifiedDateStr1 = " + modifiedDateStr1
- + "\ndeleted = " + p1.isDeleted());
+ + "\npolicyId1 = " + policyId1
+ + "\npolicyName1 = " + policyName1
+ + "\nversion1 = " + version1
+ + "\npolicyData1 = " + policyData1
+ + "\nconfigDataStr1 = " + configDataStr1
+ + "\nactionBodyStr1 = " + actionBodyStr1
+ + "\nscope = " + p1.getScope()
+ + "\ncreatedBy1 = " + createdBy1
+ + "\ncreatedDateStr1 = " + createdDateStr1
+ + "\ndescription = " + description
+ + "\nmodifiedBy1 = " + modifiedBy1
+ + "\nmodifiedDateStr1 = " + modifiedDateStr1
+ + "\ndeleted = " + p1.isDeleted());
//Set policyID
p1.setPolicyName("testPID2");
@@ -171,19 +171,19 @@ public class PolicyEntityTest {
modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null");
logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after persist*********"
- + "\npolicyId1 = " + policyId1
- + "\npolicyName1 = " + policyName1
- + "\nversion1 = " + version1
- + "\npolicyData1 = " + policyData1
- + "\nconfigDataStr1 = " + configDataStr1
- + "\nactionBodyStr1 = " + actionBodyStr1
- + "\nscopeId = " + p1.getScope()
- + "\ncreatedBy1 = " + createdBy1
- + "\ncreatedDateStr1 = " + createdDateStr1
- + "\ndescription = " + description
- + "\nmodifiedBy1 = " + modifiedBy1
- + "\nmodifiedDateStr1 = " + modifiedDateStr1
- + "\ndeleted = " + p1.isDeleted());
+ + "\npolicyId1 = " + policyId1
+ + "\npolicyName1 = " + policyName1
+ + "\nversion1 = " + version1
+ + "\npolicyData1 = " + policyData1
+ + "\nconfigDataStr1 = " + configDataStr1
+ + "\nactionBodyStr1 = " + actionBodyStr1
+ + "\nscopeId = " + p1.getScope()
+ + "\ncreatedBy1 = " + createdBy1
+ + "\ncreatedDateStr1 = " + createdDateStr1
+ + "\ndescription = " + description
+ + "\nmodifiedBy1 = " + modifiedBy1
+ + "\nmodifiedDateStr1 = " + modifiedDateStr1
+ + "\ndeleted = " + p1.isDeleted());
//Now lets fully configure the configurationData and actionBody
@@ -193,7 +193,7 @@ public class PolicyEntityTest {
ActionBodyEntity a1 = new ActionBodyEntity();
//persist the configuration Data
- em.persist(c1);
+ em.persist(c1);
c1.setConfigType("OTHER");
@@ -241,28 +241,28 @@ public class PolicyEntityTest {
Date cdModifiedDate = c1.getModifiedDate();
logger.debug("\n\n********PolicyEntityTest: Local Configuration object after setting values *********"
- + "\nconfigurationDataId = " + configurationDataId
- + "\ncdVersion = " + cdVersion
- + "\ncdConfigType = " + cdConfigType
- + "\ncdConfigBody = " + cdConfigBody
- + "\ncdCreatedBy = " + cdCreatedBy
- + "\ncdCreatedDate = " + cdCreatedDate
- + "\ncdDescription = " + cdDescription
- + "\ncdModifiedBy = " + cdModifiedBy
- + "\ncdModifiedDate = " + cdModifiedDate
- + "\ndeleted = " + c1.isDeleted());
+ + "\nconfigurationDataId = " + configurationDataId
+ + "\ncdVersion = " + cdVersion
+ + "\ncdConfigType = " + cdConfigType
+ + "\ncdConfigBody = " + cdConfigBody
+ + "\ncdCreatedBy = " + cdCreatedBy
+ + "\ncdCreatedDate = " + cdCreatedDate
+ + "\ncdDescription = " + cdDescription
+ + "\ncdModifiedBy = " + cdModifiedBy
+ + "\ncdModifiedDate = " + cdModifiedDate
+ + "\ndeleted = " + c1.isDeleted());
logger.debug("\n\n********PolicyEntityTest: Local Action Body object after setting values *********"
- + "\nactionBodyId = " + a1.getActionBodyId()
- + "\nactionBodyVersion = " + a1.getVersion()
- + "\nactionBody = " + a1.getActionBody()
- + "\nactionBodyCeatedBy = " + a1.getCreatedBy()
- + "\nactionBodyCreatedDate = " + a1.getCreatedDate()
- + "\nactionBodyModifiedBy = " + a1.getModifiedBy()
- + "\nactionBodyModifiedDate = " + a1.getModifiedDate()
- + "\nactionBodyDeleted = " + a1.isDeleted());
+ + "\nactionBodyId = " + a1.getActionBodyId()
+ + "\nactionBodyVersion = " + a1.getVersion()
+ + "\nactionBody = " + a1.getActionBody()
+ + "\nactionBodyCeatedBy = " + a1.getCreatedBy()
+ + "\nactionBodyCreatedDate = " + a1.getCreatedDate()
+ + "\nactionBodyModifiedBy = " + a1.getModifiedBy()
+ + "\nactionBodyModifiedDate = " + a1.getModifiedDate()
+ + "\nactionBodyDeleted = " + a1.isDeleted());
p1.setScope("mckiou.kevin.kim");
@@ -282,10 +282,10 @@ public class PolicyEntityTest {
List psList = queryscope.getResultList();
PolicyEntity px = null;
if(!psList.isEmpty()){
- //ignores multiple results
- px = (PolicyEntity) psList.get(0);
+ //ignores multiple results
+ px = (PolicyEntity) psList.get(0);
}else{
- fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found");
+ fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found");
}
//The scope object on the retrieved policy object should be same as the one we used to find it
@@ -295,29 +295,29 @@ public class PolicyEntityTest {
//Because getSingleResult() throws an unchecked exception which is an indication of a
//programming error, we are not going to use it.
@SuppressWarnings("rawtypes")
- List resultList = query.getResultList();
+ List resultList = query.getResultList();
PolicyEntity p2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
p2 = (PolicyEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest: No PolicyEntity DB entry found");
+ fail("\nPolicyEntityTest: No PolicyEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning configurationData*********"
- + "\npolicyId2 = " + p2.getPolicyId()
- + "\npolicyName2 = " + p2.getPolicyName()
- + "\nversion2 = " + p2.getVersion()
- + "\npolicyData2 = " + p2.getPolicyData()
- + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
- + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
- + "\nscope2 = " + p2.getScope()
- + "\ncreatedBy2 = " + p2.getCreatedBy()
- + "\ncreatedDate2 = " + p2.getCreatedDate()
- + "\ndescription2 = " + p2.getDescription()
- + "\nmodifiedBy2 = " + p2.getModifiedBy()
- + "\nmodifiedDate2 = " + p2.getModifiedDate()
- + "\ndeleted2 = " + p2.isDeleted());
+ + "\npolicyId2 = " + p2.getPolicyId()
+ + "\npolicyName2 = " + p2.getPolicyName()
+ + "\nversion2 = " + p2.getVersion()
+ + "\npolicyData2 = " + p2.getPolicyData()
+ + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
+ + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
+ + "\nscope2 = " + p2.getScope()
+ + "\ncreatedBy2 = " + p2.getCreatedBy()
+ + "\ncreatedDate2 = " + p2.getCreatedDate()
+ + "\ndescription2 = " + p2.getDescription()
+ + "\nmodifiedBy2 = " + p2.getModifiedBy()
+ + "\nmodifiedDate2 = " + p2.getModifiedDate()
+ + "\ndeleted2 = " + p2.isDeleted());
//Confirm that the retrieved policy object is the same as the persisted object
assertSame(p1,p2);
@@ -328,26 +328,26 @@ public class PolicyEntityTest {
query2.setParameter("cid", c1.getConfigurationDataId());
//Get the database version of the Configuration Data
- resultList = query2.getResultList();
+ resultList = query2.getResultList();
ConfigurationDataEntity c2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
c2 = (ConfigurationDataEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found");
+ fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to policy*********"
- + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
- + "\nversion2 = " + c2.getVersion()
- + "\nconfigType2 = " + c2.getConfigType()
- + "\nconfigBody2 = " + c2.getConfigBody()
- + "\ncreatedBy2 = " + c2.getCreatedBy()
- + "\ncreatedDate2 = " + c2.getCreatedDate()
- + "\ndescription2 = " + c2.getDescription()
- + "\nmodifiedBy2 = " + c2.getModifiedBy()
- + "\nmodifiedDate2 = " + c2.getModifiedDate()
- + "\ndeleted2 = " + c2.isDeleted());
+ + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
+ + "\nversion2 = " + c2.getVersion()
+ + "\nconfigType2 = " + c2.getConfigType()
+ + "\nconfigBody2 = " + c2.getConfigBody()
+ + "\ncreatedBy2 = " + c2.getCreatedBy()
+ + "\ncreatedDate2 = " + c2.getCreatedDate()
+ + "\ndescription2 = " + c2.getDescription()
+ + "\nmodifiedBy2 = " + c2.getModifiedBy()
+ + "\nmodifiedDate2 = " + c2.getModifiedDate()
+ + "\ndeleted2 = " + c2.isDeleted());
//Confirm the retrieved ConfigurationDataEntity object is the same as the persisted
assertSame(c1,c2);
@@ -361,25 +361,25 @@ public class PolicyEntityTest {
querya2.setParameter("aid", a1.getActionBodyId());
//Get the database version of the Action Body
- resultList = querya2.getResultList();
+ resultList = querya2.getResultList();
ActionBodyEntity a2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
a2 = (ActionBodyEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found");
+ fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to policy *********"
- + "\nactionBodyId2 = " + a2.getActionBodyId()
- + "\nactionBodyVersion2 = " + a2.getVersion()
- + "\nactionBody2 = " + a2.getActionBody()
- + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
- + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
- + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
- + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
- + "\nactionBodyDeleted2 = " + a2.isDeleted());
+ + "\nactionBodyId2 = " + a2.getActionBodyId()
+ + "\nactionBodyVersion2 = " + a2.getVersion()
+ + "\nactionBody2 = " + a2.getActionBody()
+ + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
+ + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
+ + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
+ + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
+ + "\nactionBodyDeleted2 = " + a2.isDeleted());
//Confirm the retrieved ActionBodyEntity object is the same as the persisted
@@ -398,67 +398,67 @@ public class PolicyEntityTest {
// ignores multiple results
p2 = (PolicyEntity) resultList.get(0);
}else{
- fail("PolicyEntityTest: No PolicyEntity DB entry found");
+ fail("PolicyEntityTest: No PolicyEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning configurationData*********"
- + "\npolicyId2 = " + p2.getPolicyId()
- + "\npolicyName2 = " + p2.getPolicyName()
- + "\nversion2 = " + p2.getVersion()
- + "\npolicyData2 = " + p2.getPolicyData()
- + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
- + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
- + "\nscope2 = " + p2.getScope()
- + "\ncreatedBy2 = " + p2.getCreatedBy()
- + "\ncreatedDate2 = " + p2.getCreatedDate()
- + "\ndescription2 = " + p2.getDescription()
- + "\nmodifiedBy2 = " + p2.getModifiedBy()
- + "\nmodifiedDate2 = " + p2.getModifiedDate()
- + "\ndeleted2 = " + p2.isDeleted());
+ + "\npolicyId2 = " + p2.getPolicyId()
+ + "\npolicyName2 = " + p2.getPolicyName()
+ + "\nversion2 = " + p2.getVersion()
+ + "\npolicyData2 = " + p2.getPolicyData()
+ + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
+ + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
+ + "\nscope2 = " + p2.getScope()
+ + "\ncreatedBy2 = " + p2.getCreatedBy()
+ + "\ncreatedDate2 = " + p2.getCreatedDate()
+ + "\ndescription2 = " + p2.getDescription()
+ + "\nmodifiedBy2 = " + p2.getModifiedBy()
+ + "\nmodifiedDate2 = " + p2.getModifiedDate()
+ + "\ndeleted2 = " + p2.isDeleted());
//And now the ConfigurationDataEntity object
- resultList = query2.getResultList();
+ resultList = query2.getResultList();
c2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
c2 = (ConfigurationDataEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found");
+ fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to policy*********"
- + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
- + "\nversion2 = " + c2.getVersion()
- + "\nconfigType2 = " + c2.getConfigType()
- + "\nconfigBody2 = " + c2.getConfigBody()
- + "\ncreatedBy2 = " + c2.getCreatedBy()
- + "\ncreatedDate2 = " + c2.getCreatedDate()
- + "\ndescription2 = " + c2.getDescription()
- + "\nmodifiedBy = " + c2.getModifiedBy()
- + "\nmodifiedDate = " + c2.getModifiedDate()
- + "\ndeleted2 = " + c2.isDeleted());
+ + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
+ + "\nversion2 = " + c2.getVersion()
+ + "\nconfigType2 = " + c2.getConfigType()
+ + "\nconfigBody2 = " + c2.getConfigBody()
+ + "\ncreatedBy2 = " + c2.getCreatedBy()
+ + "\ncreatedDate2 = " + c2.getCreatedDate()
+ + "\ndescription2 = " + c2.getDescription()
+ + "\nmodifiedBy = " + c2.getModifiedBy()
+ + "\nmodifiedDate = " + c2.getModifiedDate()
+ + "\ndeleted2 = " + c2.isDeleted());
//Get the database version of the Action Body
- resultList = querya2.getResultList();
+ resultList = querya2.getResultList();
a2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
a2 = (ActionBodyEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found");
+ fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to policy *********"
- + "\nactionBodyId2 = " + a2.getActionBodyId()
- + "\nactionBodyVersion2 = " + a2.getVersion()
- + "\nactionBody2 = " + a2.getActionBody()
- + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
- + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
- + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
- + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
- + "\nactionBodyDeleted2 = " + a2.isDeleted());
+ + "\nactionBodyId2 = " + a2.getActionBodyId()
+ + "\nactionBodyVersion2 = " + a2.getVersion()
+ + "\nactionBody2 = " + a2.getActionBody()
+ + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
+ + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
+ + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
+ + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
+ + "\nactionBodyDeleted2 = " + a2.isDeleted());
//****Now lets see if the orphanRemoval=true does anything useful***
@@ -473,30 +473,30 @@ public class PolicyEntityTest {
//Attempt to retrieve the configuration data object from the db. It should not be there
//Reusing the previous query
- resultList = query2.getResultList();
+ resultList = query2.getResultList();
c2 = null;
if(resultList.isEmpty()){
- logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
- + "\n Success!! No ConfigurationDataEntity DB entry found");
+ logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
+ + "\n Success!! No ConfigurationDataEntity DB entry found");
}else{
- c2 = (ConfigurationDataEntity) resultList.get(0);
- fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist"
- + "\nconfigurationDataId = " + c2.getConfigurationDataId());
+ c2 = (ConfigurationDataEntity) resultList.get(0);
+ fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist"
+ + "\nconfigurationDataId = " + c2.getConfigurationDataId());
}
//Attempt to retrieve the actionBody data object from the db. It should not be there
//Reusing the previous query
- resultList = querya2.getResultList();
+ resultList = querya2.getResultList();
a2 = null;
if(resultList.isEmpty()){
- logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
- + "\n Success!! No ActionBodyEntity DB entry found");
+ logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
+ + "\n Success!! No ActionBodyEntity DB entry found");
}else{
- a2 = (ActionBodyEntity) resultList.get(0);
- fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist"
- + "\nactionBodyId = " + a2.getActionBodyId());
+ a2 = (ActionBodyEntity) resultList.get(0);
+ fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist"
+ + "\nactionBodyId = " + a2.getActionBodyId());
}
//Now lets put the configurationData and actionBody back into the policy object and see what appears
@@ -512,86 +512,86 @@ public class PolicyEntityTest {
em.flush();
//retrieve the policy object
- resultList = query.getResultList();
+ resultList = query.getResultList();
p2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
p2 = (PolicyEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest: No PolicyEntity DB entry found");
+ fail("\nPolicyEntityTest: No PolicyEntity DB entry found");
}
//output what we policy object found
logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity and retrieving from DB*********"
- + "\npolicyId2 = " + p2.getPolicyId()
- + "\npolicyName2 = " + p2.getPolicyName()
- + "\nversion2 = " + p2.getVersion()
- + "\npolicyData2 = " + p2.getPolicyData()
- + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
- + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
- + "\nscope2 = " + p2.getScope()
- + "\ncreatedBy2 = " + p2.getCreatedBy()
- + "\ncreatedDate2 = " + p2.getCreatedDate()
- + "\ndescription2 = " + p2.getDescription()
- + "\nmodifiedBy2 = " + p2.getModifiedBy()
- + "\nmodifiedDate2 = " + p2.getModifiedDate()
- + "\ndeleted2 = " + p2.isDeleted());
+ + "\npolicyId2 = " + p2.getPolicyId()
+ + "\npolicyName2 = " + p2.getPolicyName()
+ + "\nversion2 = " + p2.getVersion()
+ + "\npolicyData2 = " + p2.getPolicyData()
+ + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
+ + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
+ + "\nscope2 = " + p2.getScope()
+ + "\ncreatedBy2 = " + p2.getCreatedBy()
+ + "\ncreatedDate2 = " + p2.getCreatedDate()
+ + "\ndescription2 = " + p2.getDescription()
+ + "\nmodifiedBy2 = " + p2.getModifiedBy()
+ + "\nmodifiedDate2 = " + p2.getModifiedDate()
+ + "\ndeleted2 = " + p2.isDeleted());
//now lets see if it put the configurationData c1 back into the table
- resultList = query2.getResultList();
+ resultList = query2.getResultList();
c2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
c2 = (ConfigurationDataEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest - Check re-entry of configurationData into DB"
- + "No ConfigurationDataEntity DB entry found");
+ fail("\nPolicyEntityTest - Check re-entry of configurationData into DB"
+ + "No ConfigurationDataEntity DB entry found");
}
//output what configurationData object we found
logger.debug("\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving from DB *********"
- + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
- + "\nversion2 = " + c2.getVersion()
- + "\nconfigType2 = " + c2.getConfigType()
- + "\nconfigBody2 = " + c2.getConfigBody()
- + "\ncreatedBy2 = " + c2.getCreatedBy()
- + "\ncreatedDate2 = " + c2.getCreatedDate()
- + "\ndescription2 = " + c2.getDescription()
- + "\nmodifiedBy = " + c2.getModifiedBy()
- + "\nmodifiedDate = " + c2.getModifiedDate()
- + "\ndeleted2 = " + c2.isDeleted());
+ + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
+ + "\nversion2 = " + c2.getVersion()
+ + "\nconfigType2 = " + c2.getConfigType()
+ + "\nconfigBody2 = " + c2.getConfigBody()
+ + "\ncreatedBy2 = " + c2.getCreatedBy()
+ + "\ncreatedDate2 = " + c2.getCreatedDate()
+ + "\ndescription2 = " + c2.getDescription()
+ + "\nmodifiedBy = " + c2.getModifiedBy()
+ + "\nmodifiedDate = " + c2.getModifiedDate()
+ + "\ndeleted2 = " + c2.isDeleted());
//now lets see if it put the actionBody a1 back into the table
//Get the database version of the Action Body
- resultList = querya2.getResultList();
+ resultList = querya2.getResultList();
a2 = null;
if(!resultList.isEmpty()){
// ignores multiple results
a2 = (ActionBodyEntity) resultList.get(0);
}else{
- fail("\nPolicyEntityTest - Check re-entry of actionBody into DB"
- + "No ActionBodyEntity DB entry found");
+ fail("\nPolicyEntityTest - Check re-entry of actionBody into DB"
+ + "No ActionBodyEntity DB entry found");
}
logger.debug("\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and retrieving from DB *********"
- + "\nactionBodyId2 = " + a2.getActionBodyId()
- + "\nactionBodyVersion2 = " + a2.getVersion()
- + "\nactionBody2 = " + a2.getActionBody()
- + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
- + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
- + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
- + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
- + "\nactionBodyDeleted2 = " + a2.isDeleted());
+ + "\nactionBodyId2 = " + a2.getActionBodyId()
+ + "\nactionBodyVersion2 = " + a2.getVersion()
+ + "\nactionBody2 = " + a2.getActionBody()
+ + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
+ + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
+ + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
+ + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
+ + "\nactionBodyDeleted2 = " + a2.isDeleted());
//I want to save all the above in the DB
try{
- et.commit();
- logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********");
+ et.commit();
+ logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********");
}catch(Exception e){
- logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********"
- + "\nTRANSACTION ROLLBACK "
- + "\n with exception: " + e);
+ logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********"
+ + "\nTRANSACTION ROLLBACK "
+ + "\n with exception: " + e);
}
// Start a new transaction
@@ -603,58 +603,58 @@ public class PolicyEntityTest {
PolicyEntity p3 = new PolicyEntity();
em.persist(p3);
-
- //first let's assure that you can save with the same name but a different scope
- p3.setPolicyName(p1.getPolicyName());
- p3.setScope("mckiou.kevin.kory");
- em.flush();
- logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
- + "\nSuccess! PolicyEntity uniqueness constraint allowed "
- + "\n policyId1 " + p1.getPolicyId()
- + "\n policyName1 " + p1.getPolicyName()
- + "\n scope1 = " + p1.getScope()
- + "\n policyId3 " + p3.getPolicyId()
- + "\n policyName3 " + p3.getPolicyName()
- + "\n scope3 = " + p3.getScope());
-
- //Assert that the policyIds are NOT the same to show that the automatic sequencing is working
- assert(p1.getPolicyId() != p3.getPolicyId());
-
- try{
- //Now set the scope the same to verify the uniqueness constraint will be enforced
- p3.setScope(p1.getScope());
-
- em.flush();
- logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
- + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow "
- + "\n policyId1 " + p1.getPolicyId()
- + "\n policyName1 " + p1.getPolicyName()
- + "\n scope1 = " + p1.getScope()
- + "\n policyId3 " + p3.getPolicyId()
- + "\n policyName3 " + p3.getPolicyName()
- + "\n scope3 = " + p3.getScope());;
+
+ //first let's assure that you can save with the same name but a different scope
+ p3.setPolicyName(p1.getPolicyName());
+ p3.setScope("mckiou.kevin.kory");
+ em.flush();
+ logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
+ + "\nSuccess! PolicyEntity uniqueness constraint allowed "
+ + "\n policyId1 " + p1.getPolicyId()
+ + "\n policyName1 " + p1.getPolicyName()
+ + "\n scope1 = " + p1.getScope()
+ + "\n policyId3 " + p3.getPolicyId()
+ + "\n policyName3 " + p3.getPolicyName()
+ + "\n scope3 = " + p3.getScope());
+
+ //Assert that the policyIds are NOT the same to show that the automatic sequencing is working
+ assert(p1.getPolicyId() != p3.getPolicyId());
+
+ try{
+ //Now set the scope the same to verify the uniqueness constraint will be enforced
+ p3.setScope(p1.getScope());
+
+ em.flush();
+ logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
+ + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow "
+ + "\n policyId1 " + p1.getPolicyId()
+ + "\n policyName1 " + p1.getPolicyName()
+ + "\n scope1 = " + p1.getScope()
+ + "\n policyId3 " + p3.getPolicyId()
+ + "\n policyName3 " + p3.getPolicyName()
+ + "\n scope3 = " + p3.getScope());;
}
catch(Exception e){
- //Success
- logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
- + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow "
- + "\n policyId1 " + p1.getPolicyId()
- + "\n policyName1 " + p1.getPolicyName()
- + "\n scope1 = " + p1.getScope()
- + "\n policyId3 " + p3.getPolicyId()
- + "\n policyName3 " + p3.getPolicyName()
- + "\n scope3 = " + p3.getScope()
- + "\n with excpetion: " + e);
+ //Success
+ logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
+ + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow "
+ + "\n policyId1 " + p1.getPolicyId()
+ + "\n policyName1 " + p1.getPolicyName()
+ + "\n scope1 = " + p1.getScope()
+ + "\n policyId3 " + p3.getPolicyId()
+ + "\n policyName3 " + p3.getPolicyName()
+ + "\n scope3 = " + p3.getScope()
+ + "\n with excpetion: " + e);
}
-
+
try{
- et2.commit();
- logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********");
+ et2.commit();
+ logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********");
}catch(Exception e){
- logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********"
- + "\nTRANSACTION ROLLBACK "
- + "\n with exception: " + e);
+ logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********"
+ + "\nTRANSACTION ROLLBACK "
+ + "\n with exception: " + e);
}
//****************Test the PolicyDBDaoEntity************************
@@ -685,63 +685,63 @@ public class PolicyEntityTest {
//Print them to the log before flushing
logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects before flush********"
- + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl()
- + "\n description-1 = " + pe1.getDescription()
- + "\n createdDate-1 = " + pe1.getCreatedDate()
- + "\n modifiedDate-1 " + pe1.getModifiedDate()
- + "\n*****************************************"
- + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl()
- + "\n description-2 = " + pe2.getDescription()
- + "\n createdDate-2 = " + pe2.getCreatedDate()
- + "\n modifiedDate-2 " + pe2.getModifiedDate()
- );
+ + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl()
+ + "\n description-1 = " + pe1.getDescription()
+ + "\n createdDate-1 = " + pe1.getCreatedDate()
+ + "\n modifiedDate-1 " + pe1.getModifiedDate()
+ + "\n*****************************************"
+ + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl()
+ + "\n description-2 = " + pe2.getDescription()
+ + "\n createdDate-2 = " + pe2.getCreatedDate()
+ + "\n modifiedDate-2 " + pe2.getModifiedDate()
+ );
//push it to the DB
em.flush();
//Now let's retrieve them from the DB using the named query
- resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList();
+ resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList();
+
+ PolicyDBDaoEntity pex = null;
+ PolicyDBDaoEntity pey = null;
- PolicyDBDaoEntity pex = null;
- PolicyDBDaoEntity pey = null;
-
if(!resultList.isEmpty()){
- if (resultList.size() != 2){
- fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2");
- }
- for(Object policyDBDaoEntity: resultList){
- PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity;
- if(pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){
- pex = pdbdao;
- }else if(pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")){
- pey = pdbdao;
- }
- }
-
+ if (resultList.size() != 2){
+ fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2");
+ }
+ for(Object policyDBDaoEntity: resultList){
+ PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity;
+ if(pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){
+ pex = pdbdao;
+ }else if(pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")){
+ pey = pdbdao;
+ }
+ }
+
//Print them to the log before flushing
logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects retrieved from DB********"
- + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl()
- + "\n description-x = " + pex.getDescription()
- + "\n createdDate-x = " + pex.getCreatedDate()
- + "\n modifiedDate-x " + pex.getModifiedDate()
- + "\n*****************************************"
- + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl()
- + "\n description-y = " + pey.getDescription()
- + "\n createdDate-y = " + pey.getCreatedDate()
- + "\n modifiedDate-y " + pey.getModifiedDate()
- );
- //Verify the retrieved objects are the same as the ones we stored in the DB
- if(pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){
- assertSame(pe1,pex);
- assertSame(pe2,pey);
- }else{
- assertSame(pe2,pex);
- assertSame(pe1,pey);
- }
+ + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl()
+ + "\n description-x = " + pex.getDescription()
+ + "\n createdDate-x = " + pex.getCreatedDate()
+ + "\n modifiedDate-x " + pex.getModifiedDate()
+ + "\n*****************************************"
+ + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl()
+ + "\n description-y = " + pey.getDescription()
+ + "\n createdDate-y = " + pey.getCreatedDate()
+ + "\n modifiedDate-y " + pey.getModifiedDate()
+ );
+ //Verify the retrieved objects are the same as the ones we stored in the DB
+ if(pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){
+ assertSame(pe1,pex);
+ assertSame(pe2,pey);
+ }else{
+ assertSame(pe2,pex);
+ assertSame(pe1,pey);
+ }
}else{
- fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found");
+ fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found");
}
//Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved.
@@ -751,32 +751,32 @@ public class PolicyEntityTest {
//retrieve it
Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDBDaoEntity p WHERE p.description=:desc");
- resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList();
-
- PolicyDBDaoEntity pez = null;
+ resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList();
+
+ PolicyDBDaoEntity pez = null;
if(!resultList.isEmpty()){
- if (resultList.size() != 1){
- fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1");
- }
- pez = (PolicyDBDaoEntity) resultList.get(0);
-
+ if (resultList.size() != 1){
+ fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1");
+ }
+ pez = (PolicyDBDaoEntity) resultList.get(0);
+
//Print them to the log before flushing
logger.debug("\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from DB********"
- + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl()
- + "\n description-x = " + pex.getDescription()
- + "\n createdDate-x = " + pex.getCreatedDate()
- + "\n modifiedDate-x " + pex.getModifiedDate()
- + "\n*****************************************"
- + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl()
- + "\n description-z = " + pez.getDescription()
- + "\n createdDate-z = " + pez.getCreatedDate()
- + "\n modifiedDate-z " + pez.getModifiedDate()
- );
- //Verify the retrieved objects are the same as the ones we stored in the DB
- assertSame(pex,pez);
+ + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl()
+ + "\n description-x = " + pex.getDescription()
+ + "\n createdDate-x = " + pex.getCreatedDate()
+ + "\n modifiedDate-x " + pex.getModifiedDate()
+ + "\n*****************************************"
+ + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl()
+ + "\n description-z = " + pez.getDescription()
+ + "\n createdDate-z = " + pez.getCreatedDate()
+ + "\n modifiedDate-z " + pez.getModifiedDate()
+ );
+ //Verify the retrieved objects are the same as the ones we stored in the DB
+ assertSame(pex,pez);
}else{
- fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found");
+ fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found");
}
//Clean up the DB
@@ -787,12 +787,12 @@ public class PolicyEntityTest {
//Wrap up the transaction
try{
- et3.commit();
- logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********");
+ et3.commit();
+ logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********");
}catch(Exception e){
- logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********"
- + "\nTRANSACTION ROLLBACK "
- + "\n with exception: " + e);
+ logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********"
+ + "\nTRANSACTION ROLLBACK "
+ + "\n with exception: " + e);
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java
index 34a26631f..162f4a928 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java
@@ -27,18 +27,18 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import com.att.research.xacml.api.pap.PDPPolicy;
public class RemoveGroupPolicyTest {
- @Test
- public void testRemove() {
- // Test constructor
- StdPDPGroup group = new StdPDPGroup();
- RemoveGroupPolicy remove = new RemoveGroupPolicy(group);
- assertEquals(remove.isRemoved(), false);
- assertEquals(remove.getUpdatedObject(), null);
-
- // Test remove
- PDPPolicy policy = new StdPDPPolicy();
- remove.prepareToRemove(policy);
- remove.doSave();
- assertEquals(remove.isRemoved(), true);
- }
+ @Test
+ public void testRemove() {
+ // Test constructor
+ StdPDPGroup group = new StdPDPGroup();
+ RemoveGroupPolicy remove = new RemoveGroupPolicy(group);
+ assertEquals(remove.isRemoved(), false);
+ assertEquals(remove.getUpdatedObject(), null);
+
+ // Test remove
+ PDPPolicy policy = new StdPDPPolicy();
+ remove.prepareToRemove(policy);
+ remove.doSave();
+ assertEquals(remove.isRemoved(), true);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java
index fed2ac973..ba400dfc0 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java
@@ -28,12 +28,12 @@ import com.mockrunner.mock.web.MockHttpServletRequest;
import com.mockrunner.mock.web.MockHttpServletResponse;
public class ImportServiceTest {
- @Test
- public void testNegativeCases() {
- ImportService service = new ImportService();
- HttpServletRequest request = new MockHttpServletRequest();
- HttpServletResponse response = new MockHttpServletResponse();
- service.doImportMicroServicePut(request, response);
- assertEquals(response.getHeader("error"), "missing");
- }
+ @Test
+ public void testNegativeCases() {
+ ImportService service = new ImportService();
+ HttpServletRequest request = new MockHttpServletRequest();
+ HttpServletResponse response = new MockHttpServletResponse();
+ service.doImportMicroServicePut(request, response);
+ assertEquals(response.getHeader("error"), "missing");
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java
index 0c85fe163..8c976d9aa 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java
@@ -34,16 +34,16 @@ import com.mockrunner.mock.web.MockHttpServletResponse;
@RunWith(PowerMockRunner.class)
public class MetricServiceTest {
- @PrepareForTest({XACMLPapServlet.class})
- @Test
- public void testNegativeGet() {
- // Mock pap servlet
- PowerMockito.mockStatic(XACMLPapServlet.class);
- when(XACMLPapServlet.getPAPEngine()).thenReturn(null);
- when(XACMLPapServlet.getEmf()).thenReturn(null);
+ @PrepareForTest({XACMLPapServlet.class})
+ @Test
+ public void testNegativeGet() {
+ // Mock pap servlet
+ PowerMockito.mockStatic(XACMLPapServlet.class);
+ when(XACMLPapServlet.getPAPEngine()).thenReturn(null);
+ when(XACMLPapServlet.getEmf()).thenReturn(null);
- MockHttpServletResponse response = new MockHttpServletResponse();
- MetricService.doGetPolicyMetrics(response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_BAD_REQUEST);
- }
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ MetricService.doGetPolicyMetrics(response);
+ assertEquals(response.getStatusCode(), HttpServletResponse.SC_BAD_REQUEST);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java
index 180c13f69..cbe9ff250 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java
@@ -26,27 +26,27 @@ import org.junit.Test;
import org.onap.policy.pap.xacml.restAuth.AuthenticationService;
public class AuthenticationServiceTest {
- private final String testCred = "testpap:alpha123";
- private final String testCredEncoded = new String(Base64.getEncoder().encode(testCred.getBytes()));
- private final String basicCred = "Basic " + testCredEncoded;
-
- @Test
- public void testAuth() throws UnsupportedEncodingException {
- String systemKey = "xacml.properties";
+ private final String testCred = "testpap:alpha123";
+ private final String testCredEncoded = new String(Base64.getEncoder().encode(testCred.getBytes()));
+ private final String basicCred = "Basic " + testCredEncoded;
- // Set the system property temporarily
- String oldProperty = System.getProperty(systemKey);
- System.setProperty(systemKey, "xacml.pap.properties");
-
- AuthenticationService service = new AuthenticationService();
- assertEquals(service.authenticate(basicCred), true);
-
- // Restore the original system property
- if (oldProperty != null) {
- System.setProperty(systemKey, oldProperty);
- }
- else {
- System.clearProperty(systemKey);
- }
- }
+ @Test
+ public void testAuth() throws UnsupportedEncodingException {
+ String systemKey = "xacml.properties";
+
+ // Set the system property temporarily
+ String oldProperty = System.getProperty(systemKey);
+ System.setProperty(systemKey, "xacml.pap.properties");
+
+ AuthenticationService service = new AuthenticationService();
+ assertEquals(service.authenticate(basicCred), true);
+
+ // Restore the original system property
+ if (oldProperty != null) {
+ System.setProperty(systemKey, oldProperty);
+ }
+ else {
+ System.clearProperty(systemKey);
+ }
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java
index 2d72c8a4d..f1554e84c 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java
@@ -38,84 +38,84 @@ import com.mockrunner.mock.web.MockHttpServletRequest;
import com.mockrunner.mock.web.MockHttpServletResponse;
public class PAPAuthenticationFilterTest {
-
- private HttpServletRequest request = null;
- private HttpServletResponse response = null;
- private String oldProperty;
- private String systemKey = "xacml.properties";
- private FilterChain filter;
- private PAPAuthenticationFilter papFilter;
-
- @Before
- public void setUp(){
- // Set the system property temporarily
- oldProperty = System.getProperty(systemKey);
- System.setProperty(systemKey, "xacml.pap.properties");
-
- request = Mockito.mock(HttpServletRequest.class);
- response = Mockito.mock(HttpServletResponse.class);
- filter = Mockito.mock(FilterChain.class);
- papFilter = new PAPAuthenticationFilter();
- }
-
- @Test
- public void testAuth() throws IOException, ServletException {
- PAPAuthenticationFilter filter = new PAPAuthenticationFilter();
- MockHttpServletRequest request = new MockHttpServletRequest();
- request.setRequestURI("/foo");
- MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = null;
-
- // Negative test the filter
- filter.doFilter(request, response, filterChain);
- assertEquals(response.getStatusCode(), 401);
-
- // Test base methods
- try {
- filter.destroy();
- filter.init(null);
- }
- catch (Exception ex) {
- fail("Not expecting any exceptions.");
- }
- }
-
- @Test
- public void testDoFilter() {
- Mockito.when(request.getRequestURI()).thenReturn("/pap/");
- Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTEyMw==");
- callDoFilter();
- Mockito.when(request.getRequestURI()).thenReturn("/pap/onap/");
- callDoFilter();
- }
-
- public void callDoFilter(){
- try {
- papFilter.doFilter(request, response, filter);
- } catch (Exception e) {
- assertEquals(NullPointerException.class, e.getClass());
- }
- }
-
- @Test
- public void testOnPassingInvalidParamters(){
- Mockito.when(request.getRequestURI()).thenReturn("/pap/");
- Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTE789==");
- try {
- papFilter.doFilter(request, response, filter);
- assertEquals(0, response.getStatus());
- } catch (Exception e) {
- fail();
- }
- }
-
- @After
- public void reset(){
- // Restore the original system property
- if (oldProperty != null) {
- System.setProperty(systemKey, oldProperty);
- } else {
- System.clearProperty(systemKey);
- }
- }
+
+ private HttpServletRequest request = null;
+ private HttpServletResponse response = null;
+ private String oldProperty;
+ private String systemKey = "xacml.properties";
+ private FilterChain filter;
+ private PAPAuthenticationFilter papFilter;
+
+ @Before
+ public void setUp(){
+ // Set the system property temporarily
+ oldProperty = System.getProperty(systemKey);
+ System.setProperty(systemKey, "xacml.pap.properties");
+
+ request = Mockito.mock(HttpServletRequest.class);
+ response = Mockito.mock(HttpServletResponse.class);
+ filter = Mockito.mock(FilterChain.class);
+ papFilter = new PAPAuthenticationFilter();
+ }
+
+ @Test
+ public void testAuth() throws IOException, ServletException {
+ PAPAuthenticationFilter filter = new PAPAuthenticationFilter();
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setRequestURI("/foo");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ FilterChain filterChain = null;
+
+ // Negative test the filter
+ filter.doFilter(request, response, filterChain);
+ assertEquals(response.getStatusCode(), 401);
+
+ // Test base methods
+ try {
+ filter.destroy();
+ filter.init(null);
+ }
+ catch (Exception ex) {
+ fail("Not expecting any exceptions.");
+ }
+ }
+
+ @Test
+ public void testDoFilter() {
+ Mockito.when(request.getRequestURI()).thenReturn("/pap/");
+ Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTEyMw==");
+ callDoFilter();
+ Mockito.when(request.getRequestURI()).thenReturn("/pap/onap/");
+ callDoFilter();
+ }
+
+ public void callDoFilter(){
+ try {
+ papFilter.doFilter(request, response, filter);
+ } catch (Exception e) {
+ assertEquals(NullPointerException.class, e.getClass());
+ }
+ }
+
+ @Test
+ public void testOnPassingInvalidParamters(){
+ Mockito.when(request.getRequestURI()).thenReturn("/pap/");
+ Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTE789==");
+ try {
+ papFilter.doFilter(request, response, filter);
+ assertEquals(0, response.getStatus());
+ } catch (Exception e) {
+ fail();
+ }
+ }
+
+ @After
+ public void reset(){
+ // Restore the original system property
+ if (oldProperty != null) {
+ System.setProperty(systemKey, oldProperty);
+ } else {
+ System.clearProperty(systemKey);
+ }
+ }
}