From: rb7147 Date: Wed, 28 Feb 2018 19:23:12 +0000 (-0500) Subject: Added Junits for Policy PAP-REST X-Git-Tag: v1.2.0~104^2 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=f0c563df34a999a1702d51cb6cb44fe10155b16b Added Junits for Policy PAP-REST Issue-ID: POLICY-600 Change-Id: Icb67ac587e614f663416b3ea0a03ca6e5b02c621 Signed-off-by: rb7147 --- diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java new file mode 100644 index 000000000..44e340396 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pap.xacml.rest.adapters; + +public class SearchData { + private String query; + private String policyType; + private String descriptiveScope; + private String closedLooppolicyType; + private String onapName; + private String d2Service; + private String vnfType; + private String policyStatus; + private String vproAction; + private String serviceType; + private String bindTextSearch; + public String getQuery() { + return query; + } + public void setQuery(String query) { + this.query = query; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getDescriptiveScope() { + return descriptiveScope; + } + public void setDescriptiveScope(String descriptiveScope) { + this.descriptiveScope = descriptiveScope; + } + public String getClosedLooppolicyType() { + return closedLooppolicyType; + } + public void setClosedLooppolicyType(String closedLooppolicyType) { + this.closedLooppolicyType = closedLooppolicyType; + } + public String getOnapName() { + return onapName; + } + public void setOnapName(String onapName) { + this.onapName = onapName; + } + public String getD2Service() { + return d2Service; + } + public void setD2Service(String d2Service) { + this.d2Service = d2Service; + } + public String getVnfType() { + return vnfType; + } + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getVproAction() { + return vproAction; + } + public void setVproAction(String vproAction) { + this.vproAction = vproAction; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getBindTextSearch() { + return bindTextSearch; + } + public void setBindTextSearch(String bindTextSearch) { + this.bindTextSearch = bindTextSearch; + } +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java index d064d052b..5de09215c 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 @@ -19,9 +19,10 @@ */ package org.onap.policy.pap.xacml.rest.elk.client; +import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; -import java.nio.file.Files; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; @@ -36,6 +37,8 @@ import java.util.Properties; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.CryptoUtils; +import org.onap.policy.xacml.util.XACMLPolicyScanner; import com.google.gson.Gson; @@ -77,13 +80,13 @@ public class ElasticSearchPolicyUpdate { String elkURL = null; String databseUrl = null; String userName = null; - String password = null; + String txt = null; String databaseDriver = null; String propertyFile = System.getProperty("PROPERTY_FILE"); Properties config = new Properties(); Path file = Paths.get(propertyFile); - if(Files.notExists(file)){ + if(!file.toFile().exists()){ LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); }else{ if(file.toString().endsWith(".properties")){ @@ -93,9 +96,9 @@ public class ElasticSearchPolicyUpdate { elkURL = config.getProperty("policy.elk.url"); databseUrl = config.getProperty("policy.database.url"); userName = config.getProperty("policy.database.username"); - password = config.getProperty("policy.database.password"); + txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password")); databaseDriver = config.getProperty("policy.database.driver"); - if(elkURL == null || databseUrl == null || userName == null || password == null || databaseDriver == null){ + if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){ LOGGER.error("please check the elk configuration"); } } catch (Exception e) { @@ -113,11 +116,11 @@ public class ElasticSearchPolicyUpdate { Connection conn = null; Statement stmt = null; - List listIndex = new ArrayList(); + List listIndex = new ArrayList<>(); try { Class.forName(databaseDriver); - conn = DriverManager.getConnection(databseUrl, userName, password); + conn = DriverManager.getConnection(databseUrl, userName, txt); stmt = conn.createStatement(); String policyEntityQuery = "Select * from PolicyEntity"; @@ -252,7 +255,9 @@ public class ElasticSearchPolicyUpdate { } } - private static String constructPolicyData(Object policyData, StringBuilder policyDataString){ + public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){ + InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8)); + Object policyData = XACMLPolicyScanner.readPolicy(stream); if(policyData instanceof PolicyType){ PolicyType policy = (PolicyType) policyData; TargetType target = policy.getTarget(); 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 77e45e30d..a8320093e 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,26 +23,18 @@ package org.onap.policy.pap.xacml.rest.elk.client; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.adapters.SearchData; import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; import org.onap.policy.pap.xacml.rest.util.JsonMessage; import org.onap.policy.rest.adapter.PolicyRestAdapter; @@ -55,10 +47,10 @@ import org.onap.policy.rest.jpa.ClosedLoopSite; import org.onap.policy.rest.jpa.DCAEuuid; import org.onap.policy.rest.jpa.DecisionSettings; import org.onap.policy.rest.jpa.DescriptiveScope; -import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.GroupPolicyScopeList; import org.onap.policy.rest.jpa.MicroServiceLocation; import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.PEPOptions; import org.onap.policy.rest.jpa.RiskType; import org.onap.policy.rest.jpa.SafePolicyWarning; @@ -66,6 +58,7 @@ import org.onap.policy.rest.jpa.TermList; import org.onap.policy.rest.jpa.VNFType; import org.onap.policy.rest.jpa.VSCLAction; import org.onap.policy.rest.jpa.VarbindDictionary; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -98,53 +91,22 @@ public class PolicyElasticSearchController{ }; 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"; @Autowired public PolicyElasticSearchController(CommonClassDao commonClassDao) { PolicyElasticSearchController.commonClassDao = commonClassDao; } - public PolicyElasticSearchController() {} - - public static void TurnOffCertsCheck() { - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted(X509Certificate[] certs, - String authType) { - } - public void checkServerTrusted(X509Certificate[] certs, - String authType) { - } - } }; - - // Install all-trusting trust manager - SSLContext ctx; - try { - ctx = SSLContext.getInstance("SSL"); - ctx.init(null, trustAllCerts, new java.security.SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(ctx - .getSocketFactory()); - } catch (NoSuchAlgorithmException | KeyManagementException e) { - LOGGER.error("SSL Security Error: " + e); - } - - // Create all-trusting host name verifier - HostnameVerifier allHostsValid = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - // Install the all-trusting host verifier - HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + public PolicyElasticSearchController() { + super(); } - - - public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { if (type == null || type.isEmpty()){ return PolicyIndexType.all; @@ -196,8 +158,10 @@ public class PolicyElasticSearchController{ @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(); @@ -207,16 +171,16 @@ public class PolicyElasticSearchController{ if(request.getParameter("policyName") != null){ String policyName = request.getParameter("policyName"); policyData.setNewFileName(policyName); - if("delete".equalsIgnoreCase(request.getParameter("action"))){ + if("delete".equalsIgnoreCase(request.getParameter(action))){ result = controller.deleteElk(policyData); }else{ result = controller.updateElk(policyData); } } - if("search".equalsIgnoreCase(request.getParameter("action"))){ + if("search".equalsIgnoreCase(request.getParameter(action))){ try { JsonNode root = mapper.readTree(request.getReader()); - SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class); + SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class); String policyType = searchData.getPolicyType(); @@ -229,7 +193,11 @@ public class PolicyElasticSearchController{ for(String keyValue : descriptiveList){ String[] entry = keyValue.split(":"); if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ - searchKeyValue.put("jsonBodyData", "*" +entry[1] +"*"); + 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]; } @@ -237,6 +205,11 @@ public class PolicyElasticSearchController{ } } + 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())){ @@ -251,27 +224,27 @@ public class PolicyElasticSearchController{ } if(searchData.getD2Service() != null){ String d2Service = searchData.getD2Service().trim(); - if(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){ + if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){ d2Service = "trinity"; - }else if(d2Service.equalsIgnoreCase("vUSP")){ + }else if("vUSP".equalsIgnoreCase(d2Service)){ d2Service = "vUSP"; - }else if(d2Service.equalsIgnoreCase("MCR")){ + }else if("MCR".equalsIgnoreCase(d2Service)){ d2Service = "mcr"; - }else if(d2Service.equalsIgnoreCase("Gamma")){ + }else if("Gamma".equalsIgnoreCase(d2Service)){ d2Service = "gamma"; - }else if(d2Service.equalsIgnoreCase("vDNS")){ + }else if("vDNS".equalsIgnoreCase(d2Service)){ d2Service = "vDNS"; } searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); } if(searchData.getVnfType() != null){ - searchKeyValue.put("jsonBodyData", "*"+searchData.getVnfType()+"*"); + searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*"); } if(searchData.getPolicyStatus() != null){ - searchKeyValue.put("jsonBodyData", "*"+searchData.getPolicyStatus()+"*"); + searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*"); } if(searchData.getVproAction() != null){ - searchKeyValue.put("jsonBodyData", "*"+searchData.getVproAction()+"*"); + searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*"); } if(searchData.getServiceType() != null){ searchKeyValue.put("serviceType", searchData.getServiceType()); @@ -282,13 +255,13 @@ public class PolicyElasticSearchController{ } PolicyIndexType type = null; if(policyType != null){ - if(policyType.equalsIgnoreCase("action")){ + if(action.equalsIgnoreCase(policyType)){ type = ElkConnector.PolicyIndexType.action; - }else if(policyType.equalsIgnoreCase("decision")){ + }else if(decision.equalsIgnoreCase(policyType)){ type = ElkConnector.PolicyIndexType.decision; - }else if(policyType.equalsIgnoreCase("config")){ + }else if(config.equalsIgnoreCase(policyType)){ type = ElkConnector.PolicyIndexType.config; - }else if(policyType.equalsIgnoreCase("closedloop")){ + }else if("closedloop".equalsIgnoreCase(policyType)){ type = ElkConnector.PolicyIndexType.closedloop; }else{ type = ElkConnector.PolicyIndexType.all; @@ -296,32 +269,35 @@ public class PolicyElasticSearchController{ }else{ type = ElkConnector.PolicyIndexType.all; } - 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); + 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"); } - }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); } } - String message=""; - if(result){ - message = "Elastic Server Transaction is success"; - }else{ - message = "Elastic Server Transaction is failed, please check the logs"; + 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"); + response.addHeader(success, success); if(policyResult){ JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); response.getWriter().write(k.toString()); @@ -353,107 +329,107 @@ public class PolicyElasticSearchController{ List policyList = new ArrayList<>(); switch (mode){ case attribute : - Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); + Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); value = attributedata.getXacmlId(); - policyList = searchElkDatabase(all, "pholder",value); + policyList = searchElkDatabase(all, pholder,value); break; case onapName : - OnapName onapName = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class); + OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); value = onapName.getOnapName(); policyList = searchElkDatabase(all, "onapName",value); break; case actionPolicy : - ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); value = actionPolicyDict.getAttributeName(); policyList = searchElkDatabase(action, "actionAttributeValue",value); break; case brmsParam : - BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + BRMSParamTemplate bRMSParamTemplate = mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); value = bRMSParamTemplate.getRuleName(); policyList = searchElkDatabase(config, "ruleName",value); break; case pepOptions : - PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); + PEPOptions pEPOptions = mapper.readValue(root.get("data").toString(), PEPOptions.class); value = pEPOptions.getPepName(); policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); break; case clSite : - ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); value = closedLoopSite.getSiteName(); policyList = searchElkDatabase(closedloop,"siteNames",value); break; case clService : - ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + ClosedLoopD2Services closedLoopD2Services = mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); value = closedLoopD2Services.getServiceName(); - policyList = searchElkDatabase(closedloop, "pholder",value); + policyList = searchElkDatabase(closedloop, pholder,value); break; case clVarbind : - VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + VarbindDictionary varbindDictionary = mapper.readValue(root.get("data").toString(), VarbindDictionary.class); value = varbindDictionary.getVarbindName(); - policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*"); + policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); break; case clVnf : - VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); + VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class); value = vNFType.getVnftype(); - policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*"); + policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); break; case clVSCL : - VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); + VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class); value = vsclAction.getVsclaction(); - policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*"); + policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); break; case decision : - DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); + DecisionSettings decisionSettings = mapper.readValue(root.get("data").toString(), DecisionSettings.class); value = decisionSettings.getXacmlId(); - policyList = searchElkDatabase(decision,"pholder",value); + policyList = searchElkDatabase(decision,pholder,value); break; case fwTerm : - TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); + TermList term = mapper.readValue(root.get("data").toString(), TermList.class); value = term.getTermName(); - policyList = searchElkDatabase(config, "pholder",value); + policyList = searchElkDatabase(config, pholder,value); break; case msDCAEUUID : - DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); + DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class); value = dcaeUUID.getName(); policyList = searchElkDatabase(config, "uuid",value); break; case msLocation : - MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + MicroServiceLocation mslocation = mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); value = mslocation.getName(); policyList = searchElkDatabase(config, "location",value); break; case msModels : - MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + MicroServiceModels msModels = mapper.readValue(root.get("data").toString(), MicroServiceModels.class); value = msModels.getModelName(); policyList = searchElkDatabase(config, "serviceType",value); break; case psGroupPolicy : - GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + GroupPolicyScopeList groupPoilicy = mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); value = groupPoilicy.getGroupName(); - policyList = searchElkDatabase(config, "pholder",value); + policyList = searchElkDatabase(config, pholder,value); break; case safeRisk : - RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class); + RiskType riskType= mapper.readValue(root.get("data").toString(), RiskType.class); value = riskType.getRiskName(); policyList = searchElkDatabase(config, "riskType",value); break; case safePolicyWarning : - SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + SafePolicyWarning safePolicy = mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); value = safePolicy.getName(); - policyList = searchElkDatabase(config, "pholder",value); + policyList = searchElkDatabase(config, pholder,value); break; default: } response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("success", "success"); + 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(e.getMessage()); + out.write(PolicyUtils.CATCH_EXCEPTION); LOGGER.error(e); } return null; @@ -463,7 +439,7 @@ public class PolicyElasticSearchController{ public List searchElkDatabase(PolicyIndexType type, String key, String value){ PolicyElasticSearchController controller = new PolicyElasticSearchController(); Map searchKeyValue = new HashMap<>(); - if(!"pholder".equals(key)){ + if(!pholder.equals(key)){ searchKeyValue.put(key, value); } @@ -485,84 +461,4 @@ public class PolicyElasticSearchController{ return ElkConnector.singleton.search(type, text, searchKeyValue); } -} - -class SearchData{ - private String query; - private String policyType; - private String descriptiveScope; - private String closedLooppolicyType; - private String onapName; - private String d2Service; - private String vnfType; - private String policyStatus; - private String vproAction; - private String serviceType; - private String bindTextSearch; - public String getQuery() { - return query; - } - public void setQuery(String query) { - this.query = query; - } - public String getPolicyType() { - return policyType; - } - public void setPolicyType(String policyType) { - this.policyType = policyType; - } - public String getDescriptiveScope() { - return descriptiveScope; - } - public void setDescriptiveScope(String descriptiveScope) { - this.descriptiveScope = descriptiveScope; - } - public String getClosedLooppolicyType() { - return closedLooppolicyType; - } - public void setClosedLooppolicyType(String closedLooppolicyType) { - this.closedLooppolicyType = closedLooppolicyType; - } - public String getOnapName() { - return onapName; - } - public void setOnapName(String onapName) { - this.onapName = onapName; - } - public String getD2Service() { - return d2Service; - } - public void setD2Service(String d2Service) { - this.d2Service = d2Service; - } - public String getVnfType() { - return vnfType; - } - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - public String getPolicyStatus() { - return policyStatus; - } - public void setPolicyStatus(String policyStatus) { - this.policyStatus = policyStatus; - } - public String getVproAction() { - return vproAction; - } - public void setVproAction(String vproAction) { - this.vproAction = vproAction; - } - public String getServiceType() { - return serviceType; - } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - public String getBindTextSearch() { - return bindTextSearch; - } - public void setBindTextSearch(String bindTextSearch) { - this.bindTextSearch = bindTextSearch; - } -} +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java index 44cb7d14a..c4b97f592 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,22 +56,9 @@ public class PAPAuthenticationFilter implements Filter { String url = httpServletRequest.getRequestURI(); logger.info("Request URI: " + url); - System.out.println("Request URI: " + url); //getting authentication credentials - if(url.contains("@Auth@")){ - int authIndex = url.lastIndexOf("@"); - int endAuthIndex = url.indexOf("/onap"); - authCredentials = "Basic " + url.substring(authIndex+1, endAuthIndex); - - //parse the url for /pap/onap/ - String url1 = url.substring(0, 4); - String url2 = url.substring(endAuthIndex, url.length()); - url = url1 + url2; - - } else { - authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); - } + authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); // Check Authentication credentials AuthenticationService authenticationService = new AuthenticationService(); @@ -79,28 +66,18 @@ public class PAPAuthenticationFilter implements Filter { if (authenticationStatus) { //indicates the request comes from Traditional Admin Console or PolicyEngineAPI - if (url.equals("/pap/")){ + 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/")){ - + }else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse){ //indicates the request comes from the ONAP Portal onap-sdk-app - if(response instanceof HttpServletResponse) { - 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 - System.out.println("New Request URI: " + url); - filter.doFilter(request, response); - /*url = url.substring(url.indexOf("/pap/")+4); - request.getRequestDispatcher(url).forward(request, response);*/ - } - + 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; @@ -122,9 +99,11 @@ public class PAPAuthenticationFilter implements Filter { @Override public void destroy() { + //Empty } @Override public void init(FilterConfig arg0) throws ServletException { + //Empty } } 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 c44459690..2b84ccaf1 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 @@ -715,7 +715,7 @@ public class XACMLPAPTest { setDBDao(); } - private void setDBDao() throws SQLException { + public void setDBDao() throws SQLException { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.h2.Driver"); // In-memory DB for testing 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 new file mode 100644 index 000000000..839af2fdc --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pap.xacml.rest.adapters; + +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()); + } +} 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 a2c6ddf4e..0dd919a35 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 @@ -35,6 +35,7 @@ import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.test.XACMLPAPTest; import org.onap.policy.rest.adapter.PolicyRestAdapter; import com.att.research.xacml.util.XACMLProperties; @@ -47,7 +48,7 @@ public class FirewallConfigPolicyTest { Map attributeMap = new HashMap<>(); FirewallConfigPolicy component = null; FirewallConfigPolicy mockFWConfig = null; - + private XACMLPAPTest papTest; /** * @throws java.lang.Exception @@ -81,6 +82,8 @@ public class FirewallConfigPolicyTest { component = new FirewallConfigPolicy(policyAdapter); mockFWConfig = Mockito.mock(FirewallConfigPolicy.class); + papTest = new XACMLPAPTest(); + papTest.setDBDao(); logger.info("setUp: exit"); } @@ -132,7 +135,7 @@ public class FirewallConfigPolicyTest { 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}]}"; - assertFalse((Boolean) method.invoke(firewallConfigPolicy, jsonBody, prevJsonBody)); + assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody, prevJsonBody)); } @Test @@ -141,7 +144,7 @@ public class FirewallConfigPolicyTest { Method method = firewallConfigPolicy.getClass().getDeclaredMethod("insertFirewallDicionaryData", 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}]}"; - assertFalse((Boolean) method.invoke(firewallConfigPolicy, jsonBody)); + assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody)); } } \ No newline at end of file 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 new file mode 100644 index 000000000..2b1300cc4 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pap.xacml.rest.elk; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.Date; + +import javax.servlet.ServletException; + +import org.apache.commons.io.IOUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.test.XACMLPAPTest; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.pap.xacml.rest.elk.client.ElasticSearchPolicyUpdate; +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"); + try { + 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(); + configurationEntity.setConfigBody("Sample Test"); + configurationEntity.setConfigType("OTHER"); + configurationEntity.setConfigurationName("com.Config_SampleTest1206.1.txt"); + configurationEntity.setDescription("test"); + configurationEntity.setModifiedBy("Test"); + configurationEntity.setModifiedDate(new Date()); + + + PolicyEntity entity = new PolicyEntity(); + entity.setPolicyName("Config_SampleTest.1.xml"); + entity.setPolicyData(policyContent.toString()); + entity.setScope("com"); + entity.setCreatedBy("Test"); + entity.setDeleted(false); + entity.setDescription("Test"); + entity.setModifiedBy("Test"); + entity.setConfigurationData(configurationEntity); + entity.preUpdate(); + CommonClassDaoImpl dao = new CommonClassDaoImpl(); + 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"); + } +} 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 new file mode 100644 index 000000000..ec86996c1 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pap.xacml.rest.elk; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +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 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/restAuth/AuthenticationServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java index 9ac434146..180c13f69 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 @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * ONAP-PDP-REST + * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -//foo package org.onap.policy.pap.xacml.restAuth; import static org.junit.Assert.assertEquals; 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 a115c084b..2d72c8a4d 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 @@ -17,19 +17,47 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -//foo package org.onap.policy.pap.xacml.restAuth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; + import java.io.IOException; + import javax.servlet.FilterChain; import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; + 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(); @@ -51,4 +79,43 @@ public class PAPAuthenticationFilterTest { 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); + } + } } diff --git a/ONAP-PAP-REST/src/test/resources/policyelk.properties b/ONAP-PAP-REST/src/test/resources/policyelk.properties new file mode 100644 index 000000000..74c447110 --- /dev/null +++ b/ONAP-PAP-REST/src/test/resources/policyelk.properties @@ -0,0 +1,30 @@ +### +# ============LICENSE_START======================================================= +# ONAP Policy Engine +# ================================================================================ +# Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + + +#Elk database url +policy.elk.url=http://localhost:9200 + + +#Policy Database properties +policy.database.driver=org.h2.Driver +policy.database.url=jdbc:h2:mem:test +policy.database.username=sa +policy.database.password= \ No newline at end of file diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTest.java similarity index 98% rename from ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java rename to ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTest.java index 88369850f..1185eddff 100644 --- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import org.onap.policy.pdp.rest.restAuth.PDPAuthenticationFilter; import com.att.research.xacml.util.XACMLProperties; import com.mockrunner.mock.web.MockRequestDispatcher; -public class FilterTests { +public class FilterTest { private PDPAuthenticationFilter authenticationFilter = new PDPAuthenticationFilter(); private final String VALIDHEADERVALUE = "Basic dGVzdHBkcDphbHBoYTQ1Ng==";