diff options
author | ARUL NAMBI <arul.nambi@amdocs.com> | 2017-08-01 09:15:32 -0400 |
---|---|---|
committer | ARUL NAMBI <arul.nambi@amdocs.com> | 2017-08-01 09:55:11 -0400 |
commit | 6cb28e580a3d3e308de77b2e7b239cae3912dd7f (patch) | |
tree | 87e3444db1e567584871fdb636f29b08b3b0cb21 /src/main/java/org | |
parent | 4609a8c564afa12bfd3781567eee84a88cba98c0 (diff) |
Adding support for external microservice
Change-Id: I96fa079d70b9f9b5f48b0c1c24801f3624babe4a
Signed-off-by: ARUL NAMBI <arul.nambi@amdocs.com>
Diffstat (limited to 'src/main/java/org')
14 files changed, 1051 insertions, 245 deletions
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<String> entityTypeAliases; private List<String> suggestionInputPermutations = new ArrayList<>(); private List<String> statusPermutations = new ArrayList<>(); private List<String> suggestableAttr = new ArrayList<>(); - private Map<String, String> payload = new HashMap<>(); - private JSONObject payloadJsonNode = new JSONObject(); - private StringBuffer outputString = new StringBuffer(); + + private Map<String, String> inputOutputData = new HashMap<>(); + private Map<String, UiFilterConfig> 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<String, String> 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<String, String> 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<String> generateSuggestionInputPermutations() { @@ -88,24 +126,75 @@ public class SuggestionSearchEntity implements DocumentStoreDataEntity, Serializ } } - ArrayList<String> listToPermutate = new ArrayList<>(statusPermutations); - ArrayList<String> listOfSearchSuggestionPermutations = new ArrayList<>(); + ArrayList<String> listOfSearchSuggestionPermutations = new ArrayList<String>(); + ArrayList<String> listToPermutate = + new ArrayList<>(this.getInputOutputData().values()); for (String entityName : entityNames) { listToPermutate.add(entityName); - permutateList(listToPermutate, new ArrayList<String>(), listToPermutate.size(), listOfSearchSuggestionPermutations); + List<List<String>> lists = SearchSuggestionPermutation.getListPermutations(listToPermutate); + for (List<String> 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<String, String> 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<String, String> 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<String> suggestibleAttrInOxm, List<String> 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<String> getStatusPermutations() { + return statusPermutations; } - public Map<String, String> getPayload() { - return payload; + public List<String> getSuggestableAttr() { + return suggestableAttr; } - public void setPayloadFromResponse(JsonNode node) { - Map<String, String> 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<String> getSuggestionInputPermutations() { + return this.suggestionInputPermutations; } - public void setPayload(Map<String, String> payload) { - this.payload = payload; + public void setId(String id) { + this.id = id; } - - public JSONObject getPayloadJsonNode() { - return payloadJsonNode; + + public void setInputOutputData(Map<String, String> inputOutputData) { + this.inputOutputData = inputOutputData; } - public void setPayloadJsonNode(JSONObject payloadJsonNode) { - this.payloadJsonNode = payloadJsonNode; + public Map<String, String> getInputOutputData() { + return inputOutputData; } - public List<String> getStatusPermutations() { - return statusPermutations; + public void setSearchSuggestionDisplayString(StringBuffer searchSuggestionDisplayString) { + this.searchSuggestionDisplayString = searchSuggestionDisplayString; } - public List<String> getSuggestableAttr() { - return suggestableAttr; + public void setFilterPayload(JSONObject filterPayload) { + this.filterPayload = filterPayload; } - - public List<String> getSuggestionInputPermutations() { - return this.suggestionInputPermutations; + + public void setFiltersSchemaUtility(UiFiltersSchemaUtility filtersSchemaUtility) { + this.filtersSchemaUtility = filtersSchemaUtility; } public void setStatusPermutations(List<String> statusPermutations) { this.statusPermutations = statusPermutations; } - public void setSuggestableAttr(ArrayList<String> attributes) { + public void setSuggestableAttr(List<String> 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 @@ -158,14 +158,40 @@ 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} * * Arguments: * {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<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getSuggestableEntityDescriptors(); if (!rootDescriptor.isEmpty()) { - List<String> suggestibleAttributes = extractSuggestableAttr(oxmEntities, entityType); + List<String> suggestibleAttrInPayload = new ArrayList<String>(); + List<String> 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<ArrayList<String>> 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<String> permutation : permutationsOfStatuses) { + List<ArrayList<String>> 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<String> 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<String, List<String>> 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<String> 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<String> createIndex = new ArrayList<String>(); - 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<String> createIndex = new ArrayList<String>(); - 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<String> 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<UiFilterConfig> filters = new ArrayList<>(); + + public UiFiltersConfig() {} + + @JsonCreator + public UiFiltersConfig(@JsonProperty("filters") final List<UiFilterConfig> filters) { + this.filters = filters; + } + + public List<UiFilterConfig> getFilters() { + return filters; + } + + public void setFilters(List<UiFilterConfig> 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<String, String> 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<ArrayList<String>> getSuggestionsPermutation(List<String> list) { - List<String> statusList = new ArrayList<>(list); - List<String> dupStatusList; - ArrayList<ArrayList<String>> uniqueList = new ArrayList<>(); - int mainLoopIndexCounter = 0; + public static ArrayList<ArrayList<String>> getUniqueListForSuggestions( + List<String> originalList) { + ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>(); + if (originalList.isEmpty()) { + lists.add(new ArrayList<String>()); + return lists; + } + List<String> list = new ArrayList<String>(originalList); + String head = list.get(0); + ArrayList<String> rest = new ArrayList<String>(list.subList(1, list.size())); + + for (ArrayList<String> activeList : getUniqueListForSuggestions(rest)) { + ArrayList<String> newList = new ArrayList<String>(); + newList.add(head); + newList.addAll(activeList); + lists.add(newList); + lists.add(activeList); + } + return lists; + } + + public static ArrayList<ArrayList<String>> getNonEmptyUniqueLists(List<String> list){ + ArrayList<ArrayList<String>> lists = getUniqueListForSuggestions(list); + // remove empty list from the power set + for (ArrayList<String> 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<String>() { - { - add(status); - } - }); + public static List<List<String>> getListPermutations(List<String> list) { + List<String> inputList = new ArrayList<String>(); + inputList.addAll(list); + if (inputList.size() == 0) { + List<List<String>> result = new ArrayList<List<String>>(); + result.add(new ArrayList<String>()); + return result; + } - // Remove all the elements to left till the current index - dupStatusList = truncateListUntill(statusList, mainLoopIndexCounter); + List<List<String>> listOfLists = new ArrayList<List<String>>(); - while (!dupStatusList.isEmpty()) { - ArrayList<String> suggListInIterate= new ArrayList<>(); - suggListInIterate.add(status); + String firstElement = inputList.remove(0); - for (String dupStatus : dupStatusList) { - suggListInIterate.add(dupStatus); - } + List<List<String>> recursiveReturn = getListPermutations(inputList); + for (List<String> li : recursiveReturn) { - uniqueList.add(suggListInIterate); - dupStatusList.remove(0); + for (int index = 0; index <= li.size(); index++) { + List<String> temp = new ArrayList<String>(li); + temp.add(index, firstElement); + listOfLists.add(temp); } - mainLoopIndexCounter++; } - - return uniqueList; + return listOfLists; } - private List<String> truncateListUntill(List<String> lists, int index) { - List<String> 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<String, List<String>> 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); + +} |