summaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client
diff options
context:
space:
mode:
Diffstat (limited to 'ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client')
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java311
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java101
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java418
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java33
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java623
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java563
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java51
7 files changed, 2100 insertions, 0 deletions
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
new file mode 100644
index 000000000..dcd44f84f
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java
@@ -0,0 +1,311 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.pap.xacml.rest.elk.client;
+
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+
+import com.google.gson.Gson;
+
+import io.searchbox.client.JestClientFactory;
+import io.searchbox.client.config.HttpClientConfig;
+import io.searchbox.client.http.JestHttpClient;
+import io.searchbox.core.Bulk;
+import io.searchbox.core.Bulk.Builder;
+import io.searchbox.core.BulkResult;
+import io.searchbox.core.Index;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+
+
+/**
+ * This code will deals with parsing the XACML content on reading from
+ * database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables)
+ * and convert the data into json to do bulk operation on putting to elastic search database.
+ * Which is used to support Elastic Search in Policy Application GUI to search policies.
+ *
+ *
+ *
+ * properties should be configured in policyelk.properties
+ *
+ */
+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 password = null;
+ String databaseDriver = null;
+
+ String propertyFile = System.getProperty("PROPERTY_FILE");
+ Properties config = new Properties();
+ Path file = Paths.get(propertyFile);
+ if(Files.notExists(file)){
+ 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");
+ password = config.getProperty("policy.database.password");
+ databaseDriver = config.getProperty("policy.database.driver");
+ if(elkURL == null || databseUrl == null || userName == null || password == null || databaseDriver == null){
+ LOGGER.error("One of the Property is null in policyelk.properties = elkurl:databaseurl:username:password:databasedriver "
+ + elkURL + ":"+ databseUrl + ":"+ userName + ":"+ password + ":"+ databaseDriver + ":");
+ }
+ } catch (Exception e) {
+ LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString());
+ }
+ }
+ }
+
+ 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;
+
+ List<Index> listIndex = new ArrayList<Index>();
+
+ try {
+ Class.forName(databaseDriver);
+ conn = DriverManager.getConnection(databseUrl, userName, password);
+ stmt = conn.createStatement();
+
+ String policyEntityQuery = "Select * from PolicyEntity";
+ ResultSet 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){
+ String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = "+configurationdataid+"";
+ Statement configstmt = conn.createStatement();
+ ResultSet configResult = configstmt.executeQuery(configEntityQuery);
+ while(configResult.next()){
+ String configBody = configResult.getString("configbody");
+ String configType = configResult.getString("configtype");
+ if("JSON".equalsIgnoreCase(configType)){
+ policyDataString.append("\"jsonBodyData\":"+configBody+",\"configType\":\""+configType+"\",");
+ }else if("OTHER".equalsIgnoreCase(configType)){
+ if(configBody!=null){
+ configBody= configBody.replaceAll("\"", "");
+ policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
+ }
+ }
+ }
+ configResult.close();
+ }
+
+ if(actionbodyid != null){
+ String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = "+actionbodyid+"";
+ Statement actionstmt = conn.createStatement();
+ ResultSet actionResult = actionstmt.executeQuery(actionEntityQuery);
+ while(actionResult.next()){
+ String actionBody = actionResult.getString("actionbody");
+ policyDataString.append("\"jsonBodyData\":"+actionBody+",");
+ }
+ actionResult.close();
+ }
+ }
+
+ String _id = policyWithScopeName;
+
+ policyDataString.append(constructPolicyData(policyData, policyDataString));
+
+ String dataString = policyDataString.toString();
+ dataString = dataString.substring(0, dataString.length()-1);
+ dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
+ dataString = dataString.replace("null", "\"\"");
+ dataString = dataString.replaceAll(" ", "").replaceAll("\n", "");
+
+ try{
+ Gson gson = new Gson();
+ gson.fromJson(dataString, Object.class);
+ }catch(Exception 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(conn != null){
+ try {
+ conn.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the connection"+e);
+ }
+ }
+ }
+ }
+
+ private static String constructPolicyData(Object policyData, StringBuilder policyDataString){
+ 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();
+ }
+
+} \ 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
new file mode 100644
index 000000000..1dea5dd4b
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.pap.xacml.rest.elk.client;
+
+
+import java.util.Map;
+
+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,
+ 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("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
new file mode 100644
index 000000000..8868db3bc
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java
@@ -0,0 +1,418 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.pap.xacml.rest.elk.client;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.index.query.QueryStringQueryBuilder;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.json.JSONObject;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+
+import io.searchbox.action.Action;
+import io.searchbox.client.JestClient;
+import io.searchbox.client.JestClientFactory;
+import io.searchbox.client.JestResult;
+import io.searchbox.client.config.HttpClientConfig;
+import io.searchbox.core.Delete;
+import io.searchbox.core.Index;
+import io.searchbox.core.Search;
+import io.searchbox.core.Search.Builder;
+import io.searchbox.indices.IndicesExists;
+import io.searchbox.indices.type.TypeExist;
+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;
+ }
+ }
+
+ @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");
+ }
+
+ 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 = 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;
+ }
+
+
+ @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);
+ }
+
+ 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) {
+ 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("OK: PUT operation of " + "->" + ": " +
+ "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
+ result.getPathToResult() + "]" + System.lineSeparator() +
+ result.getJsonString());
+ } else {
+ if (LOGGER.isWarnEnabled())
+ LOGGER.warn("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/Pair.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java
new file mode 100644
index 000000000..2b0c94bf3
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java
@@ -0,0 +1,33 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.pap.xacml.rest.elk.client;
+
+public class Pair<L,R> {
+ private L left;
+ private R right;
+ public Pair(L l, R r){
+ this.left = l;
+ this.right = r;
+ }
+ public L left(){ return left; }
+ public R right(){ return right; }
+ public void left(L l){ this.left = l; }
+ public void right(R r){ this.right = r; }
+} \ No newline at end of file
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java
new file mode 100644
index 000000000..3e065ff05
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java
@@ -0,0 +1,623 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.pap.xacml.rest.elk.client;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+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 LinkedHashMap<?, ?> serviceTypePolicyName;
+ private LinkedHashMap<?, ?> verticaMetrics;
+ private LinkedHashMap<?, ?> description;
+ private LinkedHashMap<?, ?> 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 ArrayList<Object> triggerSignatures;
+ private ArrayList<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 ArrayList<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 ArrayList<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.getDomain();
+ 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 LinkedHashMap<?, ?> getServiceTypePolicyName() {
+ return serviceTypePolicyName;
+ }
+
+ public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) {
+ this.serviceTypePolicyName = serviceTypePolicyName;
+ }
+
+ public LinkedHashMap<?, ?> getVerticaMetrics() {
+ return verticaMetrics;
+ }
+
+ public void setVerticaMetrics(LinkedHashMap<?, ?> verticaMetrics) {
+ this.verticaMetrics = verticaMetrics;
+ }
+
+ public LinkedHashMap<?, ?> getDescription() {
+ return description;
+ }
+
+ public void setDescription(LinkedHashMap<?, ?> description) {
+ this.description = description;
+ }
+
+ public LinkedHashMap<?, ?> 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 ArrayList<Object> getTriggerSignatures() {
+ return triggerSignatures;
+ }
+ public void setTriggerSignatures(ArrayList<Object> triggerSignatures) {
+ this.triggerSignatures = triggerSignatures;
+ }
+ public ArrayList<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 ArrayList<String> getBrmsDependency() {
+ return brmsDependency;
+ }
+ public void setBrmsDependency(ArrayList<String> brmsDependency) {
+ this.brmsDependency = brmsDependency;
+ }
+ public LinkedHashMap<?, ?> getRuleData() {
+ return ruleData;
+ }
+ public void setRuleData(LinkedHashMap<?, ?> ruleData) {
+ this.ruleData = ruleData;
+ }
+ public LinkedHashMap<?, ?> 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 ArrayList<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
new file mode 100644
index 000000000..2f4dc59cf
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java
@@ -0,0 +1,563 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.pap.xacml.rest.elk.client;
+
+
+import java.io.PrintWriter;
+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.elk.client.ElkConnector.PolicyIndexType;
+import org.onap.policy.pap.xacml.rest.util.JsonMessage;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.ActionPolicyDict;
+import org.onap.policy.rest.jpa.Attribute;
+import org.onap.policy.rest.jpa.BRMSParamTemplate;
+import org.onap.policy.rest.jpa.ClosedLoopD2Services;
+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.PEPOptions;
+import org.onap.policy.rest.jpa.RiskType;
+import org.onap.policy.rest.jpa.SafePolicyWarning;
+import org.onap.policy.rest.jpa.TermList;
+import org.onap.policy.rest.jpa.VNFType;
+import org.onap.policy.rest.jpa.VSCLAction;
+import org.onap.policy.rest.jpa.VarbindDictionary;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.JsonArray;
+
+import io.searchbox.client.JestResult;
+
+@Controller
+@RequestMapping({"/"})
+public class PolicyElasticSearchController{
+
+ 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
+ }
+
+ public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
+ private static final long serialVersionUID = 1L;
+ };
+
+ public static CommonClassDao commonClassDao;
+
+ @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 ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
+ if (type == null || type.isEmpty()){
+ return PolicyIndexType.all;
+ }
+ return PolicyIndexType.valueOf(type);
+ }
+
+ 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 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;
+ }
+
+
+ @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
+ public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
+ try{
+ boolean result = false;
+ boolean policyResult = false;
+ 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 = (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())){
+ searchKeyValue.put("jsonBodyData", "*" +entry[1] +"*");
+ }else{
+ searchKeyValue.put(entry[0], entry[1]);
+ }
+ }
+ }
+ }
+
+ 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(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){
+ d2Service = "trinity";
+ }else if(d2Service.equalsIgnoreCase("vUSP")){
+ d2Service = "vUSP";
+ }else if(d2Service.equalsIgnoreCase("MCR")){
+ d2Service = "mcr";
+ }else if(d2Service.equalsIgnoreCase("Gamma")){
+ d2Service = "gamma";
+ }else if(d2Service.equalsIgnoreCase("vDNS")){
+ 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(policyType.equalsIgnoreCase("action")){
+ type = ElkConnector.PolicyIndexType.action;
+ }else if(policyType.equalsIgnoreCase("decision")){
+ type = ElkConnector.PolicyIndexType.decision;
+ }else if(policyType.equalsIgnoreCase("config")){
+ type = ElkConnector.PolicyIndexType.config;
+ }else {
+ type = ElkConnector.PolicyIndexType.closedloop;
+ }
+ }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);
+ }
+ }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";
+ }
+ 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());
+ }
+ }
+
+ @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ 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 = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
+ value = attributedata.getXacmlId();
+ policyList = searchElkDatabase(all, "pholder",value);
+ break;
+ case onapName :
+ OnapName 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);
+ value = actionPolicyDict.getAttributeName();
+ policyList = searchElkDatabase(action, "actionAttributeValue",value);
+ break;
+ case brmsParam :
+ BRMSParamTemplate 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);
+ value = pEPOptions.getPepName();
+ policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value);
+ break;
+ case clSite :
+ ClosedLoopSite 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);
+ value = closedLoopD2Services.getServiceName();
+ policyList = searchElkDatabase(closedloop, "pholder",value);
+ break;
+ case clVarbind :
+ VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
+ value = varbindDictionary.getVarbindName();
+ policyList = searchElkDatabase(closedloop, "jsonBodyData.triggerSignaturesUsedForUI.signatures",value);
+ break;
+ case clVnf :
+ VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
+ value = vNFType.getVnftype();
+ policyList = searchElkDatabase(closedloop, "jsonBodyData.vnfType",value);
+ break;
+ case clVSCL :
+ VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
+ value = vsclAction.getVsclaction();
+ policyList = searchElkDatabase(closedloop, "jsonBodyData.actions",value);
+ break;
+ case decision :
+ DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
+ value = decisionSettings.getXacmlId();
+ policyList = searchElkDatabase(decision,"pholder",value);
+ break;
+ case fwTerm :
+ TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
+ value = term.getTermName();
+ policyList = searchElkDatabase(config, "pholder",value);
+ break;
+ case msDCAEUUID :
+ DCAEuuid 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);
+ value = mslocation.getName();
+ policyList = searchElkDatabase(config, "location",value);
+ break;
+ case msModels :
+ MicroServiceModels msModels = (MicroServiceModels)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);
+ value = groupPoilicy.getGroupName();
+ policyList = searchElkDatabase(config, "pholder",value);
+ break;
+ case safeRisk :
+ RiskType 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);
+ 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(e.getMessage());
+ }
+ 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);
+ }
+
+}
+
+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;
+ }
+}
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
new file mode 100644
index 000000000..58c89f781
--- /dev/null
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.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 + "|" + "]";
+
+ }
+}