diff options
Diffstat (limited to 'ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk')
7 files changed, 2325 insertions, 0 deletions
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java new file mode 100644 index 000000000..1fd95abd4 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.policy.pap.xacml.rest.elk.client; + + +import java.util.ArrayList; + +import org.openecomp.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 JestResult policy(String policyId) + throws IllegalStateException, IllegalArgumentException; + + public boolean delete(PolicyRestAdapter policyData) + throws IllegalStateException; + + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType type, String text,int connector) + throws IllegalStateException, IllegalArgumentException; + + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s,int connector) + throws IllegalStateException, IllegalArgumentException; + + public JestResult search(PolicyIndexType type, String text) + throws IllegalStateException, IllegalArgumentException; + + public JestResult search(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) + throws IllegalStateException, IllegalArgumentException; + + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; + + public ElkConnector singleton = new ElkConnectorImpl(); + + public static PolicyIndexType toPolicyIndexType(PolicyType type) + throws IllegalArgumentException { + if (type == null) + throw new IllegalArgumentException("Unsupported NULL type conversion"); + + switch(type) { + case Config: + return PolicyIndexType.config; + case Action: + return PolicyIndexType.action; + case Decision: + return PolicyIndexType.decision; + case Config_Fault: + return PolicyIndexType.closedloop; + case Config_PM: + return PolicyIndexType.closedloop; + case Config_FW: + return PolicyIndexType.config; + case Config_MS: + return PolicyIndexType.config; + case none: + return PolicyIndexType.all; + default: + throw new IllegalArgumentException("Unsupported type conversion to index: " + type.name()); + } + } + + 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); + } + } + + public static PolicyType toPolicyType(String policyName) + throws IllegalArgumentException { + if (policyName == null) + throw new IllegalArgumentException("Unsupported NULL policy name conversion to Policy Type"); + + if (policyName.startsWith("Config_Fault")) { + return PolicyType.Config_Fault; + } else if (policyName.startsWith("Config_PM")) { + return PolicyType.Config_PM; + } else if (policyName.startsWith("Config_FW")) { + return PolicyType.Config_FW; + } else if (policyName.startsWith("Config_MS")) { + return PolicyType.Config_MS; + }else if (policyName.startsWith("Action")) { + return PolicyType.Action; + } else if (policyName.startsWith("Decision")) { + return PolicyType.Decision; + } else if (policyName.startsWith("Config")) { + return PolicyType.Config; + } else { + throw new IllegalArgumentException + ("Unsupported policy name conversion to index: " + + policyName); + } + } + +} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java new file mode 100644 index 000000000..5a64ec2b7 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -0,0 +1,845 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.policy.pap.xacml.rest.elk.client; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +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.kohsuke.args4j.Option; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +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.Get; +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{ + + protected static class CLIOptions { + @Option(name="-s", usage="search", aliases={"-search", "--search"}, required=false, metaVar="<search text>") + protected String searchText; + + @Option(name="-e", usage="test and update policy if not exists", aliases={"-exist", "--exists"}, required=false, metaVar="<policy file>") + protected File testFile; + + @Option(name = "-h", aliases = {"-help", "--help"}, usage = "print this message") + private boolean help = false; + }; + + private static final String POLICY_RESULT_FIELDS = "[ \"Policy.PolicyType\", " + + "\"Policy.PolicyName\", " + + "\"Policy.Owner\", " + + "\"Policy.Scope\", " + + "\"Policy.PolicyId\", " + + "\"Policy.Version\" ]"; + + private static final String SOURCE_RESULT_FIELDS = "\"_source\": " + POLICY_RESULT_FIELDS; + + 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"); + } + + // MatchQueryBuilder mQ = QueryBuilders.matchQuery("_all", text); + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery(text); + SearchSourceBuilder searchSourceBuilder = + new SearchSourceBuilder().query(mQ). + fetchSource(new String[]{"Policy.PolicyType", + "Policy.PolicyName", + "Policy.Owner", + "Policy.Scope", + "Policy.PolicyId", + "Policy.Version"}, + null); + 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; + } + + public JestResult searchKey(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s,int connector) + 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 = ""; + + if(connector==0)// AND CONNECTOR + { + matches_s = "{\n" + + " " + SOURCE_RESULT_FIELDS + ",\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"must\" : ["; + } + else if (connector ==1)//OR CONNECTOR + { + matches_s = "{\n" + + " " + SOURCE_RESULT_FIELDS + ",\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"should\" : ["; + } + + for (Pair<ArrayList<String>,ArrayList<String>> p : filter_s) { + ArrayList<String> name_s = p.left(); + ArrayList<String> value_s = p.right(); + + if (name_s == null || name_s.size() <= 0) { + if (LOGGER.isWarnEnabled()){ + LOGGER.warn("Defaulting to text search: Empty field name array passed in"); + } + return search(type, text); + } + + if (LOGGER.isDebugEnabled()) { + for (String n: name_s) { + LOGGER.debug("Filter Name: " + n); + } + } + + if (value_s == null || value_s.size() <= 0) { + if (LOGGER.isWarnEnabled()){ + LOGGER.warn("Defaulting to text search: Empty field value array passed in"); + } + return search(type, text); + } + + if (LOGGER.isDebugEnabled()) { + for (String v: value_s) { + LOGGER.debug("Filter Value: " + v); + } + } + + /* common case: # filter names == # filter values */ + if (name_s.size() == value_s.size()) { + String match = ""; + for (int i=0; i<name_s.size(); i++) { + if (name_s.get(i).contains("*")) { + match = + "{ \"query_string\": { \"fields\": [ \"" + + name_s.get(i) + "\" ], " + + "\"query\" : \"" + + value_s.get(i) + "\" } },"; + } else { + match = + "{ \"match_phrase\": { \"" + + name_s.get(i) + "\" : \"" + + value_s.get(i) + "\" } },"; + } + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("Adding Match Line: " + match); + } + matches_s = matches_s + "\n " + match; + } + } + else if (name_s.size() > value_s.size() && (value_s.size() == 1)) { + String match = + "{ \"multi_match\": { \"query\": \"" + value_s.get(0) + "\", \"type\": \"phrase\", \"fields\": ["; + for (String n: name_s) { + match += " \"" + n + "\","; + } + match = match.substring(0, match.length()-1); + match += " ] } },";//debug + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("Adding Match Line: " + match); + } + matches_s = matches_s + "\n " + match; + } else { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("Defaulting to text search: different number of filter names and values"); + return search(type, text); + } + } + + matches_s = matches_s.substring(0, matches_s.length()-1); // remove last comma + + matches_s = matches_s + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(matches_s); + } + + 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; + } + + @Override + public JestResult search(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<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" + + " " + SOURCE_RESULT_FIELDS + ",\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"must\" : ["; + for (Pair<ArrayList<String>,ArrayList<String>> p : filter_s) { + ArrayList<String> name_s = p.left(); + ArrayList<String> value_s = p.right(); + + if (name_s == null || name_s.size() <= 0) { + if (LOGGER.isWarnEnabled()){ + LOGGER.warn("Defaulting to text search: Empty field name array passed in"); + } + return search(type, text); + } + + if (LOGGER.isDebugEnabled()) { + for (String n: name_s) { + LOGGER.debug("Filter Name: " + n); + } + } + + if (value_s == null || value_s.size() <= 0) { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("Defaulting to text search: Empty field value array passed in"); + return search(type, text); + } + + if (LOGGER.isDebugEnabled()) { + for (String v: value_s) { + LOGGER.debug("Filter Value: " + v); + } + } + + /* common case: # filter names == # filter values */ + if (name_s.size() == value_s.size()) { + String match = ""; + for (int i=0; i<name_s.size(); i++) { + if (name_s.get(i).contains("*")) { + match = + "{ \"query_string\": { \"fields\": [ \"" + + name_s.get(i) + "\" ], " + + "\"query\" : \"" + + value_s.get(i) + "\" } },"; + } else { + match = + "{ \"match_phrase\": { \"" + + name_s.get(i) + "\" : \"" + + value_s.get(i) + "\" } },"; + } + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("Adding Match Line: " + match); + } + matches_s = matches_s + "\n " + match; + } + } else if (name_s.size() > value_s.size() && (value_s.size() == 1)) { + String match = + "{ \"multi_match\": { \"query\": \"" + value_s.get(0) + "\", \"type\": \"phrase\", \"fields\": ["; + for (String n: name_s) { + match += " \"" + n + "\","; + } + match = match.substring(0, match.length()-1); + match += " ] } },"; + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("Adding Match Line: " + match); + } + matches_s = matches_s + "\n " + match; + } else { + if (LOGGER.isWarnEnabled()){ + LOGGER.warn("Defaulting to text search: different number of filter names and values"); + } + return search(type, text); + } + } + if (text != null && !text.isEmpty()) { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("Adding Match Line for search text: " + text); + } + + final JsonObject jsonText = new JsonObject(); + jsonText.addProperty("_all", text); + String escapedText = jsonText.toString(); + + matches_s = matches_s + "\n " + + "{ \"match\": " + + escapedText + " },"; + } + matches_s = matches_s.substring(0, matches_s.length()-1); // remove last comma + matches_s = matches_s + "\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(matches_s); + } + + 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; + } + + @Override + public JestResult policy(String policyId) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()){ + LOGGER.trace("ENTER: " + policyId); + } + + if (policyId == null || policyId.isEmpty()) { + throw new IllegalArgumentException("No policy id string provided"); + } + + Get policyRequest = new Get.Builder(ELK_INDEX_POLICY, policyId).build(); + + if (LOGGER.isInfoEnabled()){ + LOGGER.info("ELK Search body request: " + policyRequest.toString()); + } + + JestResult result; + try { + result = jestClient.execute(policyRequest); + } catch (IOException ioe) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + policyId + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()){ + LOGGER.info("OK:" + result.getResponseCode() + ":" + policyId + ":" + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } + + return result; + } + + /* Unsuccessful search */ + if (LOGGER.isWarnEnabled()) + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + policyId + ":" + + result.getPathToResult() + ":" + + result.getErrorMessage()); + + return result; + } + + protected JsonObject getJsonObject(JsonObject jsonObject, String member) throws IllegalArgumentException { + if (jsonObject == null) { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("No JSON object provided to get " + member); + + throw new IllegalArgumentException("No JSON Object provided"); + } + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("ENTER: " + member); + for (Entry<String, JsonElement> entry: jsonObject.entrySet()) { + LOGGER.trace("JSONOBJECT: " + entry.getKey() + "->" + entry.getValue()); + } + } + + if (jsonObject.has(member)) { + JsonElement element = jsonObject.getAsJsonObject(member); + if (element.isJsonObject()) { + return (JsonObject) element; + } + } + + throw new IllegalArgumentException(member + " is not a JSON Object"); + } + + protected JsonArray getJsonArray(JsonObject jsonObject, String member) throws IllegalArgumentException { + if (jsonObject == null) { + throw new IllegalArgumentException("No JSON Object provided"); + } + + if (jsonObject.has(member)) { + if (jsonObject.get(member).isJsonArray()) { + return (JsonArray) jsonObject.get(member); + } + } + + throw new IllegalArgumentException(member + " is not a JSON Array"); + } + + protected String getJsonPolicyMember(JsonObject aHit, String member) throws IllegalArgumentException { + if (aHit == null) { + throw new IllegalArgumentException("No JSON Object provided"); + } + + JsonObject jSource = getJsonObject(aHit, "_source"); + JsonObject jPolicy = getJsonObject(jSource, "Policy"); + JsonElement jMember = jPolicy.get(member); + if (jMember == null) { + throw new IllegalArgumentException(member + " is not a JSON Object"); + } + return jMember.getAsString(); + } + + @Override + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType indexType, String text, int connector) + throws IllegalStateException, IllegalArgumentException { + return policyLocators(indexType, text, new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(),connector); + } + + @Override + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType indexType, + String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s, int connector) + throws IllegalStateException, IllegalArgumentException { + final ArrayList<PolicyLocator> policyLocators = new ArrayList<PolicyLocator>(); + + JestResult results = searchKey(indexType, text, filter_s,connector); + if (!results.isSucceeded()) { + return policyLocators; + } + + JsonArray jsonHit_s = null; + try { + JsonObject jsonHits = getJsonObject(results.getJsonObject(), "hits"); + jsonHit_s = getJsonArray(jsonHits, "hits"); + } catch (IllegalArgumentException e) { + LOGGER.warn("SEARCH:" + text + " no valid element provided", e); + return policyLocators; + } + + for (JsonElement e : jsonHit_s) { + JsonObject elkSource = (JsonObject) e; + try { + String policyType = getJsonPolicyMember(elkSource,"PolicyType"); + String policyName = getJsonPolicyMember(elkSource,"PolicyName"); + String owner = getJsonPolicyMember(elkSource,"Owner"); + String scope = getJsonPolicyMember(elkSource,"Scope"); + String policyId = getJsonPolicyMember(elkSource,"PolicyId"); + String version = getJsonPolicyMember(elkSource,"Version"); + PolicyLocator policyLocator = + new PolicyLocator(policyType, policyName, owner, + scope, policyId, version); + policyLocators.add(policyLocator); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("SEARCH:" + text + "|FOUND:" + policyLocator); + } + } catch (IllegalArgumentException ex) { + LOGGER.warn("SEARCH:" + text + " missing locator information.", ex); + } + } + return policyLocators; + } + + 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) ? indexType.name() : "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/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java new file mode 100644 index 000000000..cf4cecbb4 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.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/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java new file mode 100644 index 000000000..f0783529a --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java @@ -0,0 +1,550 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.policy.pap.xacml.rest.elk.client; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; + +public class PolicyElasticData { + + private String scope; + private String policyType; + private String configPolicyType; + private String policyName; + private String policyDescription; + private String ecompName; + private String configName; + private String configType; + private String jsonBody; + + //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; + + public PolicyElasticData(PolicyRestAdapter policyData) { + this.scope = policyData.getDomain(); + this.policyType = policyData.getPolicyType(); + this.configPolicyType = policyData.getConfigPolicyType(); + this.policyName = policyData.getNewFileName(); + this.policyDescription = policyData.getPolicyDescription(); + this.ecompName = policyData.getEcompName(); + this.configName = policyData.getConfigName(); + this.configType = policyData.getConfigType(); + this.jsonBody = policyData.getJsonBody(); + + //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(); + } + + 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 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 getEcompName() { + return ecompName; + } + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + 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 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; + } + +} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java new file mode 100644 index 000000000..9e512dab2 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -0,0 +1,603 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.policy.pap.xacml.rest.elk.client; + + +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; +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 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.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.ActionPolicyDict; +import org.openecomp.policy.rest.jpa.Attribute; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; +import org.openecomp.policy.rest.jpa.ClosedLoopD2Services; +import org.openecomp.policy.rest.jpa.ClosedLoopSite; +import org.openecomp.policy.rest.jpa.DCAEuuid; +import org.openecomp.policy.rest.jpa.DecisionSettings; +import org.openecomp.policy.rest.jpa.DescriptiveScope; +import org.openecomp.policy.rest.jpa.EcompName; +import org.openecomp.policy.rest.jpa.EnforcingType; +import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; +import org.openecomp.policy.rest.jpa.MicroServiceLocation; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.openecomp.policy.rest.jpa.PEPOptions; +import org.openecomp.policy.rest.jpa.RiskType; +import org.openecomp.policy.rest.jpa.SafePolicyWarning; +import org.openecomp.policy.rest.jpa.TermList; +import org.openecomp.policy.rest.jpa.VNFType; +import org.openecomp.policy.rest.jpa.VSCLAction; +import org.openecomp.policy.rest.jpa.VarbindDictionary; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class PolicyElasticSearchController{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); + private volatile HashMap<Path, String> filteredPolicies = new HashMap<Path, String>(); + private List<JSONObject> policyNames = null; + + enum Mode{ + attribute, ecompName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, enforcer, 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; + }; + //For AND and OR logical connector AND=0 and OR=1 + private int connectorSelected; + + public static CommonClassDao commonClassDao; + + 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); + } + + protected void clSearchBody(String clPolicyType, String bodyField, String bodyValue, + ArrayList<Pair<ArrayList<String>, ArrayList<String>>> filter_s) { + if (LOGGER.isDebugEnabled()) + LOGGER.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue); + + final ArrayList<String> clBodyField_s = new ArrayList<String>(); + final ArrayList<String> clBodyValue_s = new ArrayList<String>(); + + if (clPolicyType == null || clPolicyType.isEmpty()) { + clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField); + clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } else { + clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } + filter_s.add(new Pair<ArrayList<String>, ArrayList<String>>(clBodyField_s, clBodyValue_s)); + } + + protected void clSearchFilter(String clType, String clField, String clValue, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) { + if (LOGGER.isDebugEnabled()) + LOGGER.debug("ENTER: " + clType + ":" + clField + ":" + clValue); + + ArrayList<String> clSearchField_s = new ArrayList<String>(); + clSearchField_s.add("Policy.Body." + clType + "_Body." + clField); + + ArrayList<String> clSearchValue_s = new ArrayList<String>(); + clSearchValue_s.add(clValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchField_s, clSearchValue_s)); + } + + 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={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + 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; + @SuppressWarnings("unused") + String msg; + switch (mode){ + case attribute : + Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); + value = attributedata.getXacmlId(); + msg = searchElkDatabase("pholder",value); + break; + case ecompName : + EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class); + value = ecompName.getEcompName(); + msg = searchElkDatabase("pholder",value); + break; + case actionPolicy : + ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + value = actionPolicyDict.getAttributeName(); + msg = searchElkDatabase("pholder",value); + break; + case brmsParam : + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + value = bRMSParamTemplate.getRuleName(); + msg = searchElkDatabase("BRMSParamTemplate AND " + value); + break; + case pepOptions : + PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); + value = pEPOptions.getPepName(); + msg = searchElkDatabase("pepName",value); + break; + case clSite : + ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + value = closedLoopSite.getSiteName(); + msg = searchElkDatabase("siteNames",value); + break; + case clService : + ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + value = closedLoopD2Services.getServiceName(); + msg = searchElkDatabase("d2Services",value); + break; + case clVarbind : + VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + value = varbindDictionary.getVarbindName(); + msg = searchElkDatabase("triggerSignaturesUsedForUI.signatures",value); + break; + case clVnf : + VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); + value = vNFType.getVnftype(); + msg = searchElkDatabase("vnfType",value); + break; + case clVSCL : + VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); + value = vsclAction.getVsclaction(); + msg = searchElkDatabase("actions",value); + break; + case decision : + DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); + value = decisionSettings.getXacmlId(); + msg = searchElkDatabase("pholder",value); + break; + case enforcer : + EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class); + value = enforcingType.getEnforcingType(); + msg = searchElkDatabase("pholder",value); + break; + case fwTerm : + TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); + value = term.getTermName(); + msg = searchElkDatabase("firewallRuleList.ruleName",value); + break; + case msDCAEUUID : + DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); + value = dcaeUUID.getName(); + msg = searchElkDatabase("uuid",value); + break; + case msLocation : + MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + value = mslocation.getName(); + msg = searchElkDatabase("location",value); + break; + case msModels : + MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + value = msModels.getModelName(); + msg = searchElkDatabase("configName",value); + break; + case psGroupPolicy : + GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + value = groupPoilicy.getGroupName(); + msg = searchElkDatabase("PolicyScope",value); + break; + case safeRisk : + RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class); + value = riskType.getRiskName(); + msg = searchElkDatabase("Risk Type",value); + break; + case safePolicyWarning : + SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + value = safePolicy.getName(); + msg = searchElkDatabase("Safe Warning",value); + break; + default: + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + policyNames + "}"); + out.write(j.toString()); + return null; + }catch(Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + //Search Elk database + public String searchElkDatabase(String value){ + String policyType = ""; + String searchText = value; + ArrayList<PolicyLocator> locators; + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0); + } catch (Exception ise) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage()); + value = "$notSuccess%"; + return value; + } + policyNames = new ArrayList<JSONObject>(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName + "." +p.version + ".xml"; + LOGGER.debug(dbPolicyName); + JSONObject el = new JSONObject(); + el.put("name", dbPolicyName); + policyNames.add(el); + } + if(!locators.isEmpty()){ + value = "$success%"; + return value; + } + return value; + } + + //Search the Elk database + public String searchElkDatabase(String key, String value){ + String policyType = ""; + String searchText = key+":"+value; + ArrayList<PolicyLocator> locators; + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + LOGGER.debug("Parameter value is"+value); + + String clSearchKey=null; + clSearchKey=key; + + LOGGER.debug("Filter value is"+clSearchKey); + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchKey); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchKey); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchKey); + //clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey); + + String clSearchValue=null; + clSearchValue=value; + + LOGGER.debug("Search value is"+clSearchValue); + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(clSearchValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0); + LOGGER.debug("No Exceptions"); + for (PolicyLocator l: locators) { + LOGGER.debug(l.policyName); + } + LOGGER.debug("After for"); + } catch (Exception ise) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage()); + //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ise, "AttributeDictionary", " Exception while searching Elk database "); + LOGGER.debug("Exceptions"); + value = "$notSuccess%"; + return value; + } + policyNames = new ArrayList<JSONObject>(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + File.separator + p.policyType + "_" + p.policyName + ".xml"; + LOGGER.debug(dbPolicyName); + JSONObject el = new JSONObject(); + el.put("name", dbPolicyName); + policyNames.add(el); + } + if(!locators.isEmpty()){ + value = "$success%"; + LOGGER.debug("Success"); + return value; + } + return value; + } + + //For AutoPush of policy using descriptive Scope. + //Returns string either "UnMatched" or "Matched" or "Search Unavailable". + public String searchDescriptiveScope(String scopeName, String policyNameToCheck) { + String searchText=null; + String status="UnMatched"; + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = + new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + //Finding the descriptive scope search tag. + LOGGER.warn("Entry into DS"); + DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", scopeName); + + searchText=dsSearch.getSearch(); + LOGGER.warn("Search text is " + searchText); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("DescriptiveScope Search String is " +searchText ); + } + + + if(searchText.contains(":")) + { + String connector="AND"; + + for (String retval: searchText.split(connector)){ + + int index= retval.indexOf(':'); + String filterKey=null; + String filterValue=null; + + filterKey=retval.substring(0,index).trim(); + filterValue= retval.substring(index+1).trim(); + + LOGGER.debug("Key is "+filterKey+" and value is "+filterValue); + String clSearchBoxFilter=filterKey; + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter); + + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(filterValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + } + } + + ArrayList<PolicyLocator> locators=null; + try { + LOGGER.warn("Before calling search"); + locators = ElkConnector.singleton.policyLocators(ElkConnector.PolicyIndexType.all, + searchText, filter_s,connectorSelected); + LOGGER.warn("After calling search"); + } catch (Exception ise) { + //AdminNotification.warn("Search is unavailable: " + ise.getMessage()); + status= "Search Unavailable"; + LOGGER.warn("Search is unavailable"); + } + synchronized(filteredPolicies) { + if (locators.isEmpty()) { + LOGGER.debug("No match has been found"); + //AdminNotification.warn("No match has been found"); + status="UnMatched"; + } + + for (PolicyLocator p: locators) { + LOGGER.debug("Second String "+policyNameToCheck); + if(p.policyName.contains(policyNameToCheck)) + { + status="Matched"; + LOGGER.warn("Policies matched"); + break; + } + else + { + LOGGER.warn("Policies Unmatched"); + status="UnMatched"; + } + } + } + return status; + + } +} + +class SearchData{ + private String query; + private String policyType; + private String descriptiveScope; + private String closedLooppolicyType; + private String ecompName; + 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 getEcompName() { + return ecompName; + } + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + 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/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java new file mode 100644 index 000000000..f246c9b15 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.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 + "|" + "]"; + + } +} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java new file mode 100644 index 000000000..91f97cae3 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-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.openecomp.policy.pap.xacml.rest.elk.client; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PolicySearchController { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicySearchController.class); + + @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) + public void elkTransaction(HttpServletRequest request, HttpServletResponse response) { + try{ + boolean result = false; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter policyData = new PolicyRestAdapter(); + if(request.getParameter("policyName") != null){ + String policyName = request.getParameter("policyName"); + policyData.setNewFileName(policyName); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + if("delete".equalsIgnoreCase(request.getParameter("action"))){ + result = controller.deleteElk(policyData); + }else{ + result = controller.updateElk(policyData); + } + } + 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"); + response.getWriter().write(j.toString()); + }catch(Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); + LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage()); + e.printStackTrace(); + } + } + +} |