From: ARUL NAMBI Date: Tue, 1 Aug 2017 13:15:32 +0000 (-0400) Subject: Adding support for external microservice X-Git-Tag: v1.1.0~23 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=aai%2Fdata-router.git;a=commitdiff_plain;h=6cb28e580a3d3e308de77b2e7b239cae3912dd7f Adding support for external microservice Change-Id: I96fa079d70b9f9b5f48b0c1c24801f3624babe4a Signed-off-by: ARUL NAMBI --- diff --git a/src/main/java/org/openecomp/datarouter/entity/SuggestionSearchEntity.java b/src/main/java/org/openecomp/datarouter/entity/SuggestionSearchEntity.java index ae2711b..82e2fa9 100644 --- a/src/main/java/org/openecomp/datarouter/entity/SuggestionSearchEntity.java +++ b/src/main/java/org/openecomp/datarouter/entity/SuggestionSearchEntity.java @@ -34,48 +34,86 @@ import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; +import org.openecomp.datarouter.search.filters.config.UiFilterConfig; +import org.openecomp.datarouter.search.filters.config.UiFiltersConfig; +import org.openecomp.datarouter.search.filters.config.UiFiltersSchemaUtility; import org.openecomp.datarouter.util.NodeUtils; +import org.openecomp.datarouter.util.SearchSuggestionPermutation; import com.fasterxml.jackson.databind.JsonNode; public class SuggestionSearchEntity implements DocumentStoreDataEntity, Serializable { private static final long serialVersionUID = -3636393943669310760L; + private static final String FILTER_ID = "filterId"; + private static final String FILTER_VALUE = "filterValue"; + private static final String FILTER_LIST = "filterList"; + protected String id; // generated SHA-256 digest private String entityType; private List entityTypeAliases; private List suggestionInputPermutations = new ArrayList<>(); private List statusPermutations = new ArrayList<>(); private List suggestableAttr = new ArrayList<>(); - private Map payload = new HashMap<>(); - private JSONObject payloadJsonNode = new JSONObject(); - private StringBuffer outputString = new StringBuffer(); + + private Map inputOutputData = new HashMap<>(); + private Map filters = new HashMap<>(); + private JSONObject filterPayload = new JSONObject(); + private StringBuffer searchSuggestionDisplayString = new StringBuffer(); + private JSONArray payloadFilters = new JSONArray(); + private UiFiltersSchemaUtility filtersSchemaUtility = new UiFiltersSchemaUtility(); + + public SuggestionSearchEntity() { + UiFiltersConfig filterConfigList = filtersSchemaUtility.loadUiFiltersConfig(); + + // Populate the map with keys that will match the suggestableAttr values + for (UiFilterConfig filter : filterConfigList.getFilters()) { + if (filter.getDataSource() != null) { + filters.put(filter.getDataSource().getFieldName(), filter); + } + } + } - public void deriveFields() throws NoSuchAlgorithmException { + /** + * Create the search suggestion string to display to the user in the search suggestion drop-down + * + * @throws NoSuchAlgorithmException + */ + public void generateSearchSuggestionDisplayStringAndId() throws NoSuchAlgorithmException { int payloadEntryCounter = 1; - for (Map.Entry payload : getPayload().entrySet()) { - if (payload.getValue() != null && payload.getValue().length() > 0) { - this.getPayloadJsonNode().put(payload.getKey(), payload.getValue()); - this.outputString.append(payload.getValue()); + for (Map.Entry outputValue : inputOutputData.entrySet()) { + if (outputValue.getValue() != null && outputValue.getValue().length() > 0) { + this.searchSuggestionDisplayString.append(outputValue.getValue()); - if (payloadEntryCounter < getPayload().entrySet().size()) { - this.outputString.append(" and "); + if (payloadEntryCounter < inputOutputData.entrySet().size()) { + this.searchSuggestionDisplayString.append(" and "); } else { - this.outputString.append(" "); + this.searchSuggestionDisplayString.append(" "); } } payloadEntryCounter++; } - this.outputString.append(getEntityTypeAliases().get(0)); - this.id = NodeUtils.generateUniqueShaDigest(outputString.toString()); + this.searchSuggestionDisplayString.append(getEntityTypeAliases().get(0)); + generateSearchSuggestionId(searchSuggestionDisplayString.toString()); + } + + /** + * Generates an ID by encrypting the string to display to the user in the search suggestion + * drop-down + * + * @param outputString The string to create the encrypted ID from + */ + private void generateSearchSuggestionId(String searchSuggestionDisplayString) { + this.id = NodeUtils.generateUniqueShaDigest(searchSuggestionDisplayString); } /** * Launch pad for performing permutations of the entity type, aliases, prov status and orchestration status. - * SHA-256 will result in an ID with a guaranteed uniqueness compared to just a java hashcode value. + * SHA-256 will result in an ID with a guaranteed uniqueness compared to just a java hashcode value + * * @return */ public List generateSuggestionInputPermutations() { @@ -88,24 +126,75 @@ public class SuggestionSearchEntity implements DocumentStoreDataEntity, Serializ } } - ArrayList listToPermutate = new ArrayList<>(statusPermutations); - ArrayList listOfSearchSuggestionPermutations = new ArrayList<>(); + ArrayList listOfSearchSuggestionPermutations = new ArrayList(); + ArrayList listToPermutate = + new ArrayList<>(this.getInputOutputData().values()); for (String entityName : entityNames) { listToPermutate.add(entityName); - permutateList(listToPermutate, new ArrayList(), listToPermutate.size(), listOfSearchSuggestionPermutations); + List> lists = SearchSuggestionPermutation.getListPermutations(listToPermutate); + for (List li : lists){ + listOfSearchSuggestionPermutations.add(String.join(" ", li)); + } listToPermutate.remove(entityName); } return listOfSearchSuggestionPermutations; } + /** + * Return a custom JSON representation of this class + */ + @Override + public String getAsJson() throws IOException { + if (entityType == null || suggestionInputPermutations == null) { + return null; + } + + JSONObject rootNode = new JSONObject(); + JSONArray inputArray = new JSONArray(); + JSONObject payloadNode = new JSONObject(); + StringBuffer outputString = new StringBuffer(); + + int payloadEntryCounter = 1; + + // Add prov and orchestration status to search suggestion string + for (Map.Entry payload : inputOutputData.entrySet()) { + payloadNode.put(payload.getKey(), payload.getValue()); + outputString.append(payload.getValue()); + + if (payloadEntryCounter < inputOutputData.entrySet().size()) { + // Add the word "and" between prov and orchestration statuses, if both are present + outputString.append(" and "); + payloadEntryCounter++; + } + } + + /* Add entity type to search suggestion string. We've decided to use the first entity type alias + * from the OXM */ + outputString.append(" ").append(getEntityTypeAliases().get(0)); + + for (String permutation : suggestionInputPermutations) { + inputArray.put(permutation); + } + + // Build up the search suggestion as JSON + JSONObject entitySuggest = new JSONObject(); + entitySuggest.put("input", inputArray); + entitySuggest.put("output", outputString); + entitySuggest.put("payload", this.filterPayload); + rootNode.put("entity_suggest", entitySuggest); + + return rootNode.toString(); + } + public boolean isSuggestableDoc() { - return this.getPayload().size() != 0; + return this.getFilterPayload().length() != 0; } - + /** * Generate all permutations of Entity Type and (Prov Status and/or Orchestration Status) + * * @param list The list of unique elements to create permutations of * @param permutation A list to hold the current permutation used during * @param size To keep track of the original size of the number of unique elements @@ -137,48 +226,51 @@ public class SuggestionSearchEntity implements DocumentStoreDataEntity, Serializ } /** - * return Custom-built JSON representation of this class + * Populate a string that will represent the UI filters portion of the JSON payload that's stored in the + * search engine + * + * @param entityFromUebEvent + * @param suggestibleAttrInPayload */ - @Override - public String getAsJson() throws IOException { - if (entityType == null || suggestionInputPermutations == null) { - return null; - } - - JSONObject rootNode = new JSONObject(); - JSONArray inputArray = new JSONArray(); - JSONObject payloadNode = new JSONObject(); - StringBuffer outputString = new StringBuffer(); - - int payloadEntryCounter = 1; - - // Add prov and orchestration status to search suggestion string - for (Map.Entry payload : getPayload().entrySet()) { - payloadNode.put(payload.getKey(), payload.getValue()); - outputString.append(payload.getValue()); - - if (payloadEntryCounter < getPayload().entrySet().size()) { - // Add the word "and" between prov and orchestration statuses, if both are present - outputString.append(" and "); - payloadEntryCounter++; + public void setFilterBasedPayloadFromResponse(JsonNode entityFromUebEvent, + List suggestibleAttrInOxm, List suggestibleAttrInPayload) { + if (suggestibleAttrInOxm != null) { + for (String attribute : suggestibleAttrInOxm) { + UiFilterConfig filterConfig = filters.get(attribute); + + if (suggestibleAttrInPayload.contains(attribute)) { + inputOutputData.put(attribute, entityFromUebEvent.get(attribute).asText()); + + if(filterConfig != null) { + JSONObject filterPayload = new JSONObject(); + filterPayload.put(FILTER_ID, filterConfig.getFilterId()); + filterPayload.put(FILTER_VALUE, entityFromUebEvent.get(attribute).asText()); + this.payloadFilters.put(filterPayload); + } else { + this.filterPayload.put(attribute, entityFromUebEvent.get(attribute).asText()); + } + } else { + if(filterConfig != null) { + JSONObject emptyValueFilterPayload = new JSONObject(); + emptyValueFilterPayload.put(FILTER_ID, filterConfig.getFilterId()); + this.payloadFilters.put(emptyValueFilterPayload); + } + } } - } - - // Add entity type to search suggestion string. We've decided to use the first entity type alias from the OXM - outputString.append(" ").append(getEntityTypeAliases().get(0)); - for (String permutation : suggestionInputPermutations) { - inputArray.put(permutation); + this.filterPayload.put(FILTER_LIST, this.payloadFilters); } + } - // Build up the search suggestion as JSON - JSONObject entitySuggest = new JSONObject(); - entitySuggest.put("input", inputArray); - entitySuggest.put("output", outputString); - entitySuggest.put("payload", payloadNode); - rootNode.put("entity_suggest", entitySuggest); - - return rootNode.toString(); + public void setPayloadFromResponse(JsonNode node) { + if (suggestableAttr != null) { + for (String attribute : suggestableAttr) { + if (node.get(attribute) != null) { + inputOutputData.put(attribute, node.get(attribute).asText()); + this.filterPayload.put(attribute, node.get(attribute).asText()); + } + } + } } public String getEntityType() { @@ -202,65 +294,55 @@ public class SuggestionSearchEntity implements DocumentStoreDataEntity, Serializ return id; } - public void setId(String id) { - this.id = id; + public StringBuffer getSearchSuggestionDisplayString() { + return searchSuggestionDisplayString; } - public StringBuffer getOutputString() { - return outputString; + public JSONObject getFilterPayload() { + return filterPayload; } - public void setOutputString(StringBuffer outputString) { - this.outputString = outputString; + public List getStatusPermutations() { + return statusPermutations; } - public Map getPayload() { - return payload; + public List getSuggestableAttr() { + return suggestableAttr; } - public void setPayloadFromResponse(JsonNode node) { - Map nodePayload = new HashMap<>(); - JsonNode entityNode = node.get("entity"); - if (suggestableAttr != null) { - for (String attribute : suggestableAttr) { - if (entityNode.get(attribute) != null && !entityNode.get(attribute).asText().trim().isEmpty()) { - nodePayload.put(attribute, entityNode.get(attribute).asText()); - this.statusPermutations.add(entityNode.get(attribute).asText()); - } - } - this.setPayload(nodePayload); - } + public List getSuggestionInputPermutations() { + return this.suggestionInputPermutations; } - public void setPayload(Map payload) { - this.payload = payload; + public void setId(String id) { + this.id = id; } - - public JSONObject getPayloadJsonNode() { - return payloadJsonNode; + + public void setInputOutputData(Map inputOutputData) { + this.inputOutputData = inputOutputData; } - public void setPayloadJsonNode(JSONObject payloadJsonNode) { - this.payloadJsonNode = payloadJsonNode; + public Map getInputOutputData() { + return inputOutputData; } - public List getStatusPermutations() { - return statusPermutations; + public void setSearchSuggestionDisplayString(StringBuffer searchSuggestionDisplayString) { + this.searchSuggestionDisplayString = searchSuggestionDisplayString; } - public List getSuggestableAttr() { - return suggestableAttr; + public void setFilterPayload(JSONObject filterPayload) { + this.filterPayload = filterPayload; } - - public List getSuggestionInputPermutations() { - return this.suggestionInputPermutations; + + public void setFiltersSchemaUtility(UiFiltersSchemaUtility filtersSchemaUtility) { + this.filtersSchemaUtility = filtersSchemaUtility; } public void setStatusPermutations(List statusPermutations) { this.statusPermutations = statusPermutations; } - public void setSuggestableAttr(ArrayList attributes) { + public void setSuggestableAttr(List attributes) { for (String attribute : attributes) { this.suggestableAttr.add(attribute); } @@ -275,7 +357,9 @@ public class SuggestionSearchEntity implements DocumentStoreDataEntity, Serializ return "SuggestionSearchEntity [id=" + id + ", entityType=" + entityType + ", entityTypeAliases=" + entityTypeAliases + ", suggestionInputPermutations=" + suggestionInputPermutations + ", statusPermutations=" + statusPermutations - + ", suggestableAttr=" + suggestableAttr + ", payload=" + payload + ", payloadJsonNode=" - + payloadJsonNode + ", outputString=" + outputString + "]"; + + ", suggestableAttr=" + suggestableAttr + ", inputOutputData=" + inputOutputData + + ", filters=" + filters + ", filterPayload=" + filterPayload + + ", searchSuggestionDisplayString=" + searchSuggestionDisplayString + ", payloadFilters=" + + payloadFilters + "]"; } } diff --git a/src/main/java/org/openecomp/datarouter/logging/DataRouterMsgs.java b/src/main/java/org/openecomp/datarouter/logging/DataRouterMsgs.java index 71a5d5d..6206b63 100644 --- a/src/main/java/org/openecomp/datarouter/logging/DataRouterMsgs.java +++ b/src/main/java/org/openecomp/datarouter/logging/DataRouterMsgs.java @@ -157,6 +157,21 @@ public enum DataRouterMsgs implements LogMessageEnum { INVALID_OXM_DIR, + /** + * Arguments: {0} = origin payload + */ + INVALID_ORIGIN_PAYLOAD, + + /** + * Arguments: {0} = Origin URL {1} = Target outbound URL + */ + ROUTING_FROM_TO, + + /** + * Arguments: {0} = Target outbound URL, {1} = Response + */ + ROUTING_RESPONSE, + /** * Failed to create or update document in index {0}. Cause: {1} * @@ -164,8 +179,19 @@ public enum DataRouterMsgs implements LogMessageEnum { * {0} = Index name * {1} = Failure cause */ - FAIL_TO_CREATE_UPDATE_DOC; + FAIL_TO_CREATE_UPDATE_DOC, + + /** + * Arguments: {0} = Operation, {1} = Time in ms + */ + OP_TIME, + /** Arguments: {0} = Schema file location */ + READING_JSON_SCHEMA_ERROR, + + /** Arguments: {0} = Error message */ + JSON_CONVERSION_ERROR; + /** * Static initializer to ensure the resource bundles for this class are loaded... */ diff --git a/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicy.java b/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicy.java index 3c3990e..4938bdd 100644 --- a/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicy.java +++ b/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicy.java @@ -24,13 +24,6 @@ */ package org.openecomp.datarouter.policy; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.sun.jersey.core.util.MultivaluedMapImpl; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -71,6 +64,7 @@ import org.openecomp.datarouter.util.CrossEntityReference; import org.openecomp.datarouter.util.DataRouterConstants; import org.openecomp.datarouter.util.EntityOxmReferenceHelper; import org.openecomp.datarouter.util.ExternalOxmModelProcessor; +import org.openecomp.datarouter.util.NodeUtils; import org.openecomp.datarouter.util.OxmModelLoader; import org.openecomp.datarouter.util.RouterServiceUtil; import org.openecomp.datarouter.util.SearchServiceAgent; @@ -80,10 +74,17 @@ import org.openecomp.datarouter.util.VersionedOxmEntities; import org.openecomp.restclient.client.Headers; import org.openecomp.restclient.client.OperationResult; import org.openecomp.restclient.client.RestClient; +import org.openecomp.restclient.enums.RestAuthenticationMode; import org.openecomp.restclient.rest.HttpUtil; -import org.openecomp.datarouter.util.NodeUtils; import org.slf4j.MDC; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sun.jersey.core.util.MultivaluedMapImpl; + public class EntityEventPolicy implements Processor { public static final String additionalInfo = "Response of AAIEntityEventPolicy"; @@ -255,9 +256,15 @@ public class EntityEventPolicy implements Processor { } // Load the UEB payload data, any errors will result in a failure and discard - JSONObject uebObjHeader = getUebHeaderAsJson(uebPayload); + JSONObject uebObjHeader = getUebContentAsJson(uebPayload, EVENT_HEADER); if (uebObjHeader == null) { - returnWithError(exchange, uebPayload, "Payload is missing event-header"); + returnWithError(exchange, uebPayload, "Payload is missing " + EVENT_HEADER); + return; + } + + JSONObject uebObjEntity = getUebContentAsJson(uebPayload, ENTITY_HEADER); + if (uebObjEntity == null) { + returnWithError(exchange, uebPayload, "Payload is missing " + ENTITY_HEADER); return; } @@ -561,9 +568,17 @@ public class EntityEventPolicy implements Processor { Map rootDescriptor = oxmEntities.getSuggestableEntityDescriptors(); if (!rootDescriptor.isEmpty()) { - List suggestibleAttributes = extractSuggestableAttr(oxmEntities, entityType); + List suggestibleAttrInPayload = new ArrayList(); + List suggestibleAttrInOxm = extractSuggestableAttr(oxmEntities, entityType); + if (suggestibleAttrInOxm != null) { + for (String attr: suggestibleAttrInOxm){ + if ( uebObjEntity.has(attr) ){ + suggestibleAttrInPayload.add(attr); + } + } + } - if (suggestibleAttributes == null) { + if (suggestibleAttrInPayload.isEmpty()) { return; } @@ -572,39 +587,38 @@ public class EntityEventPolicy implements Processor { ae.setLink(entityLink); ae.deriveFields(uebAsJson); - handleSuggestiveSearchData(ae, action, this.aggregationSearchVnfTarget); + handleSearchServiceOperation(ae, action, this.aggregationSearchVnfTarget); /* * It was decided to silently ignore DELETE requests for resources we don't allow to be * deleted. e.g. auto-suggestion deletion is not allowed while aggregation deletion is. */ if (!ACTION_DELETE.equalsIgnoreCase(action)) { - SearchSuggestionPermutation searchSuggestionPermutation = - new SearchSuggestionPermutation(); - List> permutationsOfStatuses = - searchSuggestionPermutation.getSuggestionsPermutation(suggestibleAttributes); - - // Now we have a list of all possible permutations for the status that are - // defined for this entity type. Try inserting a document for every combination. - for (ArrayList permutation : permutationsOfStatuses) { + List> listOfValidPowerSetElements = + SearchSuggestionPermutation.getNonEmptyUniqueLists(suggestibleAttrInPayload); + + // Now we have a list containing the power-set (minus empty element) for the status that are + // available in the payload. Try inserting a document for every combination. + for (ArrayList list : listOfValidPowerSetElements) { SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity(); suggestionSearchEntity.setEntityType(entityType); - suggestionSearchEntity.setSuggestableAttr(permutation); - suggestionSearchEntity.setPayloadFromResponse(uebAsJson); + suggestionSearchEntity.setSuggestableAttr(list); suggestionSearchEntity.setEntityTypeAliases(suggestionAliases); + suggestionSearchEntity.setFilterBasedPayloadFromResponse(uebAsJson.get("entity"), + suggestibleAttrInOxm, list); suggestionSearchEntity.setSuggestionInputPermutations( suggestionSearchEntity.generateSuggestionInputPermutations()); if (suggestionSearchEntity.isSuggestableDoc()) { try { - suggestionSearchEntity.deriveFields(); + suggestionSearchEntity.generateSearchSuggestionDisplayStringAndId(); } catch (NoSuchAlgorithmException e) { logger.error(EntityEventPolicyMsgs.DISCARD_UPDATING_SEARCH_SUGGESTION_DATA, "Cannot create unique SHA digest for search suggestion data. Exception: " + e.getLocalizedMessage()); } - handleSuggestiveSearchData(suggestionSearchEntity, action, + handleSearchServiceOperation(suggestionSearchEntity, action, this.autoSuggestSearchTarget); } } @@ -676,10 +690,10 @@ public class EntityEventPolicy implements Processor { /* * Load the UEB JSON payload, any errors would result to a failure case response. */ - private JSONObject getUebHeaderAsJson(String payload) { + private JSONObject getUebContentAsJson(String payload, String contentKey) { JSONObject uebJsonObj; - JSONObject uebObjHeader; + JSONObject uebObjContent; try { uebJsonObj = new JSONObject(payload); @@ -689,15 +703,15 @@ public class EntityEventPolicy implements Processor { return null; } - if (uebJsonObj.has(EVENT_HEADER)) { - uebObjHeader = uebJsonObj.getJSONObject(EVENT_HEADER); + if (uebJsonObj.has(contentKey)) { + uebObjContent = uebJsonObj.getJSONObject(contentKey); } else { - logger.debug(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, EVENT_HEADER); - logger.error(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, EVENT_HEADER); + logger.debug(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, contentKey); + logger.error(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, contentKey); return null; } - return uebObjHeader; + return uebObjContent; } @@ -973,76 +987,6 @@ public class EntityEventPolicy implements Processor { * @param target Resource to perform the operation on * @param allowDeleteEvent Allow delete operation to be performed on resource */ - private void handleSuggestiveSearchData(DocumentStoreDataEntity eventEntity, String action, - String target) { - try { - Map> headers = new HashMap<>(); - headers.put(Headers.FROM_APP_ID, Arrays.asList("DataLayer")); - headers.put(Headers.TRANSACTION_ID, Arrays.asList(MDC.get(MdcContext.MDC_REQUEST_ID))); - - String entityId = eventEntity.getId(); - - if ((action.equalsIgnoreCase(ACTION_CREATE) && entityId != null) - || action.equalsIgnoreCase(ACTION_UPDATE)) { - // Run the GET to retrieve the ETAG from the search service - OperationResult storedEntity = searchAgent.getDocument(aggregateGenericVnfIndex, entityId); - - if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) { - List etag = storedEntity.getHeaders().get(Headers.ETAG); - - if (etag != null && etag.size() > 0) { - headers.put(Headers.IF_MATCH, etag); - } else { - logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, target + entityId, - entityId); - } - } - - String eventEntityStr = eventEntity.getAsJson(); - - if (eventEntityStr != null) { - List createIndex = new ArrayList(); - createIndex.add("true"); - headers.put("X-CreateIndex", createIndex); - searchAgent.putDocument(aggregateGenericVnfIndex, entityId, eventEntity.getAsJson(), headers); - } - } else if (action.equalsIgnoreCase(ACTION_CREATE)) { - String eventEntityStr = eventEntity.getAsJson(); - - if (eventEntityStr != null) { - List createIndex = new ArrayList(); - createIndex.add("true"); - headers.put("X-CreateIndex", createIndex); - searchAgent.postDocument(aggregateGenericVnfIndex, eventEntityStr, headers); - } - } else if (action.equalsIgnoreCase(ACTION_DELETE)) { - // Run the GET to retrieve the ETAG from the search service - OperationResult storedEntity = searchAgent.getDocument(aggregateGenericVnfIndex, entityId); - - if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) { - List etag = storedEntity.getHeaders().get(Headers.ETAG); - - if (etag != null && etag.size() > 0) { - headers.put(Headers.IF_MATCH, etag); - } else { - logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, target + entityId, - entityId); - } - - searchAgent.deleteDocument(aggregateGenericVnfIndex, eventEntity.getId(), headers); - } else { - logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, target + entityId, - entityId); - } - } else { - logger.error(EntityEventPolicyMsgs.ENTITY_OPERATION_NOT_SUPPORTED, action); - } - } catch (IOException e) { - logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE, eventEntity.getId(), - action); - } - } - private void handleSearchServiceOperation(DocumentStoreDataEntity eventEntity, String action, String index) { @@ -1076,7 +1020,6 @@ public class EntityEventPolicy implements Processor { // Write the entity to the search service. // PUT searchAgent.putDocument(index, entityId, eventEntity.getAsJson(), headers); - } else if (action.equalsIgnoreCase(ACTION_CREATE)) { // Write the entry to the search service. searchAgent.postDocument(index, eventEntity.getAsJson(), headers); diff --git a/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicyConfig.java b/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicyConfig.java index 8e14be1..4728f82 100644 --- a/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicyConfig.java +++ b/src/main/java/org/openecomp/datarouter/policy/EntityEventPolicyConfig.java @@ -118,12 +118,12 @@ public class EntityEventPolicyConfig { public void setSearchKeystorePwd(String searchKeystorePwd) { this.searchKeystorePwd = searchKeystorePwd; } - -public String getSearchAggregationVnfIndex() { - return searchAggregationVnfIndex; -} - -public void setSearchAggregationVnfIndex(String searchAggregationVnfIndex) { - this.searchAggregationVnfIndex = searchAggregationVnfIndex; -} + + public String getSearchAggregationVnfIndex() { + return searchAggregationVnfIndex; + } + + public void setSearchAggregationVnfIndex(String searchAggregationVnfIndex) { + this.searchAggregationVnfIndex = searchAggregationVnfIndex; + } } diff --git a/src/main/java/org/openecomp/datarouter/search/filters/config/UiFilterConfig.java b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFilterConfig.java new file mode 100644 index 0000000..a516de0 --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFilterConfig.java @@ -0,0 +1,114 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.search.filters.config; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_NULL) +public class UiFilterConfig { + + @JsonProperty("filterId") + private String filterId; + + @JsonProperty("filterName") + private String filterName; + + @JsonProperty("displayName") + private String displayName; + + @JsonProperty("dataType") + private String dataType; + + @JsonProperty("dataSource") + private UiFilterDataSourceConfig dataSource = new UiFilterDataSourceConfig(); + + @JsonCreator + public UiFilterConfig(@JsonProperty("filterId") final String filterId, + @JsonProperty("filterName") final String filterName, + @JsonProperty("displayName") final String displayName, + @JsonProperty("dataType") final String dataType, + @JsonProperty("dataSource") final UiFilterDataSourceConfig dataSource + ) { + this.filterId = filterId; + this.filterName = filterName; + this.displayName = displayName; + this.dataType = dataType; + this.dataSource = dataSource; + } + + @JsonProperty("filterId") + public String getFilterId() { + return filterId; + } + + public void setFilterId(String filterId) { + this.filterId = filterId; + } + + @JsonProperty("filterName") + public String getFilterName() { + return filterName; + } + + public void setFilterName(String filterName) { + this.filterName = filterName; + } + + @JsonProperty("displayName") + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + @JsonProperty("dataType") + public String getDataType() { + return dataType; + } + + public void setDataType(String dataType) { + this.dataType = dataType; + } + + @JsonProperty("dataSource") + public UiFilterDataSourceConfig getDataSource() { + return dataSource; + } + + public void setDataSource(UiFilterDataSourceConfig dataSource) { + this.dataSource = dataSource; + } + + @Override + public String toString() { + return "UiFilterConfig [filterId=" + filterId + ", filterName=" + filterName + ", displayName=" + + displayName + ", dataType=" + dataType + ", dataSource=" + dataSource + "]"; + } +} diff --git a/src/main/java/org/openecomp/datarouter/search/filters/config/UiFilterDataSourceConfig.java b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFilterDataSourceConfig.java new file mode 100644 index 0000000..ac22d7b --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFilterDataSourceConfig.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.search.filters.config; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_NULL) +public class UiFilterDataSourceConfig { + + @JsonProperty("indexName") + private String indexName; + + @JsonProperty("docType") + private String docType; + + @JsonProperty("fieldName") + private String fieldName; + + @JsonProperty("pathToField") + private String pathToField; + + public UiFilterDataSourceConfig(){} + + @JsonCreator + public UiFilterDataSourceConfig( + @JsonProperty("indexName") final String indexName, @JsonProperty("docType") final String docType, + @JsonProperty("fieldName") final String fieldName, @JsonProperty("pathToField") final String pathToField) { + this.indexName = indexName; + this.docType = docType; + this.fieldName = fieldName; + this.pathToField = pathToField; + } + + @JsonProperty("indexName") + public String getIndexName() { + return indexName; + } + + public void setIndexName(String indexName) { + this.indexName = indexName; + } + + @JsonProperty("docType") + public String getDocType() { + return docType; + } + + public void setDocType(String docType) { + this.docType = docType; + } + + @JsonProperty("fieldName") + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + @JsonProperty("pathToField") + public String getPathToField() { + return pathToField; + } + + public void setPathToField(String pathToField) { + this.pathToField = pathToField; + } + + @Override + public String toString() { + return "UiFilterDataSourceConfig [indexName=" + indexName + ", docType=" + docType + + ", fieldName=" + fieldName + ", pathToField=" + pathToField + "]"; + } +} + diff --git a/src/main/java/org/openecomp/datarouter/search/filters/config/UiFiltersConfig.java b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFiltersConfig.java new file mode 100644 index 0000000..dff4a30 --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFiltersConfig.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.search.filters.config; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UiFiltersConfig { + @JsonProperty("filters") + private List filters = new ArrayList<>(); + + public UiFiltersConfig() {} + + @JsonCreator + public UiFiltersConfig(@JsonProperty("filters") final List filters) { + this.filters = filters; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + @Override + public String toString() { + return "UiFiltersConfig [filters=" + filters + "]"; + } +} diff --git a/src/main/java/org/openecomp/datarouter/search/filters/config/UiFiltersSchemaUtility.java b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFiltersSchemaUtility.java new file mode 100644 index 0000000..e674495 --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/search/filters/config/UiFiltersSchemaUtility.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.search.filters.config; + +import java.io.File; +import java.io.IOException; + +import org.openecomp.cl.api.Logger; +import org.openecomp.cl.eelf.LoggerFactory; +import org.openecomp.datarouter.logging.DataRouterMsgs; +import org.openecomp.datarouter.util.DataRouterConstants; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Utility methods for interacting with the UI filters schema file + */ +public class UiFiltersSchemaUtility { + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(UiFiltersSchemaUtility.class); + + private ObjectMapper mapper = new ObjectMapper(); + + /** + * Reads in the file and populates an object with that data + * + * @throws Exception + */ + public UiFiltersConfig loadUiFiltersConfig() { + UiFiltersConfig filtersConfig = new UiFiltersConfig(); + + try { + filtersConfig = mapper.readValue(new File(DataRouterConstants.UI_FILTER_LIST_FILE), UiFiltersConfig.class); + } catch (IOException e) { + LOG.error(DataRouterMsgs.JSON_CONVERSION_ERROR, "Could not convert filters config file " + + DataRouterConstants.UI_FILTER_LIST_FILE + " to " + filtersConfig.getClass()); + } + + return filtersConfig; + } +} diff --git a/src/main/java/org/openecomp/datarouter/util/AaiUiSvcPolicyUtil.java b/src/main/java/org/openecomp/datarouter/util/AaiUiSvcPolicyUtil.java new file mode 100644 index 0000000..d5388d6 --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/util/AaiUiSvcPolicyUtil.java @@ -0,0 +1,77 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class AaiUiSvcPolicyUtil { + + static ObjectMapper mapper = new ObjectMapper(); + + public static JsonNode getOriginPayload(JsonNode payload) throws Exception{ + /* + *{ + "origin-uri": "/routerService/1search1", + "origin-payload": {} + } + */ + JsonNode origPayload = null; + + if (payload.has("origin-payload")){ + origPayload = payload.get("origin-payload"); + } + return origPayload; + } + + public static String getOriginUri ( JsonNode payload ) throws Exception { + String originUri = ""; + if (payload.has("origin-uri")){ + originUri = payload.get("origin-uri").textValue(); + } + return originUri; + } + + public static String getTargetUri(JsonNode payload) throws Exception{ + /* + *{ + "origin-uri": "/routerService/1search1", + "origin-payload": {} + } + */ + String uri = ""; + String originUri = getOriginUri(payload); + final Matcher m = Pattern.compile("/routerService/(.*)").matcher(originUri); + if ( m.find() ) { + uri = m.group(1); + } + return uri; + } + +} diff --git a/src/main/java/org/openecomp/datarouter/util/DataRouterConstants.java b/src/main/java/org/openecomp/datarouter/util/DataRouterConstants.java index f9f5df3..fff16f2 100644 --- a/src/main/java/org/openecomp/datarouter/util/DataRouterConstants.java +++ b/src/main/java/org/openecomp/datarouter/util/DataRouterConstants.java @@ -27,16 +27,18 @@ package org.openecomp.datarouter.util; public class DataRouterConstants { public static final String DR_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); + + public static final String DR_AJSC_HOME = System.getProperty("AJSC_HOME"); public static final String DR_SPECIFIC_CONFIG = System.getProperty("CONFIG_HOME") + DR_FILESEP; public static final String DR_BUNDLECONFIG_NAME = (System.getProperty("BUNDLECONFIG_DIR") == null) ? "bundleconfig" : System.getProperty("BUNDLECONFIG_DIR"); - public static final String DR_HOME_BUNDLECONFIG = (System.getProperty("AJSC_HOME") == null) + public static final String DR_HOME_BUNDLECONFIG = (DR_AJSC_HOME == null) ? DR_FILESEP + "opt" + DR_FILESEP + "app" + DR_FILESEP + "datalayer" + DR_FILESEP + DR_BUNDLECONFIG_NAME - : System.getProperty("AJSC_HOME") + DR_FILESEP + DR_BUNDLECONFIG_NAME; + : DR_AJSC_HOME + DR_FILESEP + DR_BUNDLECONFIG_NAME; /** This is the etc directory, relative to AAI_HOME. */ public static final String DR_HOME_ETC = DR_HOME_BUNDLECONFIG + DR_FILESEP + "etc" + DR_FILESEP; @@ -48,6 +50,8 @@ public class DataRouterConstants { public static final String DR_HOME_ETC_OXM = DR_HOME_ETC + "oxm" + DR_FILESEP; + public static final String UI_FILTER_LIST_FILE = + DR_SPECIFIC_CONFIG + DR_FILESEP + "filters" + DR_FILESEP + "aaiui_filters.json"; // AAI Related public static final String AAI_ECHO_SERVICE = "/util/echo"; diff --git a/src/main/java/org/openecomp/datarouter/util/RouterServiceUtil.java b/src/main/java/org/openecomp/datarouter/util/RouterServiceUtil.java index b30c9f9..f2ff7ac 100644 --- a/src/main/java/org/openecomp/datarouter/util/RouterServiceUtil.java +++ b/src/main/java/org/openecomp/datarouter/util/RouterServiceUtil.java @@ -26,16 +26,40 @@ package org.openecomp.datarouter.util; import com.fasterxml.jackson.databind.JsonNode; +import org.apache.camel.Exchange; +import org.apache.camel.component.cxf.common.message.CxfConstants; +import org.apache.cxf.message.Message; import org.json.JSONObject; +import org.openecomp.cl.mdc.MdcContext; +import org.openecomp.restclient.client.Headers; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.UUID; + +import javax.servlet.ServletRequest; public class RouterServiceUtil { + + public static void setMdcContext(Exchange exchange){ + String txnID = exchange.getIn().getHeader(Headers.TRANSACTION_ID, + Arrays.asList(UUID.randomUUID())).toString(); + String remote = exchange.getIn().getHeader(Headers.FROM_APP_ID, "").toString(); + String remoteAddress = ""; + Message cxfMessage = exchange.getIn().getHeader(CxfConstants.CAMEL_CXF_MESSAGE, Message.class); + if (cxfMessage != null) { + ServletRequest request = (ServletRequest) cxfMessage.get("HTTP.REQUEST"); + if ( request != null) + remoteAddress = request.getRemoteAddr(); + } + + MdcContext.initialize(txnID, "Synapse", "", remote, remoteAddress); + } public static Map parseJsonPayloadIntoMap(String jsonPayload) { @@ -223,4 +247,27 @@ public class RouterServiceUtil { String json = jsonObject.toString(); return json; } + + /** + * Helper utility to concatenate substrings of a URI together to form a proper URI. + * + * @param suburis the list of substrings to concatenate together + * @return the concatenated list of substrings + */ + public static String concatSubUri(String... suburis) { + String finalUri = ""; + + for (String suburi : suburis) { + + if (suburi != null) { + // Remove any leading / since we only want to append / + suburi = suburi.replaceFirst("^/*", ""); + + // Add a trailing / if one isn't already there + finalUri += suburi.endsWith("/") ? suburi : suburi + "/"; + } + } + + return finalUri; + } } diff --git a/src/main/java/org/openecomp/datarouter/util/SearchSuggestionPermutation.java b/src/main/java/org/openecomp/datarouter/util/SearchSuggestionPermutation.java index 91f5910..4954a92 100644 --- a/src/main/java/org/openecomp/datarouter/util/SearchSuggestionPermutation.java +++ b/src/main/java/org/openecomp/datarouter/util/SearchSuggestionPermutation.java @@ -38,52 +38,63 @@ public class SearchSuggestionPermutation { * @param list The list of statuses to create permutations of * @return A list which contains a array list of all possible combinations */ - @SuppressWarnings("serial") - public List> getSuggestionsPermutation(List list) { - List statusList = new ArrayList<>(list); - List dupStatusList; - ArrayList> uniqueList = new ArrayList<>(); - int mainLoopIndexCounter = 0; + public static ArrayList> getUniqueListForSuggestions( + List originalList) { + ArrayList> lists = new ArrayList>(); + if (originalList.isEmpty()) { + lists.add(new ArrayList()); + return lists; + } + List list = new ArrayList(originalList); + String head = list.get(0); + ArrayList rest = new ArrayList(list.subList(1, list.size())); + + for (ArrayList activeList : getUniqueListForSuggestions(rest)) { + ArrayList newList = new ArrayList(); + newList.add(head); + newList.addAll(activeList); + lists.add(newList); + lists.add(activeList); + } + return lists; + } + + public static ArrayList> getNonEmptyUniqueLists(List list){ + ArrayList> lists = getUniqueListForSuggestions(list); + // remove empty list from the power set + for (ArrayList emptyList : lists ){ + if ( emptyList.isEmpty() ) { + lists.remove(emptyList); + break; + } + } + return lists; + } - for (String status : statusList) { - // Add the single entity subset - //This will add the unique single values eg [A],[B],[C],[D] - uniqueList.add(new ArrayList() { - { - add(status); - } - }); + public static List> getListPermutations(List list) { + List inputList = new ArrayList(); + inputList.addAll(list); + if (inputList.size() == 0) { + List> result = new ArrayList>(); + result.add(new ArrayList()); + return result; + } - // Remove all the elements to left till the current index - dupStatusList = truncateListUntill(statusList, mainLoopIndexCounter); + List> listOfLists = new ArrayList>(); - while (!dupStatusList.isEmpty()) { - ArrayList suggListInIterate= new ArrayList<>(); - suggListInIterate.add(status); + String firstElement = inputList.remove(0); - for (String dupStatus : dupStatusList) { - suggListInIterate.add(dupStatus); - } + List> recursiveReturn = getListPermutations(inputList); + for (List li : recursiveReturn) { - uniqueList.add(suggListInIterate); - dupStatusList.remove(0); + for (int index = 0; index <= li.size(); index++) { + List temp = new ArrayList(li); + temp.add(index, firstElement); + listOfLists.add(temp); } - mainLoopIndexCounter++; } - - return uniqueList; + return listOfLists; } - private List truncateListUntill(List lists, int index) { - List truncatedList = new ArrayList<>(lists); - int counter = 0; - - while (counter <= index) { - truncatedList.remove(0); - counter++; - } - - return truncatedList; - } } diff --git a/src/main/java/org/openecomp/datarouter/util/client/NoAuthRestClient.java b/src/main/java/org/openecomp/datarouter/util/client/NoAuthRestClient.java new file mode 100644 index 0000000..33874a8 --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/util/client/NoAuthRestClient.java @@ -0,0 +1,226 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.util.client; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; + +import org.apache.camel.Exchange; +import org.apache.camel.component.http.HttpMessage; +import org.apache.camel.Message; +import org.openecomp.cl.api.Logger; +import org.openecomp.cl.eelf.LoggerFactory; +import org.openecomp.cl.mdc.MdcContext; +import org.openecomp.datarouter.logging.DataRouterMsgs; +import org.openecomp.datarouter.util.AaiUiSvcPolicyUtil; +import org.openecomp.datarouter.util.NodeUtils; +import org.openecomp.datarouter.util.RouterServiceUtil; +import org.openecomp.restclient.client.Headers; +import org.openecomp.restclient.client.OperationResult; +import org.openecomp.restclient.client.RestClient; +import org.openecomp.restclient.enums.RestAuthenticationMode; +import org.slf4j.MDC; + +import org.springframework.http.HttpStatus; + +import org.openecomp.restclient.rest.HttpUtil; +import com.fasterxml.jackson.databind.JsonNode; + +public class NoAuthRestClient implements SvcRoutingRestClient { + + private RestClient restClient; + + private String host; + private String port; + private String originUrl; + private String targetUri; + private JsonNode targetPayload; + private Logger logger; + private Logger auditLogger; + + public NoAuthRestClient(int connectTimeOut, int readTimeOut) { + LoggerFactory loggerFactoryInstance = LoggerFactory.getInstance(); + logger = loggerFactoryInstance.getLogger(NoAuthRestClient.class.getName()); + auditLogger = loggerFactoryInstance.getAuditLogger(NoAuthRestClient.class.getName()); + restClient = new RestClient().authenticationMode(RestAuthenticationMode.HTTP_NOAUTH) + .connectTimeoutMs(connectTimeOut).readTimeoutMs(readTimeOut); + } + + + private OperationResult getResults(String url, JsonNode payload){ + Map> headers = new HashMap<>(); + headers.put(Headers.FROM_APP_ID, Arrays.asList("Synapse")); + headers.put(Headers.TRANSACTION_ID, Arrays.asList(MDC.get(MdcContext.MDC_REQUEST_ID))); + return this.getRestClient().post(url, payload.asText(), headers, MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + } + + public final void handleRequest (String host, String port, Exchange exchange) throws Exception { + RouterServiceUtil.setMdcContext(exchange); + Message message = exchange.getIn(); + String body = message.getBody(String.class); + OperationResult result = new OperationResult(); + + this.setHost(host); + this.setPort(port); + + this.setOriginUrl(message.getHeader(Exchange.HTTP_URL).toString()); + if (body != null && body.length() != 0) { + JsonNode node = NodeUtils.convertJsonStrToJsonNode(body); + this.setTargetPayload(AaiUiSvcPolicyUtil.getOriginPayload(node)); + this.setTargetUri(AaiUiSvcPolicyUtil.getTargetUri(node)); + } + + if ( this.getTargetPayload() == null || this.getTargetUri() == null){ + logger.error(DataRouterMsgs.INVALID_ORIGIN_PAYLOAD, body); + result.setResultCode(HttpStatus.BAD_REQUEST.value()); + result.setFailureCause("Invalid payload"); + } + + String targetUrl = "http://" + host + ":" + port + "/" + this.targetUri; + auditLogger.info(DataRouterMsgs.ROUTING_FROM_TO, this.getOriginUrl(), targetUrl); + long startTimeInMs = System.currentTimeMillis(); + + result = this.getResults(targetUrl, targetPayload); + + long targetMsOpTime = (System.currentTimeMillis() - startTimeInMs); + auditLogger.info(DataRouterMsgs.OP_TIME, "Target service at "+ targetUrl, String.valueOf(targetMsOpTime)); + + int rc = result.getResultCode(); + String resultStr = ""; + if (HttpUtil.isHttpResponseClassSuccess(rc)) { + resultStr = result.getResult(); + } else { + resultStr = result.getFailureCause(); + } + + logger.debug(DataRouterMsgs.ROUTING_RESPONSE, targetUrl, result.toString()); + exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, rc); + exchange.getOut().setBody(resultStr); + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#getHost() + */ + @Override + public String getHost() { + return host; + } + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#setHost(java.lang.String) + */ + @Override + public void setHost(String host) { + this.host = host; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#getPort() + */ + @Override + public String getPort() { + return port; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#setPort(java.lang.String) + */ + @Override + public void setPort(String port) { + this.port = port; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#getTargetUri() + */ + @Override + public String getTargetUri() { + return targetUri; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#setTargetUri(java.lang.String) + */ + @Override + public void setTargetUri(String targetUri) { + this.targetUri = targetUri; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#getTargetPayload() + */ + @Override + public JsonNode getTargetPayload() { + return targetPayload; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#setTargetPayload(com.fasterxml.jackson.databind.JsonNode) + */ + @Override + public void setTargetPayload(JsonNode targetPayload) { + this.targetPayload = targetPayload; + } + + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#getRestClient() + */ + @Override + public RestClient getRestClient() { + return restClient; + } + + /* (non-Javadoc) + * @see org.openecomp.datarouter.util.client.SvcRoutingRestClient#setRestClient() + */ + @Override + public void setRestClient(RestClient client) { + this.restClient = client; + } + + + public String getOriginUrl() { + return originUrl; + } + + + public void setOriginUrl(String originUrl) { + this.originUrl = originUrl; + } + + +} diff --git a/src/main/java/org/openecomp/datarouter/util/client/SvcRoutingRestClient.java b/src/main/java/org/openecomp/datarouter/util/client/SvcRoutingRestClient.java new file mode 100644 index 0000000..b1af73c --- /dev/null +++ b/src/main/java/org/openecomp/datarouter/util/client/SvcRoutingRestClient.java @@ -0,0 +1,54 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.util.client; + +import org.openecomp.restclient.client.RestClient; + +import com.fasterxml.jackson.databind.JsonNode; + + +public interface SvcRoutingRestClient { + + String getHost(); + + void setHost(String host); + + String getPort(); + + void setPort(String port); + + String getTargetUri(); + + void setTargetUri(String targetUri); + + JsonNode getTargetPayload(); + + void setTargetPayload(JsonNode targetPayload); + + RestClient getRestClient(); + + void setRestClient(RestClient client); + +} diff --git a/src/main/resources/logging/DataRouterMsgs.properties b/src/main/resources/logging/DataRouterMsgs.properties index 9650b22..fbb24c4 100644 --- a/src/main/resources/logging/DataRouterMsgs.properties +++ b/src/main/resources/logging/DataRouterMsgs.properties @@ -84,6 +84,18 @@ CREATE_MISSING_INDEX=\ PROCESS_EVENT=\ DR0010I|\ Processed event {0}. Result: {1} + +ROUTING_FROM_TO=\ + DR0011I|\ + Routing incoming request from {0} to {1}. + +ROUTING_RESPONSE=\ + DR0012D|\ + Response from URL {0}: {1}. + +OP_TIME=\ + DR0013I|\ + {0} took {1} ms. STARTUP_FAILURE=\ DR2001E|\ @@ -136,7 +148,19 @@ INVALID_OXM_DIR=\ SYSTEM_ERROR=\ DR3011E|\ System Error: {0}\ + +INVALID_ORIGIN_PAYLOAD=\ + DR3012E|\ + Invalid origin-payload: {0}\ + +READING_JSON_SCHEMA_ERROR=\ + DR3013E|\ + Error reading JSON schema from: {0}\ +JSON_CONVERSION_ERROR=\ + DR3014E|\ + Error converting JSON: {0}\ + FAIL_TO_CREATE_UPDATE_DOC=\ DR3015E|\ Failed to create or update document in index {0}. Cause: {1} diff --git a/src/test/java/org/openecomp/datarouter/entity/SuggestionSearchEntityTest.java b/src/test/java/org/openecomp/datarouter/entity/SuggestionSearchEntityTest.java new file mode 100644 index 0000000..3404eec --- /dev/null +++ b/src/test/java/org/openecomp/datarouter/entity/SuggestionSearchEntityTest.java @@ -0,0 +1,158 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ +package org.openecomp.datarouter.entity; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.datarouter.search.filters.config.UiFiltersSchemaUtility; + +public class SuggestionSearchEntityTest { + private static SuggestionSearchEntity suggestionSearchEntity; + + @Before + public void setUpBeforeTest() { + UiFiltersSchemaUtility filtersSchemaUtility = Mockito.mock(UiFiltersSchemaUtility.class); + Mockito.when(filtersSchemaUtility.loadUiFiltersConfig()).thenReturn(null); + + suggestionSearchEntity = new SuggestionSearchEntity(); + suggestionSearchEntity.setFiltersSchemaUtility(filtersSchemaUtility); + suggestionSearchEntity.setEntityType("generic-vnf"); + suggestionSearchEntity.setEntityTypeAliases(Arrays.asList("VNFs")); + } + + /** + * Read in the contents of the given file (can include sub-path) in test/resources folder + * + * @param filePath The file name or path (relative to test/resources) to read from + * @return The contents of the file as a String + */ + public String getResourceFileContents(String filePath) { + StringBuilder result = new StringBuilder(""); + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource(filePath).getFile()); + + try (Scanner scanner = new Scanner(file)) { + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + result.append(line).append("\n"); + } + + scanner.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + + return result.toString(); + } + + @Test + public void testGetAsJson_multipleFilterAttributableStatusesIncluded() throws IOException { + String expectedOutput = + getResourceFileContents("uifilters/testGetAsJson_multipleFilterAttributableStatusesIncluded_expectedValue.json"); + + List suggestionInputPermutations = Arrays.asList( + "provStatus1 orchestrationStatus1 generic-vnf", + "provStatus1 generic-vnf orchestrationStatus1", + "orchestrationStatus1 generic-vnf provStatus1", + "orchestrationStatus1 provStatus1 generic-vnf", + "generic-vnf provStatus1 orchestrationStatus1", + "generic-vnf orchestrationStatus1 provStatus1"); + + MapinputOutputData = new HashMap<>(); + inputOutputData.put("prov-status", "provStatus1"); + inputOutputData.put("orchestration-status", "orchestrationStatus1"); + + // Build UI filters JSON string + JSONObject payloadFilter1 = new JSONObject(); + payloadFilter1.put("filterId", "1"); + payloadFilter1.put("filterValue", "orchestrationStatus1"); + + JSONObject payloadFilter2 = new JSONObject(); + payloadFilter2.put("filterId", "2"); + payloadFilter2.put("filterValue", "provStatus1"); + + JSONArray payloadFilters = new JSONArray(); + payloadFilters.put(payloadFilter2); + payloadFilters.put(payloadFilter1); + + JSONObject filterPayload = new JSONObject(); + filterPayload.put("filterList", payloadFilters); + + suggestionSearchEntity.setSuggestionInputPermutations(suggestionInputPermutations); + suggestionSearchEntity.setInputOutputData(inputOutputData); + suggestionSearchEntity.setFilterPayload(filterPayload); + + String actualOutput = suggestionSearchEntity.getAsJson(); + + assertEquals(expectedOutput.trim(), actualOutput.trim()); + } + + @Test + public void testGetAsJson_singleFilterAttributableStatusIncluded() throws IOException { + String expectedOutput = + getResourceFileContents("uifilters/testGetAsJson_singleFilterAttributableStatusIncluded_expectedValue.json"); + + List suggestionInputPermutations = Arrays.asList( + "provStatus1 generic-vnf", + "generic-vnf provStatus1"); + + MapinputOutputData = new HashMap<>(); + inputOutputData.put("prov-status", "provStatus1"); + + // Build UI filters JSON string + JSONObject payloadFilter1 = new JSONObject(); + payloadFilter1.put("filterId", "2"); + payloadFilter1.put("filterValue", "provStatus1"); + + JSONArray payloadFilters = new JSONArray(); + payloadFilters.put(payloadFilter1); + + JSONObject filterPayload = new JSONObject(); + filterPayload.put("filterList", payloadFilters); + + suggestionSearchEntity.setSuggestionInputPermutations(suggestionInputPermutations); + suggestionSearchEntity.setInputOutputData(inputOutputData); + suggestionSearchEntity.setFilterPayload(filterPayload); + + String actualOutput = suggestionSearchEntity.getAsJson(); + + assertEquals(expectedOutput.trim(), actualOutput.trim()); + } +} diff --git a/src/test/java/org/openecomp/datarouter/util/AaiUiSvcPolicyUtilTest.java b/src/test/java/org/openecomp/datarouter/util/AaiUiSvcPolicyUtilTest.java new file mode 100644 index 0000000..5e6841f --- /dev/null +++ b/src/test/java/org/openecomp/datarouter/util/AaiUiSvcPolicyUtilTest.java @@ -0,0 +1,112 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ + +package org.openecomp.datarouter.util; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class AaiUiSvcPolicyUtilTest { + + private final static String ORIGIN_URI = "testUri/somePath"; + private final static String ORIGIN_PAYLOAD = "test payload"; + + private final static String validPayload = "{" + + "\"origin-uri\": \"" + ORIGIN_URI + "\"," + + "\"origin-payload\": \"" + ORIGIN_PAYLOAD + "\"}"; + + private final static String payloadWithoutOriginUri = "{" + + "\"origin-payload\": \"" + ORIGIN_PAYLOAD + "\"}"; + + private final static String payloadWithoutOriginPayload = "{" + + "\"origin-uri\": \"" + ORIGIN_URI + "\"}"; + + private static JsonNode node = null; + private static JsonNode nodeWithoutOrginUri = null; + private static JsonNode nodeWithoutOrginPayload = null; + static ObjectMapper mapper = new ObjectMapper(); + + @BeforeClass + public static void init(){ + try { + node = mapper.readTree(validPayload); + nodeWithoutOrginUri = mapper.readTree(payloadWithoutOriginUri); + nodeWithoutOrginPayload = mapper.readTree(payloadWithoutOriginPayload); + } catch (Exception e) { + fail("Initialization error"); + } + } + + @Test + public void testGetOriginPayload_missingPayload() { + JsonNode value = null; + try { + value = AaiUiSvcPolicyUtil.getOriginPayload(nodeWithoutOrginPayload); + assertNull("Failure to extract origin payload", value); + } catch (Exception e) { + fail("Failure to extract origin payload"); + } + } + + @Test + public void testGetOriginPayload_validPayload() { + JsonNode value = null; + try { + value = AaiUiSvcPolicyUtil.getOriginPayload(node); + assertTrue("Failure to extract origin payload", ORIGIN_PAYLOAD.equals(value.asText())); + } catch (Exception e) { + fail("Failure to extract origin payload"); + } + } + + @Test + public void testGetOriginUri_missingUri() { + String value = null; + try { + value = AaiUiSvcPolicyUtil.getOriginUri(nodeWithoutOrginUri); + assertTrue("Failure to extract origin uri", value.isEmpty()); + } catch (Exception e) { + fail("Failure to extract origin uri"); + } + } + + @Test + public void testGetOriginUri_validPayload() { + String value = null; + try { + value = AaiUiSvcPolicyUtil.getOriginUri(node); + assertTrue("Failure to extract origin uri", ORIGIN_URI.equals(value)); + } catch (Exception e) { + fail("Failure to extract origin uri"); + } + } +} diff --git a/src/test/java/org/openecomp/datarouter/util/client/NoAuthRestClientTest.java b/src/test/java/org/openecomp/datarouter/util/client/NoAuthRestClientTest.java new file mode 100644 index 0000000..4e4db75 --- /dev/null +++ b/src/test/java/org/openecomp/datarouter/util/client/NoAuthRestClientTest.java @@ -0,0 +1,115 @@ +/** + * ============LICENSE_START======================================================= + * DataRouter + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * 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========================================================= + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ + +package org.openecomp.datarouter.util.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import javax.ws.rs.core.MediaType; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.restclient.client.OperationResult; +import org.openecomp.restclient.client.RestClient; + +public class NoAuthRestClientTest { + + RestClient client = null; + OperationResult successResult = null; + OperationResult failureResult = null; + Exchange exchange = null; + NoAuthRestClient narc = new NoAuthRestClient(60,60); + String goodDomain = "AGoodUrlThatNeverFails.com"; + String badDomain = "ABadUrlThatAlwaysFails.com"; + String goodTargetUrl = "http://" + goodDomain + ":1234/servicegraph"; + String badTargetUrl = "http://" + badDomain + ":1234/servicegraph"; + String payload = "{\"origin-uri\":\"/routerService/servicegraph\"," + + "\"origin-payload\":{\"hashId\":\"claymore-sdwan-service.full.(View and Inspect)\"}}"; + + String successResponsePayload = "very-good-result"; + String failureResponsePayload = "Server Error"; + + @SuppressWarnings("unchecked") + @Before + public void init(){ + client = Mockito.mock(RestClient.class); + successResult = new OperationResult(200, successResponsePayload); + failureResult = new OperationResult(500, failureResponsePayload); + failureResult.setFailureCause(failureResponsePayload); + Mockito.when(client.post(Mockito.eq(goodTargetUrl), Mockito.anyString(), Mockito.anyMap(), + Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(MediaType.APPLICATION_JSON_TYPE))) + .thenReturn(successResult); + Mockito.when(client.post(Mockito.eq(badTargetUrl), Mockito.anyString(), Mockito.anyMap(), + Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(MediaType.APPLICATION_JSON_TYPE))) + .thenReturn(failureResult); + narc.setRestClient(client); + + } + + public Exchange getExchange(){ + CamelContext ctx = new DefaultCamelContext(); + Exchange ex = new DefaultExchange(ctx); + ex.getIn().setHeader(Exchange.HTTP_URL, "http://ARandomOrigin.com"); + ex.getIn().setBody(payload); + return ex; + } + + @Test + public void testHandleRequest_successScenario() { + Exchange ex = getExchange(); + try { + narc.handleRequest(goodDomain, "1234", ex); + String outBody = ex.getOut().getBody(String.class); + assertEquals("Routing success scenario: Failure to get correct http status.", + ex.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE), 200 ); + assertEquals("Routing success scenario: Failure to get response body.", + outBody, successResponsePayload); + } catch (Exception e) { + fail("Routing success scenario: Failure to process."); + } + } + + @Test + public void testHandleRequest_failureScenario() { + Exchange ex = getExchange(); + try { + narc.handleRequest(badDomain, "1234", ex); + String outBody = ex.getOut().getBody(String.class); + assertEquals("Routing failure scenario: Failure to get correct http status.", + ex.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE), 500 ); + assertEquals("Routing failure scenario: Failure to get response body.", + outBody, failureResult.getFailureCause()); + } catch (Exception e) { + fail("Routing failure scenario: Failure to process."); + } + } + +} diff --git a/src/test/resources/uifilters/testGetAsJson_multipleFilterAttributableStatusesIncluded_expectedValue.json b/src/test/resources/uifilters/testGetAsJson_multipleFilterAttributableStatusesIncluded_expectedValue.json new file mode 100644 index 0000000..fdbf4ca --- /dev/null +++ b/src/test/resources/uifilters/testGetAsJson_multipleFilterAttributableStatusesIncluded_expectedValue.json @@ -0,0 +1 @@ +{"entity_suggest":{"output":"provStatus1 and orchestrationStatus1 VNFs","input":["provStatus1 orchestrationStatus1 generic-vnf","provStatus1 generic-vnf orchestrationStatus1","orchestrationStatus1 generic-vnf provStatus1","orchestrationStatus1 provStatus1 generic-vnf","generic-vnf provStatus1 orchestrationStatus1","generic-vnf orchestrationStatus1 provStatus1"],"payload":{"filterList":[{"filterId":"2","filterValue":"provStatus1"},{"filterId":"1","filterValue":"orchestrationStatus1"}]}}} \ No newline at end of file diff --git a/src/test/resources/uifilters/testGetAsJson_singleFilterAttributableStatusIncluded_expectedValue.json b/src/test/resources/uifilters/testGetAsJson_singleFilterAttributableStatusIncluded_expectedValue.json new file mode 100644 index 0000000..92a10c2 --- /dev/null +++ b/src/test/resources/uifilters/testGetAsJson_singleFilterAttributableStatusIncluded_expectedValue.json @@ -0,0 +1 @@ +{"entity_suggest":{"output":"provStatus1 VNFs","input":["provStatus1 generic-vnf","generic-vnf provStatus1"],"payload":{"filterList":[{"filterId":"2","filterValue":"provStatus1"}]}}} \ No newline at end of file