diff options
author | Shawn Severin <shawn.severin@amdocs.com> | 2017-12-08 12:53:42 -0500 |
---|---|---|
committer | Shawn Severin <shawn.severin@amdocs.com> | 2017-12-08 12:54:36 -0500 |
commit | e72b52437992610d38939700d38c42336cade235 (patch) | |
tree | 765c492fecd4a4de547cfc0d308086494c964fae | |
parent | 27da2e3395b009702c9032f9fa184f253747c8a7 (diff) |
Adding back-end support for UI filters
Issue-ID: AAI-543
Change-Id: I5cec6f340ab6c531f073e10e7902a84036c961d5
Signed-off-by: Shawn Severin <shawn.severin@amdocs.com>
202 files changed, 4002 insertions, 3525 deletions
diff --git a/src/main/java/org/onap/aai/sparky/HelloWorld.java b/src/main/java/org/onap/aai/sparky/HelloWorld.java index 688416b..2eff767 100644 --- a/src/main/java/org/onap/aai/sparky/HelloWorld.java +++ b/src/main/java/org/onap/aai/sparky/HelloWorld.java @@ -28,7 +28,7 @@ import org.apache.camel.Exchange; * The Class HelloWorld. */ public class HelloWorld { - + /** * Instantiates a new hello world. */ @@ -43,4 +43,4 @@ public class HelloWorld { exc.setOut(exc.getIn()); exc.getOut().setBody("Hello World!"); } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/JaxrsEchoService.java b/src/main/java/org/onap/aai/sparky/JaxrsEchoService.java index 878f618..8e7e0a2 100644 --- a/src/main/java/org/onap/aai/sparky/JaxrsEchoService.java +++ b/src/main/java/org/onap/aai/sparky/JaxrsEchoService.java @@ -36,7 +36,7 @@ import javax.ws.rs.Produces; */ @Path("/jaxrs-services") public class JaxrsEchoService { - + /** * Ping. * diff --git a/src/main/java/org/onap/aai/sparky/analytics/AbstractStatistics.java b/src/main/java/org/onap/aai/sparky/analytics/AbstractStatistics.java index aff70ae..9d2fec6 100644 --- a/src/main/java/org/onap/aai/sparky/analytics/AbstractStatistics.java +++ b/src/main/java/org/onap/aai/sparky/analytics/AbstractStatistics.java @@ -31,6 +31,7 @@ import java.util.concurrent.atomic.AtomicInteger; public class AbstractStatistics implements ComponentStatistics { private HashMap<String, AtomicInteger> namedCounters; + /** * @return the namedCounters */ @@ -69,7 +70,9 @@ public class AbstractStatistics implements ComponentStatistics { namedHistograms = new HashMap<String, HistogramSampler>(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.analytics.ComponentStatistics#addCounter(java.lang.String) */ /* @@ -90,7 +93,9 @@ public class AbstractStatistics implements ComponentStatistics { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.analytics.ComponentStatistics#pegCounter(java.lang.String) */ @Override @@ -104,7 +109,9 @@ public class AbstractStatistics implements ComponentStatistics { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.analytics.ComponentStatistics#incrementCounter(java.lang.String, int) */ @Override @@ -119,8 +126,11 @@ public class AbstractStatistics implements ComponentStatistics { } - /* (non-Javadoc) - * @see org.onap.aai.sparky.analytics.ComponentStatistics#addHistogram(java.lang.String, java.lang.String, long, int, int) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.analytics.ComponentStatistics#addHistogram(java.lang.String, + * java.lang.String, long, int, int) */ @Override public synchronized void addHistogram(String key, String histName, long maxYValue, int numBins, @@ -134,7 +144,9 @@ public class AbstractStatistics implements ComponentStatistics { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.analytics.ComponentStatistics#updateHistogram(java.lang.String, long) */ @Override @@ -146,7 +158,9 @@ public class AbstractStatistics implements ComponentStatistics { } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.analytics.ComponentStatistics#reset() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/analytics/HistogramSampler.java b/src/main/java/org/onap/aai/sparky/analytics/HistogramSampler.java index 1e9f970..b1d55f4 100644 --- a/src/main/java/org/onap/aai/sparky/analytics/HistogramSampler.java +++ b/src/main/java/org/onap/aai/sparky/analytics/HistogramSampler.java @@ -259,9 +259,8 @@ public final class HistogramSampler { if (counter == (numBins - 1)) { // outlier bin double leftBound = (stepSize * counter); - sb.append(indentPadding).append("\t") - .append(" x >= " + String.format(floatFormatStr, leftBound) + " : " - + histogramBins[counter]) + sb.append(indentPadding).append("\t").append( + " x >= " + String.format(floatFormatStr, leftBound) + " : " + histogramBins[counter]) .append("\n"); } else { diff --git a/src/main/java/org/onap/aai/sparky/analytics/HistoricalCounter.java b/src/main/java/org/onap/aai/sparky/analytics/HistoricalCounter.java index 47565ac..622693c 100644 --- a/src/main/java/org/onap/aai/sparky/analytics/HistoricalCounter.java +++ b/src/main/java/org/onap/aai/sparky/analytics/HistoricalCounter.java @@ -186,7 +186,9 @@ public class HistoricalCounter { value = 0.0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/config/oxm/CrossEntityReference.java b/src/main/java/org/onap/aai/sparky/config/oxm/CrossEntityReference.java index 3cb0a9d..e4a9f90 100644 --- a/src/main/java/org/onap/aai/sparky/config/oxm/CrossEntityReference.java +++ b/src/main/java/org/onap/aai/sparky/config/oxm/CrossEntityReference.java @@ -66,7 +66,9 @@ public class CrossEntityReference { referenceAttributes.add(additionalAttribute); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/config/oxm/OxmEntityDescriptor.java b/src/main/java/org/onap/aai/sparky/config/oxm/OxmEntityDescriptor.java index a62f22e..379cca2 100644 --- a/src/main/java/org/onap/aai/sparky/config/oxm/OxmEntityDescriptor.java +++ b/src/main/java/org/onap/aai/sparky/config/oxm/OxmEntityDescriptor.java @@ -42,7 +42,7 @@ public class OxmEntityDescriptor { private String geoLatName; private String geoLongName; - + private SuggestionSearchEntity suggestionSearchEntity; public String getEntityName() { @@ -141,15 +141,15 @@ public class OxmEntityDescriptor { return false; } - + public SuggestionSearchEntity getSuggestionSearchEntity() { return this.suggestionSearchEntity; } - + public void setSuggestionSearchEntity(SuggestionSearchEntity suggestionSearchEntity) { this.suggestionSearchEntity = suggestionSearchEntity; } - + /** * Checks for non-null, populated SuggestionSearchEntity. * @@ -164,7 +164,7 @@ public class OxmEntityDescriptor { } return false; } - + @Override public String toString() { return "OxmEntityDescriptor [entityName=" + entityName + ", primaryKeyAttributeName=" diff --git a/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoader.java b/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoader.java index 6841121..853a537 100644 --- a/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoader.java +++ b/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoader.java @@ -72,7 +72,7 @@ public class OxmModelLoader { private Map<String, HashMap<String, String>> geoEntityOxmModel = new LinkedHashMap<String, HashMap<String, String>>(); - + private Map<String, HashMap<String, String>> suggestionSearchEntityOxmModel = new LinkedHashMap<String, HashMap<String, String>>(); @@ -87,7 +87,7 @@ public class OxmModelLoader { private Map<String, OxmEntityDescriptor> geoEntityDescriptors = new HashMap<String, OxmEntityDescriptor>(); - + private Map<String, OxmEntityDescriptor> suggestionSearchEntityDescriptors = new HashMap<String, OxmEntityDescriptor>(); @@ -133,23 +133,22 @@ public class OxmModelLoader { public void loadModel(String version) { String fileName = loadOxmFileName(version); - try(FileInputStream inputStream = new FileInputStream(new File(fileName))) { - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStream); + try (FileInputStream inputStream = new FileInputStream(new File(fileName))) { + Map<String, Object> properties = new HashMap<String, Object>(); + properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStream); - final DynamicJAXBContext oxmContext = DynamicJAXBContextFactory - .createContextFromOXM(Thread.currentThread() - .getContextClassLoader(), properties); - parseOxmContext(oxmContext); - // populateSearchableOxmModel(); - LOG.info(AaiUiMsgs.OXM_LOAD_SUCCESS); + final DynamicJAXBContext oxmContext = DynamicJAXBContextFactory + .createContextFromOXM(Thread.currentThread().getContextClassLoader(), properties); + parseOxmContext(oxmContext); + // populateSearchableOxmModel(); + LOG.info(AaiUiMsgs.OXM_LOAD_SUCCESS); } catch (FileNotFoundException fnf) { - LOG.info(AaiUiMsgs.OXM_READ_ERROR_NONVERBOSE); - LOG.error(AaiUiMsgs.OXM_READ_ERROR_VERBOSE, fileName); + LOG.info(AaiUiMsgs.OXM_READ_ERROR_NONVERBOSE); + LOG.error(AaiUiMsgs.OXM_READ_ERROR_VERBOSE, fileName); } catch (Exception exc) { - LOG.info(AaiUiMsgs.OXM_PARSE_ERROR_NONVERBOSE); - LOG.error(AaiUiMsgs.OXM_PARSE_ERROR_VERBOSE, fileName, exc.getMessage()); + LOG.info(AaiUiMsgs.OXM_PARSE_ERROR_NONVERBOSE); + LOG.error(AaiUiMsgs.OXM_PARSE_ERROR_VERBOSE, fileName, exc.getMessage()); } } @@ -163,7 +162,7 @@ public class OxmModelLoader { List<Descriptor> descriptorsList = oxmContext.getXMLContext().getDescriptors(); for (@SuppressWarnings("rawtypes") - Descriptor desc : descriptorsList) { + Descriptor desc : descriptorsList) { DynamicType entity = oxmContext.getDynamicType(desc.getAlias()); @@ -185,7 +184,7 @@ public class OxmModelLoader { Map<String, String> properties = entity.getDescriptor().getProperties(); if (properties != null) { for (Map.Entry<String, String> entry : properties.entrySet()) { - + if (entry.getKey().equalsIgnoreCase("searchable")) { oxmProperties.put("searchableAttributes", entry.getValue()); } else if (entry.getKey().equalsIgnoreCase("crossEntityReference")) { @@ -201,29 +200,29 @@ public class OxmModelLoader { } else if (entry.getKey().equalsIgnoreCase("containsSuggestibleProps")) { oxmProperties.put("containsSuggestibleProps", "true"); - + Vector<DatabaseMapping> descriptorMaps = entity.getDescriptor().getMappings(); List<String> listOfSuggestableAttributes = new ArrayList<String>(); - + for (DatabaseMapping descMap : descriptorMaps) { if (descMap.isAbstractDirectMapping()) { - + if (descMap.getProperties().get("suggestibleOnSearch") != null) { - String suggestableOnSearchString = String.valueOf( - descMap.getProperties().get("suggestibleOnSearch")); - + String suggestableOnSearchString = + String.valueOf(descMap.getProperties().get("suggestibleOnSearch")); + boolean isSuggestibleOnSearch = Boolean.valueOf(suggestableOnSearchString); if (isSuggestibleOnSearch) { /* Grab attribute types for suggestion */ - String attributeName = descMap.getField().getName() - .replaceAll("/text\\(\\)", ""); + String attributeName = + descMap.getField().getName().replaceAll("/text\\(\\)", ""); listOfSuggestableAttributes.add(attributeName); - + if (descMap.getProperties().get("suggestionVerbs") != null) { - String suggestionVerbsString = String.valueOf( - descMap.getProperties().get("suggestionVerbs")); - + String suggestionVerbsString = + String.valueOf(descMap.getProperties().get("suggestionVerbs")); + oxmProperties.put("suggestionVerbs", suggestionVerbsString); } } @@ -231,8 +230,8 @@ public class OxmModelLoader { } } if (!listOfSuggestableAttributes.isEmpty()) { - oxmProperties.put("suggestibleAttributes", String.join(",", - listOfSuggestableAttributes)); + oxmProperties.put("suggestibleAttributes", + String.join(",", listOfSuggestableAttributes)); } } else if (entry.getKey().equalsIgnoreCase("suggestionAliases")) { oxmProperties.put("suggestionAliases", entry.getValue()); @@ -254,7 +253,7 @@ public class OxmModelLoader { if (oxmProperties.containsKey("geoLat") && oxmProperties.containsKey("geoLong")) { geoEntityOxmModel.put(entityName, oxmProperties); } - + if (oxmProperties.containsKey("containsSuggestibleProps")) { suggestionSearchEntityOxmModel.put(entityName, oxmProperties); } @@ -294,12 +293,12 @@ public class OxmModelLoader { entity.setGeoLatName(attribute.get("geoLat")); entity.setGeoLongName(attribute.get("geoLong")); } - + if (attribute.containsKey("suggestionVerbs")) { String entityName = attribute.get("entityName"); SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity(this); suggestionSearchEntity.setEntityType(entityName); - + entity.setSuggestionSearchEntity(suggestionSearchEntity); } @@ -354,39 +353,39 @@ public class OxmModelLoader { } crossReferenceEntityDescriptors.put(attribute.get("entityName"), entity); } - - for (Entry<String, HashMap<String, String>> suggestionEntityModel : - suggestionSearchEntityOxmModel.entrySet()) { + + for (Entry<String, HashMap<String, String>> suggestionEntityModel : suggestionSearchEntityOxmModel + .entrySet()) { HashMap<String, String> attribute = suggestionEntityModel.getValue(); - + String entityName = attribute.get("entityName"); SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity(this); suggestionSearchEntity.setEntityType(entityName); - + if (attribute.get("suggestionVerbs") != null) { - suggestionSearchEntity.setSuggestionConnectorWords(Arrays.asList( - attribute.get("suggestionVerbs").split(","))); + suggestionSearchEntity.setSuggestionConnectorWords( + Arrays.asList(attribute.get("suggestionVerbs").split(","))); } - + if (attribute.get("suggestionAliases") != null) { - suggestionSearchEntity.setSuggestionAliases(Arrays.asList( - attribute.get("suggestionAliases").split(","))); + suggestionSearchEntity + .setSuggestionAliases(Arrays.asList(attribute.get("suggestionAliases").split(","))); } - + if (attribute.get("suggestibleAttributes") != null) { - suggestionSearchEntity.setSuggestionPropertyTypes(Arrays.asList( - attribute.get("suggestibleAttributes").split(","))); + suggestionSearchEntity.setSuggestionPropertyTypes( + Arrays.asList(attribute.get("suggestibleAttributes").split(","))); } - + OxmEntityDescriptor entity = new OxmEntityDescriptor(); entity.setSuggestionSearchEntity(suggestionSearchEntity); entity.setEntityName(entityName); - + if (attribute.get("primaryKeyAttributeNames") != null) { entity.setPrimaryKeyAttributeName( Arrays.asList(attribute.get("primaryKeyAttributeNames").replace(" ", "").split(","))); } - + suggestionSearchEntityDescriptors.put(entityName, entity); } } @@ -445,7 +444,7 @@ public class OxmModelLoader { public String loadOxmFileName(String version) { return new String(TierSupportUiConstants.CONFIG_OXM_LOCATION + "aai_oxm_" + version + ".xml"); } - + /* * Get the original representation of the OXM Model */ @@ -499,7 +498,7 @@ public class OxmModelLoader { public Map<String, OxmEntityDescriptor> getGeoEntityDescriptors() { return geoEntityDescriptors; } - + public Map<String, OxmEntityDescriptor> getSuggestionSearchEntityDescriptors() { return suggestionSearchEntityDescriptors; } diff --git a/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilter.java b/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilter.java index cf25c72..0ddf80a 100644 --- a/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilter.java +++ b/src/main/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilter.java @@ -39,8 +39,11 @@ import org.onap.aai.cl.mdc.MdcContext; * The Class OxmModelLoaderFilter. */ public class OxmModelLoaderFilter implements Filter { - /* (non-Javadoc) - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) + /* + * (non-Javadoc) + * + * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, + * javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) @@ -54,16 +57,17 @@ public class OxmModelLoaderFilter implements Filter { chain.doFilter(request, response); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { - String txnID = NodeUtils.getRandomTxnId(); - MdcContext.initialize(txnID, "OxmModelLoaderFilter", "", - "Init", ""); + String txnID = NodeUtils.getRandomTxnId(); + MdcContext.initialize(txnID, "OxmModelLoaderFilter", "", "Init", ""); - try { + try { OxmModelLoader.getInstance(); } catch (Exception exc) { throw new ServletException("Caught an exception while initializing OXM model loader filter", @@ -72,7 +76,9 @@ public class OxmModelLoaderFilter implements Filter { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.Filter#destroy() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/NetworkTransaction.java b/src/main/java/org/onap/aai/sparky/dal/NetworkTransaction.java index 16644f0..da24c80 100644 --- a/src/main/java/org/onap/aai/sparky/dal/NetworkTransaction.java +++ b/src/main/java/org/onap/aai/sparky/dal/NetworkTransaction.java @@ -117,7 +117,9 @@ public class NetworkTransaction { this.descriptor = descriptor; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapter.java b/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapter.java index 41bf467..08a6584 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapter.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapter.java @@ -61,15 +61,15 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor private static final Logger LOG = LoggerFactory.getInstance().getLogger(ActiveInventoryAdapter.class); - + private static final String HEADER_TRANS_ID = "X-TransactionId"; private static final String HEADER_FROM_APP_ID = "X-FromAppId"; private static final String HEADER_AUTHORIZATION = "Authorization"; private static final String TRANSACTION_ID_PREFIX = "txnId-"; private static final String UI_APP_NAME = "AAI-UI"; - - + + private ActiveInventoryConfig config; /** @@ -98,7 +98,7 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor sslContextFactory.setServerCertificationChainValidationEnabled( config.getAaiSslConfig().isValidateServerCertificateChain()); - + if (config.getAaiRestConfig().getAuthenticationMode() == RestAuthenticationMode.SSL_CERT) { sslContextFactory.setClientCertFileName(config.getAaiSslConfig().getKeystoreFilename()); sslContextFactory.setClientCertPassword(config.getAaiSslConfig().getKeystorePassword()); @@ -110,8 +110,12 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestfulDataAccessor#setClientDefaults(com.sun.jersey.api.client.Client, java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.rest.RestfulDataAccessor#setClientDefaults(com.sun.jersey.api.client. + * Client, java.lang.String, java.lang.String, java.lang.String) */ @Override protected Builder setClientDefaults(Client client, String url, String payloadContentType, @@ -146,29 +150,34 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor final String basePath = aaiRestConfig.getResourceBasePath(); return String.format("https://%s:%s%s%s", host, port, basePath, resourceUrl); } - - public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams) throws Exception { - + + public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams) + throws Exception { + URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query")); - - for( String queryParam : queryParams) { + + for (String queryParam : queryParams) { urlBuilder.addParameter("key", queryParam); } - + urlBuilder.addParameter("start-node-type", startNodeType); urlBuilder.addParameter("include", startNodeType); - + final String constructedLink = urlBuilder.toString(); - + // TODO: debug log for constructed link return constructedLink; -} + } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinksByEntityType(java.lang.String) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinksByEntityType(java.lang. + * String) */ @Override public OperationResult getSelfLinksByEntityType(String entityType) throws Exception { @@ -177,7 +186,7 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor * For this one, I want to dynamically construct the nodes-query for self-link discovery as a * utility method that will use the OXM model entity data to drive the query as well. */ - + if (entityType == null) { throw new NullPointerException( "Failed to getSelfLinksByEntityType() because entityType is null"); @@ -204,8 +213,12 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinkForEntity(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinkForEntity(java.lang.String, + * java.lang.String, java.lang.String) */ @Override public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName, @@ -295,8 +308,12 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor return doGet(url, acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#queryActiveInventoryWithRetries(java.lang.String, java.lang.String, int) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#queryActiveInventoryWithRetries(java. + * lang.String, java.lang.String, int) */ @Override public OperationResult queryActiveInventoryWithRetries(String url, String responseType, @@ -371,7 +388,9 @@ public class ActiveInventoryAdapter extends RestfulDataAccessor } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestfulDataAccessor#shutdown() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryDataProvider.java b/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryDataProvider.java index ae7c852..21fb4e6 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryDataProvider.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryDataProvider.java @@ -75,7 +75,8 @@ public interface ActiveInventoryDataProvider extends RestDataProvider { * @return * @throws Exception */ - String getGenericQueryForSelfLink(String startNodeType, List<String> queryKeyParams) throws Exception; + String getGenericQueryForSelfLink(String startNodeType, List<String> queryKeyParams) + throws Exception; /* * (non-Javadoc) diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatistics.java b/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatistics.java index 69e7808..c1ed906 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatistics.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatistics.java @@ -291,7 +291,7 @@ public class ActiveInventoryEntityStatistics { sb.append("\n ") .append(String.format( "%-30s TOTAL: %-12d FOUND: %-12d NO_PAYLOAD:" - + " %-12d NOT_FOUND: %-12d NUM_RETRIES: %-12d ERROR: %-12d", + + " %-12d NOT_FOUND: %-12d NUM_RETRIES: %-12d ERROR: %-12d", counterEntityKey, totalValue, foundValue, noPayloadValue, notFoundValue, numRetriesValue, errorValue)); } diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfig.java b/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfig.java index c1b0f4e..e88ca51 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfig.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfig.java @@ -35,18 +35,19 @@ import org.onap.aai.sparky.util.Encryptor; import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants; import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; + /** * The Class ActiveInventoryConfig. */ public class ActiveInventoryConfig { - - + + public static final String CONFIG_FILE = TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION + "aai.properties"; private static ActiveInventoryConfig instance; - private static final Logger LOG = LoggerFactory.getInstance().getLogger( - ActiveInventoryConfig.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(ActiveInventoryConfig.class); private static final String HTTP_SCHEME = "http"; private static final String HTTPS_SCHEME = "https"; @@ -79,7 +80,7 @@ public class ActiveInventoryConfig { } - + protected ActiveInventoryConfig(Properties props) throws Exception { aaiRestConfig = new ActiveInventoryRestConfig(props); @@ -116,7 +117,7 @@ public class ActiveInventoryConfig { public void setAaiSslConfig(ActiveInventorySslConfig aaiSslConfig) { this.aaiSslConfig = aaiSslConfig; } - + public String repairSelfLink(String selflink) { if (selflink == null) { @@ -142,17 +143,20 @@ public class ActiveInventoryConfig { return builder.build().toString(); } - + public static String extractResourcePath(String selflink) { - try { - return new URI(selflink).getPath(); - } catch (URISyntaxException uriSyntaxException) { - LOG.error(AaiUiMsgs.ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK, uriSyntaxException.getMessage()); - return selflink; - } - } - - /* (non-Javadoc) + try { + return new URI(selflink).getPath(); + } catch (URISyntaxException uriSyntaxException) { + LOG.error(AaiUiMsgs.ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK, + uriSyntaxException.getMessage()); + return selflink; + } + } + + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfig.java b/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfig.java index 4f6fdee..5ed537b 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfig.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfig.java @@ -82,7 +82,7 @@ public class ActiveInventoryRestConfig { private String resourceBasePath; private List<String> shallowEntities; - + private RestAuthenticationMode authenticationMode; public List<String> getShallowEntities() { @@ -131,17 +131,19 @@ public class ActiveInventoryRestConfig { * cached instance is < maxTimeToLiveInMs. */ maxTimeToLiveInMs = Long.parseLong(cacheProps.getProperty("maxTimeToLiveInMs", "-1")); - authenticationMode = RestAuthenticationMode.getRestAuthenticationMode(restProps.getProperty("authenticationMode", RestAuthenticationMode.SSL_CERT.getAuthenticationModeLabel())); + authenticationMode = + RestAuthenticationMode.getRestAuthenticationMode(restProps.getProperty("authenticationMode", + RestAuthenticationMode.SSL_CERT.getAuthenticationModeLabel())); /* - * In any kind of error scenario, set the authentication mode to SSL_CERT as our default. - * This is an arbitrary default, but was chosen based on the way this code worked before - * introduction of the SSL Basic Auth settings. + * In any kind of error scenario, set the authentication mode to SSL_CERT as our default. This + * is an arbitrary default, but was chosen based on the way this code worked before introduction + * of the SSL Basic Auth settings. */ - if ( authenticationMode == RestAuthenticationMode.UNKNOWN_MODE) { + if (authenticationMode == RestAuthenticationMode.UNKNOWN_MODE) { authenticationMode = RestAuthenticationMode.SSL_CERT; } - + } public RestAuthenticationMode getAuthenticationMode() { @@ -253,11 +255,13 @@ public class ActiveInventoryRestConfig { this.port = port; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ - - + + public void setResourceBasePath(String resourceBasePath) { this.resourceBasePath = resourceBasePath; } diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfig.java b/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfig.java index 98e3eed..080a787 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfig.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfig.java @@ -48,7 +48,7 @@ public class ActiveInventorySslConfig { private String basicAuthUsername; private String basicAuthPassword; - + /** * Instantiates a new active inventory ssl config. * @@ -86,12 +86,12 @@ public class ActiveInventorySslConfig { truststoreFilename = TierSupportUiConstants.CONFIG_AUTH_LOCATION + sslProps.getProperty("truststore.filename"); - + basicAuthUsername = sslProps.getProperty("basicAuth.username"); basicAuthPassword = decryptPassword(sslProps.getProperty("basicAuth.password")); - - } - + + } + private String decryptPassword(String encryptedPassword) { try { @@ -109,7 +109,7 @@ public class ActiveInventorySslConfig { } } - + public String getBasicAuthUsername() { return basicAuthUsername; } @@ -190,11 +190,10 @@ public class ActiveInventorySslConfig { public void setValidateServerCertificateChain(boolean validateServerCertificateChain) { this.validateServerCertificateChain = validateServerCertificateChain; } - + public String getBasicAuthenticationCredentials() { - String usernameAndPassword = getBasicAuthUsername() + ":" - + getBasicAuthPassword(); + String usernameAndPassword = getBasicAuthUsername() + ":" + getBasicAuthPassword(); return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes()); } @@ -212,7 +211,9 @@ public class ActiveInventorySslConfig { this.enableSslDebug = enableSslDebug; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/aai/enums/RestAuthenticationMode.java b/src/main/java/org/onap/aai/sparky/dal/aai/enums/RestAuthenticationMode.java index 743b031..846fb2f 100644 --- a/src/main/java/org/onap/aai/sparky/dal/aai/enums/RestAuthenticationMode.java +++ b/src/main/java/org/onap/aai/sparky/dal/aai/enums/RestAuthenticationMode.java @@ -30,10 +30,8 @@ package org.onap.aai.sparky.dal.aai.enums; */ public enum RestAuthenticationMode { - HTTP_NOAUTH("HTTP_NO_AUTH"), - SSL_BASIC("SSL_BASIC"), - SSL_CERT("SSL_CERT"), - UNKNOWN_MODE("UNKNOWN_MODE"); + HTTP_NOAUTH("HTTP_NO_AUTH"), SSL_BASIC("SSL_BASIC"), SSL_CERT("SSL_CERT"), UNKNOWN_MODE( + "UNKNOWN_MODE"); private String authenticationModeLabel; @@ -44,23 +42,23 @@ public enum RestAuthenticationMode { public String getAuthenticationModeLabel() { return authenticationModeLabel; } - + public static RestAuthenticationMode getRestAuthenticationMode(String authenticationMode) { RestAuthenticationMode mappedMode = RestAuthenticationMode.UNKNOWN_MODE; - + if (authenticationMode == null) { return mappedMode; } try { mappedMode = RestAuthenticationMode.valueOf(authenticationMode); - } catch ( Exception exc) { + } catch (Exception exc) { mappedMode = RestAuthenticationMode.UNKNOWN_MODE; } return mappedMode; } - + } diff --git a/src/main/java/org/onap/aai/sparky/dal/cache/EntityCache.java b/src/main/java/org/onap/aai/sparky/dal/cache/EntityCache.java index c1b6efa..04baf7c 100644 --- a/src/main/java/org/onap/aai/sparky/dal/cache/EntityCache.java +++ b/src/main/java/org/onap/aai/sparky/dal/cache/EntityCache.java @@ -30,7 +30,7 @@ import org.onap.aai.sparky.dal.rest.OperationResult; * @author davea. */ public interface EntityCache { - + /** * Gets the. * diff --git a/src/main/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCache.java b/src/main/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCache.java index 6967d16..5245e29 100644 --- a/src/main/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCache.java +++ b/src/main/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCache.java @@ -47,8 +47,11 @@ public class InMemoryEntityCache implements EntityCache { cachedEntityData = new ConcurrentHashMap<String, OperationResult>(); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.cache.EntityCache#put(java.lang.String, org.onap.aai.sparky.dal.rest.OperationResult) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.cache.EntityCache#put(java.lang.String, + * org.onap.aai.sparky.dal.rest.OperationResult) */ @Override public void put(String key, OperationResult data) { @@ -64,7 +67,9 @@ public class InMemoryEntityCache implements EntityCache { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.cache.EntityCache#get(java.lang.String, java.lang.String) */ @Override @@ -77,7 +82,9 @@ public class InMemoryEntityCache implements EntityCache { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.cache.EntityCache#shutdown() */ @Override @@ -87,7 +94,9 @@ public class InMemoryEntityCache implements EntityCache { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.cache.EntityCache#clear() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/cache/PersistentEntityCache.java b/src/main/java/org/onap/aai/sparky/dal/cache/PersistentEntityCache.java index c2b4b42..f64b3c7 100644 --- a/src/main/java/org/onap/aai/sparky/dal/cache/PersistentEntityCache.java +++ b/src/main/java/org/onap/aai/sparky/dal/cache/PersistentEntityCache.java @@ -167,7 +167,9 @@ public class PersistentEntityCache implements EntityCache { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.cache.EntityCache#get(java.lang.String, java.lang.String) */ @Override @@ -195,8 +197,11 @@ public class PersistentEntityCache implements EntityCache { } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.cache.EntityCache#put(java.lang.String, org.onap.aai.sparky.dal.rest.OperationResult) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.cache.EntityCache#put(java.lang.String, + * org.onap.aai.sparky.dal.rest.OperationResult) */ @Override public void put(String key, OperationResult data) { @@ -222,7 +227,9 @@ public class PersistentEntityCache implements EntityCache { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.cache.EntityCache#shutdown() */ @Override @@ -233,7 +240,9 @@ public class PersistentEntityCache implements EntityCache { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.cache.EntityCache#clear() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchAdapter.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchAdapter.java index 19bcf1a..9962bcb 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchAdapter.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchAdapter.java @@ -51,7 +51,9 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { this.esConfig = esConfig; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String) */ @Override @@ -59,7 +61,9 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { return restDataProvider.doGet(url, acceptContentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String, java.lang.String) */ @Override @@ -67,31 +71,42 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { return restDataProvider.doDelete(url, acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, + * java.lang.String) */ @Override public OperationResult doPost(String url, String jsonPayload, String acceptContentType) { return restDataProvider.doPost(url, jsonPayload, acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, + * java.lang.String) */ @Override public OperationResult doPut(String url, String jsonPayload, String acceptContentType) { return restDataProvider.doPut(url, jsonPayload, acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, + * java.lang.String) */ @Override public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) { return restDataProvider.doPatch(url, jsonPayload, acceptContentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String) */ @Override @@ -99,7 +114,9 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { return restDataProvider.doHead(url, acceptContentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#clearCache() */ @Override @@ -107,8 +124,11 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { restDataProvider.clearCache(); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.elasticsearch.ElasticSearchDataProvider#doBulkOperation(java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.elasticsearch.ElasticSearchDataProvider#doBulkOperation(java.lang. + * String, java.lang.String) */ @Override public OperationResult doBulkOperation(String url, String payload) { @@ -118,7 +138,9 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { RestfulDataAccessor.APPLICATION_JSON); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.elasticsearch.ElasticSearchDataProvider#shutdown() */ @Override @@ -126,8 +148,12 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { restDataProvider.shutdown(); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.onap.aai.sparky.dal.rest.HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.onap.aai.sparky.dal.rest. + * HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public OperationResult doRestfulOperation(HttpMethod method, String url, String payload, @@ -136,8 +162,12 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.elasticsearch.ElasticSearchDataProvider#buildBulkImportOperationRequest(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.elasticsearch.ElasticSearchDataProvider#buildBulkImportOperationRequest + * (java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public String buildBulkImportOperationRequest(String index, String type, String id, @@ -155,8 +185,8 @@ public class ElasticSearchAdapter implements ElasticSearchDataProvider { @Override public OperationResult retrieveEntityById(String entityId) throws Exception { - String url = esConfig.getElasticFullUrl("/" +entityId); - return doGet( url, "application/json"); + String url = esConfig.getElasticFullUrl("/" + entityId); + return doGet(url, "application/json"); } /** diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchDataProvider.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchDataProvider.java index 78aea91..416e251 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchDataProvider.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchDataProvider.java @@ -51,10 +51,12 @@ public interface ElasticSearchDataProvider extends RestDataProvider { * @return the operation result */ OperationResult doBulkOperation(String url, String payload); - + OperationResult retrieveEntityById(String entityId) throws Exception; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#shutdown() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatistics.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatistics.java index 42a0fcd..50d318b 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatistics.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatistics.java @@ -256,12 +256,11 @@ public class ElasticSearchEntityStatistics { int deletedValue = (deleted == null) ? 0 : deleted.get(); int errorValue = (error == null) ? 0 : error.get(); - sb.append("\n ") - .append(String.format( - "%-30s TOTAL: %-12d CREATED: %-12d MODIFIED:" + sb.append("\n ").append(String.format( + "%-30s TOTAL: %-12d CREATED: %-12d MODIFIED:" + " %-12d OTHER_2XX: %-12d DELETED: %-12d ERROR: %-12d", - counterEntityKey, totalValue, createdValue, modifiedValue, otherSuccessValue, - deletedValue, errorValue)); + counterEntityKey, totalValue, createdValue, modifiedValue, otherSuccessValue, + deletedValue, errorValue)); } return sb.toString(); } diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/HashQueryResponse.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/HashQueryResponse.java index 7b6dc95..646916b 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/HashQueryResponse.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/HashQueryResponse.java @@ -28,28 +28,32 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class HashQueryResponse { private String jsonPayload = null; private OperationResult opResult = null; - + public HashQueryResponse() { this(null, null); } - + public HashQueryResponse(String jsonPayload, OperationResult opResult) { this.jsonPayload = jsonPayload; this.opResult = opResult; } - + public String getJsonPayload() { return jsonPayload; } + public void setJsonPayload(String jsonPayload) { this.jsonPayload = jsonPayload; } + public OperationResult getOpResult() { return opResult; } + public void setOpResult(OperationResult opResult) { this.opResult = opResult; } + @Override public String toString() { return "HashQueryResponse [jsonPayload=" + jsonPayload + ", opResult=" + opResult + "]"; diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/SearchAdapter.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/SearchAdapter.java index 0682867..200f405 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/SearchAdapter.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/SearchAdapter.java @@ -50,7 +50,7 @@ import org.onap.aai.cl.mdc.MdcContext; public class SearchAdapter { private static final Logger LOG = LoggerFactory.getInstance().getLogger(SearchAdapter.class); - + private RestClient client; /** @@ -93,7 +93,8 @@ public class SearchAdapter { /** * Instantiates a new search adapter. - * @throws Exception + * + * @throws Exception */ public SearchAdapter() throws Exception { sasConfig = SearchServiceConfig.getConfig(); @@ -118,8 +119,8 @@ public class SearchAdapter { } public OperationResult doPost(String url, String jsonPayload, String acceptContentType) { - org.onap.aai.restclient.client.OperationResult or = client.post(url, jsonPayload, getTxnHeader(), - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + org.onap.aai.restclient.client.OperationResult or = client.post(url, jsonPayload, + getTxnHeader(), MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); return new OperationResult(or.getResultCode(), or.getResult()); } diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java index f8385a1..68e4151 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java @@ -77,7 +77,7 @@ public class ElasticSearchConfig { private String autoSuggestSettingsFileName; private String autoSuggestMappingsFileName; - + private String dynamicMappingsFileName; private static final String IP_ADDRESS_DEFAULT = "localhost"; @@ -106,7 +106,7 @@ public class ElasticSearchConfig { private static final String ENTITY_AUTO_SUGGEST_MAPPINGS_FILE_DEFAULT = TierSupportUiConstants.ENTITY_AUTO_SUGGEST_SETTINGS_FILE_DEFAULT; - + private static final String ENTITY_DYNAMIC_MAPPINGS_FILE_DEFAULT = TierSupportUiConstants.ENTITY_DYNAMIC_MAPPINGS_FILE_DEFAULT; @@ -332,16 +332,17 @@ public class ElasticSearchConfig { TierSupportUiConstants.getConfigPath(this.getSettingsFileName())); } - public String getDynamicMappings() throws ElasticSearchOperationException{ + public String getDynamicMappings() throws ElasticSearchOperationException { return getConfigAsString("mapping", TierSupportUiConstants.getConfigPath(this.getDynamicMappingsFileName())); } + public String getElasticSearchMappings() throws ElasticSearchOperationException { return getConfigAsString("mapping", TierSupportUiConstants.getConfigPath(this.getMappingsFileName())); } - public String getElasticSearchEntityCountHistoryMappings() + public String getElasticSearchEntityCountHistoryMappings() throws ElasticSearchOperationException { return getConfigAsString("mapping", TierSupportUiConstants.getConfigPath(this.getEntityCountHistoryMappingsFileName())); @@ -477,7 +478,7 @@ public class ElasticSearchConfig { } } - + public String buildAutosuggestionTableConfig() throws ElasticSearchOperationException { JsonNode esSettingsNode; @@ -504,7 +505,7 @@ public class ElasticSearchConfig { } } - + /** * @return the instance */ @@ -636,12 +637,11 @@ public class ElasticSearchConfig { + ", clusterName=" + clusterName + ", mappingsFileName=" + mappingsFileName + ", settingsFileName=" + settingsFileName + ", syncAdapterMaxConcurrentWorkers=" + syncAdapterMaxConcurrentWorkers + ", auditIndexName=" + auditIndexName - + ", entityCountHistoryIndex=" - + entityCountHistoryIndex + ", autosuggestIndexname=" + autosuggestIndexname - + ", entityCountHistoryMappingsFileName=" + entityCountHistoryMappingsFileName - + ", autoSuggestSettingsFileName=" + autoSuggestSettingsFileName - + ", autoSuggestMappingsFileName=" + autoSuggestMappingsFileName - + ", dynamicMappingsFileName=" + dynamicMappingsFileName + ", processorConfig=" - + processorConfig + "]"; + + ", entityCountHistoryIndex=" + entityCountHistoryIndex + ", autosuggestIndexname=" + + autosuggestIndexname + ", entityCountHistoryMappingsFileName=" + + entityCountHistoryMappingsFileName + ", autoSuggestSettingsFileName=" + + autoSuggestSettingsFileName + ", autoSuggestMappingsFileName=" + + autoSuggestMappingsFileName + ", dynamicMappingsFileName=" + dynamicMappingsFileName + + ", processorConfig=" + processorConfig + "]"; } } diff --git a/src/main/java/org/onap/aai/sparky/dal/rest/OperationResult.java b/src/main/java/org/onap/aai/sparky/dal/rest/OperationResult.java index c147cb0..419dc88 100644 --- a/src/main/java/org/onap/aai/sparky/dal/rest/OperationResult.java +++ b/src/main/java/org/onap/aai/sparky/dal/rest/OperationResult.java @@ -133,7 +133,7 @@ public class OperationResult { public void setResult(String result) { this.result = result; } - + /** * Sets the result. * @@ -180,7 +180,9 @@ public class OperationResult { this.numRequestRetries = numRequestRetries; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/rest/RestClientBuilder.java b/src/main/java/org/onap/aai/sparky/dal/rest/RestClientBuilder.java index c32a9b9..77f04e0 100644 --- a/src/main/java/org/onap/aai/sparky/dal/rest/RestClientBuilder.java +++ b/src/main/java/org/onap/aai/sparky/dal/rest/RestClientBuilder.java @@ -38,9 +38,8 @@ import org.onap.aai.sparky.security.SecurityContextFactoryImpl; * This is a generic REST Client builder with flexible security validation. Sometimes it's nice to * be able to disable server chain cert validation and hostname validation to work-around lab * issues, but at the same time be able to provide complete validation with client cert + hostname + - * server cert chain validation. - * I used the ModelLoader REST client as a base and merged in the TSUI client I wrote which also - * validates the server hostname and server certificate chain. + * server cert chain validation. I used the ModelLoader REST client as a base and merged in the TSUI + * client I wrote which also validates the server hostname and server certificate chain. * * @author DAVEA * diff --git a/src/main/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessor.java b/src/main/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessor.java index 78da999..c229de1 100644 --- a/src/main/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessor.java +++ b/src/main/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessor.java @@ -134,8 +134,12 @@ public class RestfulDataAccessor implements RestDataProvider { return null; } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.onap.aai.sparky.dal.rest.HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see + * org.onap.aai.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.onap.aai.sparky.dal.rest. + * HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public OperationResult doRestfulOperation(HttpMethod method, String url, String payload, @@ -255,7 +259,9 @@ public class RestfulDataAccessor implements RestDataProvider { this.resourceNotFoundErrorsSurpressed = resourceNotFoundErrorsSurpressed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String) */ @Override @@ -263,7 +269,9 @@ public class RestfulDataAccessor implements RestDataProvider { return doRestfulOperation(HttpMethod.GET, url, null, null, acceptContentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String, java.lang.String) */ @Override @@ -271,8 +279,11 @@ public class RestfulDataAccessor implements RestDataProvider { return doRestfulOperation(HttpMethod.DELETE, url, null, null, acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, + * java.lang.String) */ @Override public OperationResult doPost(String url, String jsonPayload, String acceptContentType) { @@ -280,8 +291,11 @@ public class RestfulDataAccessor implements RestDataProvider { acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, + * java.lang.String) */ @Override public OperationResult doPut(String url, String jsonPayload, String acceptContentType) { @@ -289,8 +303,11 @@ public class RestfulDataAccessor implements RestDataProvider { acceptContentType); } - /* (non-Javadoc) - * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, + * java.lang.String) */ @Override public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) { @@ -298,7 +315,9 @@ public class RestfulDataAccessor implements RestDataProvider { acceptContentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String) */ @Override @@ -328,7 +347,9 @@ public class RestfulDataAccessor implements RestDataProvider { return builder; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#shutdown() */ @Override @@ -340,7 +361,9 @@ public class RestfulDataAccessor implements RestDataProvider { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.dal.rest.RestDataProvider#clearCache() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/dal/sas/config/SearchServiceConfig.java b/src/main/java/org/onap/aai/sparky/dal/sas/config/SearchServiceConfig.java index ff3a151..0925d71 100644 --- a/src/main/java/org/onap/aai/sparky/dal/sas/config/SearchServiceConfig.java +++ b/src/main/java/org/onap/aai/sparky/dal/sas/config/SearchServiceConfig.java @@ -52,11 +52,11 @@ public class SearchServiceConfig { private String version; private String type; - + private String certName; - + private String keystorePassword; - + private String keystore; private static final String IP_ADDRESS_DEFAULT = "localhost"; @@ -98,18 +98,17 @@ public class SearchServiceConfig { */ private void initializeProperties() { Properties props = ConfigHelper.loadConfigFromExplicitPath(CONFIG_FILE); - + Properties sasProps = ConfigHelper.getConfigWithPrefix("search-service", props); - + ipAddress = sasProps.getProperty("ipAddress", IP_ADDRESS_DEFAULT); httpPort = sasProps.getProperty("httpPort", "" + HTTP_PORT_DEFAULT); version = sasProps.getProperty("version", "" + VERSION_DEFAULT); indexName = sasProps.getProperty("indexName", INDEX_NAME_DEFAULT); auditIndexName = sasProps.getProperty("auditIndexName", AUDIT_INDEX_NAME_DEFAULT); - topographicalSearchIndex = sasProps.getProperty("topographicalIndexName", - TOPOGRAPHICAL_INDEX_NAME_DEFAULT); - certName = - sasProps.getProperty("ssl.cert-name", "aai-client-cert.p12"); + topographicalSearchIndex = + sasProps.getProperty("topographicalIndexName", TOPOGRAPHICAL_INDEX_NAME_DEFAULT); + certName = sasProps.getProperty("ssl.cert-name", "aai-client-cert.p12"); keystorePassword = sasProps.getProperty("ssl.keystore-password", "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o"); keystore = sasProps.getProperty("ssl.keystore", "tomcat_keystore"); @@ -178,8 +177,8 @@ public class SearchServiceConfig { public void setType(String type) { this.type = type; } - - + + public String getCertName() { return certName; } diff --git a/src/main/java/org/onap/aai/sparky/dal/servlet/ResettableStreamHttpServletRequest.java b/src/main/java/org/onap/aai/sparky/dal/servlet/ResettableStreamHttpServletRequest.java index 9845330..4713222 100644 --- a/src/main/java/org/onap/aai/sparky/dal/servlet/ResettableStreamHttpServletRequest.java +++ b/src/main/java/org/onap/aai/sparky/dal/servlet/ResettableStreamHttpServletRequest.java @@ -98,7 +98,9 @@ public class ResettableStreamHttpServletRequest extends HttpServletRequestWrappe this.buffer = new ByteArrayInputStream(contents); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.io.InputStream#read() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/logging/AaiUiMsgs.java b/src/main/java/org/onap/aai/sparky/logging/AaiUiMsgs.java index 4555b70..c89f83c 100644 --- a/src/main/java/org/onap/aai/sparky/logging/AaiUiMsgs.java +++ b/src/main/java/org/onap/aai/sparky/logging/AaiUiMsgs.java @@ -67,8 +67,7 @@ public enum AaiUiMsgs implements LogMessageEnum { /** Arguments: {0} = Reason. */ FAILED_TO_ADD_SKELETON_NODE, /** Arguments: {0} = Reason. */ - FAILED_TO_PROCESS_SKELETON_NODE, - INVALID_RESOLVE_STATE_DURING_INIT, + FAILED_TO_PROCESS_SKELETON_NODE, INVALID_RESOLVE_STATE_DURING_INIT, /** Arguments: {0} = Reason. */ FAILED_TO_PROCESS_INITIAL_STATE, /** Arguments: {0} = Relationship. */ @@ -120,7 +119,7 @@ public enum AaiUiMsgs implements LogMessageEnum { /** Arguments: {0} = Current state, {1} = New state {2} = Triggering action */ ACTIVE_INV_NODE_CHANGE_STATE_NO_NODE_ID, /** Arguments: {0} = Count Key {1} = Aggregation Key. */ - AGGREGATION_KEY_ERROR, + AGGREGATION_KEY_ERROR, /** Arguments: {0} Configuration */ CONFIGURATION_ERROR, /** Arguments: {0} = Source. */ @@ -134,7 +133,7 @@ public enum AaiUiMsgs implements LogMessageEnum { /** No argument */ INVALID_REQUEST_PARAMS, /** Arguments: {0} = Key. */ - ERROR_SORTING_VIOLATION_DATA, + ERROR_SORTING_VIOLATION_DATA, /** Arguments: {0} = exception */ ERROR_SERVLET_PROCESSSING, /** Arguments: {0} = exception */ @@ -203,7 +202,7 @@ public enum AaiUiMsgs implements LogMessageEnum { COLLECT_TOTAL, /** Arguments: {0} Number of required fetches */ SYNC_NUMBER_REQ_FETCHES, - /** Arguments: {0} Number of total fetches {1} Number of available records*/ + /** Arguments: {0} Number of total fetches {1} Number of available records */ SYNC_NUMBER_TOTAL_FETCHES, /** Arguments: {0} Completion Time */ COLLECT_TOTAL_TIME, @@ -234,14 +233,14 @@ public enum AaiUiMsgs implements LogMessageEnum { /** No argument */ HISTORICAL_SYNC_PENDING, /** Arguments: {0} = Time */ - HISTORICAL_SYNC_TO_BEGIN, + HISTORICAL_SYNC_TO_BEGIN, /** Arguments: {0} = message */ DEBUG_GENERIC, /** Arguments: {0} = message */ INFO_GENERIC, /** Arguments: {0} = message */ WARN_GENERIC, - /** Arguments: {0} = context {1} = Exception*/ + /** Arguments: {0} = context {1} = Exception */ INTERRUPTED, /** Arguments: {0} = Entity Type {1} Entity */ GEO_SYNC_IGNORING_ENTITY, @@ -255,11 +254,11 @@ public enum AaiUiMsgs implements LogMessageEnum { OXM_READ_ERROR_VERBOSE, /** No argument */ OXM_PARSE_ERROR_NONVERBOSE, - /** Arguments: {0} = OXM File name {1} = Exception*/ + /** Arguments: {0} = OXM File name {1} = Exception */ OXM_PARSE_ERROR_VERBOSE, /** No argument */ OXM_LOAD_SUCCESS, - /** Arguments: {0} = Entity {1} = Found property-value*/ + /** Arguments: {0} = Entity {1} = Found property-value */ OXM_PROP_DEF_ERR_CROSS_ENTITY_REF, /** Arguments: {0} = Sequence Number */ ETAG_RETRY_SEQ, @@ -347,7 +346,7 @@ public enum AaiUiMsgs implements LogMessageEnum { SKIP_PERIODIC_SYNC_AS_SYNC_DIDNT_FINISH, /** Arguments: {0} = Message */ SYNC_DURATION, - /** Arguments: {0} = Entity Type */ + /** Arguments: {0} = Entity Type */ ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, /** Arguments: {0} = AAI Query Result */ ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION, @@ -359,7 +358,10 @@ public enum AaiUiMsgs implements LogMessageEnum { SELF_LINK_DETERMINATION_FAILED_UNEXPECTED_LINKS, /** Arguments: {1} = Query {2} = Operation Result Code {3} = Operation Result */ SELF_LINK_RETRIEVAL_FAILED, - /** Arguments: {0} = Controller {1} = Synchronizer Current Internal State {2} = New State {3} = Caused By Action */ + /** + * Arguments: {0} = Controller {1} = Synchronizer Current Internal State {2} = New State {3} = + * Caused By Action + */ SYNC_INTERNAL_STATE_CHANGED, /** Arguments: {0} = Message */ SYNC_INVALID_CONFIG_PARAM, @@ -378,8 +380,7 @@ public enum AaiUiMsgs implements LogMessageEnum { /** Arguments: {0} = File name */ FILE_NOT_FOUND, /** Arguments: {0} = File name */ - FILE_READ_IN_PROGRESS, - ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES, + FILE_READ_IN_PROGRESS, ERROR_LOADING_OXM_SUGGESTIBLE_ENTITIES, /** Arguments: {0} = Error message */ ES_SUGGESTION_SEARCH_ENTITY_SYNC_ERROR, /** Arguments: {0} = Error message */ @@ -403,14 +404,12 @@ public enum AaiUiMsgs implements LogMessageEnum { /** Arguments: {0} = URL to extract parameter from */ ERROR_REMOVING_URL_PARAM, /** Arguments: {0} = Hash value */ - ERROR_INVALID_HASH, - ERROR_HASH_NOT_FOUND, - ERROR_READING_HTTP_REQ_PARAMS, + ERROR_INVALID_HASH, ERROR_HASH_NOT_FOUND, ERROR_READING_HTTP_REQ_PARAMS, /** Arguments: {0} = Exception */ ERROR_D3_GRAPH_VISUALIZATION, /** Arguments: {0} = Exception */ ERROR_AAI_QUERY_WITH_RETRY, - /** Arguments: Error extracting resource path from self-link. Error = {0} */ + /** Arguments: Error extracting resource path from self-link. Error = {0} */ ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK, /** Arguments: {0} = Schema file location */ ERROR_READING_JSON_SCHEMA, diff --git a/src/main/java/org/onap/aai/sparky/search/EntityTypeSummary.java b/src/main/java/org/onap/aai/sparky/search/EntityTypeSummary.java index cfc7a61..4e55a30 100644 --- a/src/main/java/org/onap/aai/sparky/search/EntityTypeSummary.java +++ b/src/main/java/org/onap/aai/sparky/search/EntityTypeSummary.java @@ -28,23 +28,23 @@ import java.util.List; public class EntityTypeSummary { private int totalChartHits; private List<EntityTypeSummaryBucket> buckets = new ArrayList<>(); - + public int getTotalChartHits() { return totalChartHits; } - + public List<EntityTypeSummaryBucket> getBuckets() { return buckets; } - + public void setTotalChartHits(int totalChartHits) { this.totalChartHits = totalChartHits; } - + public void setBuckets(List<EntityTypeSummaryBucket> buckets) { this.buckets = buckets; } - + public void addBucket(EntityTypeSummaryBucket bucket) { this.buckets.add(bucket); } diff --git a/src/main/java/org/onap/aai/sparky/search/EntityTypeSummaryBucket.java b/src/main/java/org/onap/aai/sparky/search/EntityTypeSummaryBucket.java index bc08e60..6185559 100644 --- a/src/main/java/org/onap/aai/sparky/search/EntityTypeSummaryBucket.java +++ b/src/main/java/org/onap/aai/sparky/search/EntityTypeSummaryBucket.java @@ -25,19 +25,19 @@ package org.onap.aai.sparky.search; public class EntityTypeSummaryBucket { private int count; private String key; - + public int getCount() { return count; } - + public String getKey() { return key; } - + public void setCount(int count) { this.count = count; } - + public void setKey(String key) { this.key = key; } diff --git a/src/main/java/org/onap/aai/sparky/search/SearchEntityProperties.java b/src/main/java/org/onap/aai/sparky/search/SearchEntityProperties.java index c65811e..56e8fdd 100644 --- a/src/main/java/org/onap/aai/sparky/search/SearchEntityProperties.java +++ b/src/main/java/org/onap/aai/sparky/search/SearchEntityProperties.java @@ -28,19 +28,19 @@ import java.util.Map; public class SearchEntityProperties { private String type; private Map<String, String> fields = new HashMap<>(); - + public String getType() { return type; } - + public Map<String, String> getFields() { return fields; } - + public void setType(String type) { this.type = type; } - + public void setFields(Map<String, String> field) { this.fields = field; } diff --git a/src/main/java/org/onap/aai/sparky/search/Suggestion.java b/src/main/java/org/onap/aai/sparky/search/Suggestion.java index 51ddb63..72530ef 100644 --- a/src/main/java/org/onap/aai/sparky/search/Suggestion.java +++ b/src/main/java/org/onap/aai/sparky/search/Suggestion.java @@ -26,31 +26,31 @@ public class Suggestion { private String entityType; private String searchTags; private SearchEntityProperties properties; - + public Suggestion(SearchEntityProperties properties) { this.properties = properties; } - + public String getEntityType() { return entityType; } - + public String getSearchTags() { return searchTags; } - + public SearchEntityProperties getProperties() { return properties; } - + public void setEntityType(String entityType) { this.entityType = entityType; } - + public void setSearchTags(String searchTags) { this.searchTags = searchTags; } - + public void setProperties(SearchEntityProperties properties) { this.properties = properties; } diff --git a/src/main/java/org/onap/aai/sparky/search/SuggestionList.java b/src/main/java/org/onap/aai/sparky/search/SuggestionList.java index 6cd2c9a..5548ffb 100644 --- a/src/main/java/org/onap/aai/sparky/search/SuggestionList.java +++ b/src/main/java/org/onap/aai/sparky/search/SuggestionList.java @@ -31,7 +31,7 @@ public class SuggestionList { private Long totalFound; private Long numReturned; private List<Suggestion> suggestions = new LinkedList<>(); - + public void addSuggestion(Suggestion suggestion) { suggestions.add(suggestion); } @@ -67,4 +67,4 @@ public class SuggestionList { public void setNumReturned(Long numReturned) { this.numReturned = numReturned; } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/search/VnfSearchQueryBuilder.java b/src/main/java/org/onap/aai/sparky/search/VnfSearchQueryBuilder.java index 8fe1d00..9e206b3 100644 --- a/src/main/java/org/onap/aai/sparky/search/VnfSearchQueryBuilder.java +++ b/src/main/java/org/onap/aai/sparky/search/VnfSearchQueryBuilder.java @@ -36,7 +36,7 @@ import javax.json.JsonObjectBuilder; */ public class VnfSearchQueryBuilder { - + /** * Creates the suggestions query. * diff --git a/src/main/java/org/onap/aai/sparky/search/VnfSearchService.java b/src/main/java/org/onap/aai/sparky/search/VnfSearchService.java index 904dc69..654aad0 100644 --- a/src/main/java/org/onap/aai/sparky/search/VnfSearchService.java +++ b/src/main/java/org/onap/aai/sparky/search/VnfSearchService.java @@ -114,7 +114,8 @@ public class VnfSearchService { if (suggestions.length() > 0) { suggestionsArray = suggestions.getJSONObject(0).getJSONArray("options"); for (int i = 0; i < suggestionsArray.length(); i++) { - suggestionsArray.getJSONObject(i).remove("score"); // FE doesn't like this noise: 'score' + suggestionsArray.getJSONObject(i).remove("score"); // FE doesn't like this noise: + // 'score' } total = suggestionsArray.length(); @@ -139,7 +140,7 @@ public class VnfSearchService { JSONArray bucketsArray = (responseJson.getJSONObject("aggregations") .getJSONObject("default").getJSONArray("buckets")); int count = 0; - for (int i=0; i< bucketsArray.length(); i++) { + for (int i = 0; i < bucketsArray.length(); i++) { count += bucketsArray.getJSONObject(i).getInt("doc_count"); } JSONObject content = new JSONObject(); @@ -209,22 +210,26 @@ public class VnfSearchService { * @return the suggestions results * @throws IOException Signals that an I/O exception has occurred. */ - public List<SuggestionEntity> getSuggestionsResults(QuerySearchEntity querySearchEntity, int resultCountLimit) throws IOException { + public List<SuggestionEntity> getSuggestionsResults(QuerySearchEntity querySearchEntity, + int resultCountLimit) throws IOException { List<SuggestionEntity> returnList = new ArrayList<SuggestionEntity>(); - + /* Create suggestions query */ - JsonObject vnfSearch = VnfSearchQueryBuilder.createSuggestionsQuery(String.valueOf(resultCountLimit), querySearchEntity.getQueryStr()); - + JsonObject vnfSearch = VnfSearchQueryBuilder + .createSuggestionsQuery(String.valueOf(resultCountLimit), querySearchEntity.getQueryStr()); + /* Parse suggestions response */ - OperationResult opResult = search.doPost(getFullUrl(esConfig.getAutosuggestIndexname(), ES_SUGGEST_API), vnfSearch.toString(), APP_JSON); + OperationResult opResult = + search.doPost(getFullUrl(esConfig.getAutosuggestIndexname(), ES_SUGGEST_API), + vnfSearch.toString(), APP_JSON); String result = opResult.getResult(); - + if (!opResult.wasSuccessful()) { LOG.error(AaiUiMsgs.ERROR_PARSING_JSON_PAYLOAD_VERBOSE, result); return returnList; } - + JSONObject responseJson = new JSONObject(result); String suggestionsKey = "vnfs"; JSONArray suggestionsArray = new JSONArray(); @@ -236,71 +241,75 @@ public class VnfSearchService { if (querySuggestion != null) { SuggestionEntity responseSuggestion = new SuggestionEntity(); responseSuggestion.setText(querySuggestion.getString("text")); - responseSuggestion.setRoute("vnfSearch"); // TODO -> Read route from suggestive-search.properties instead of hard coding - responseSuggestion.setHashId(NodeUtils.generateUniqueShaDigest(querySuggestion.getString("text"))); + responseSuggestion.setRoute("vnfSearch"); // TODO -> Read route from + // suggestive-search.properties instead of hard + // coding + responseSuggestion + .setHashId(NodeUtils.generateUniqueShaDigest(querySuggestion.getString("text"))); returnList.add(responseSuggestion); - } + } } } return returnList; } - - + + /** - * This method sets server response if lookup in ES has 0 count - * TODO: Change the response code to appropriate when FE-BE contract is finalized - * @param response - */ + * This method sets server response if lookup in ES has 0 count TODO: Change the response code to + * appropriate when FE-BE contract is finalized + * + * @param response + */ public void setZeroCountResponse(HttpServletResponse response) throws IOException { - JSONObject payload = new JSONObject(); - payload.put("count", 0); - setServletResponse(false, 200, response, payload.toString() ); + JSONObject payload = new JSONObject(); + payload.put("count", 0); + setServletResponse(false, 200, response, payload.toString()); } - + /** - * This method sets server response if lookup in ES for an aggregation has 0 results - * TODO: Change the response code to appropriate when FE-BE contract is finalized - * @param response - */ + * This method sets server response if lookup in ES for an aggregation has 0 results TODO: Change + * the response code to appropriate when FE-BE contract is finalized + * + * @param response + */ public void setEmptyAggResponse(HttpServletResponse response) throws IOException { - JSONObject aggPayload = new JSONObject(); + JSONObject aggPayload = new JSONObject(); aggPayload.put("totalChartHits", 0); aggPayload.put("buckets", new JSONArray()); JSONObject payload = new JSONObject(); payload.append("groupby_aggregation", aggPayload); - setServletResponse(false, 200, response, payload.toString() ); + setServletResponse(false, 200, response, payload.toString()); } - + public HashQueryResponse getJSONPayloadFromHash(String hashId) { - + HashQueryResponse hashQueryResponse = new HashQueryResponse(); JsonObjectBuilder hashSearch = Json.createObjectBuilder(); VnfSearchQueryBuilder.buildSingleTermCountQuery(hashSearch, "_id", hashId); String hashSearchQuery = hashSearch.build().toString(); OperationResult opResult = search.doPost( - getFullUrl(esConfig.getAutosuggestIndexname(), ES_SEARCH_API), - hashSearchQuery, APP_JSON); + getFullUrl(esConfig.getAutosuggestIndexname(), ES_SEARCH_API), hashSearchQuery, APP_JSON); hashQueryResponse.setOpResult(opResult); - - if(opResult != null && opResult.wasSuccessful()){ + + if (opResult != null && opResult.wasSuccessful()) { String result = opResult.getResult(); if (result != null) { JSONObject responseJson = new JSONObject(result); - JSONArray hits = responseJson.getJSONObject("hits").getJSONArray("hits"); - if(hits != null && hits.length() > 0){ - hashQueryResponse.setJsonPayload (hits.getJSONObject(0).getJSONObject("_source") - .getJSONObject("entity_suggest").toString()); + JSONArray hits = responseJson.getJSONObject("hits").getJSONArray("hits"); + if (hits != null && hits.length() > 0) { + hashQueryResponse.setJsonPayload(hits.getJSONObject(0).getJSONObject("_source") + .getJSONObject("entity_suggest").toString()); } } } return hashQueryResponse; } - + public void getEntityCountResults(HttpServletResponse response, Map<String, String> attributes) throws IOException { // Create entity counts query JsonObject vnfSearch = VnfSearchQueryBuilder.createEntityCountsQuery(attributes); - + // Parse response for entity counts query OperationResult opResult = search.doPost( getFullUrl(TierSupportUiConstants.getAggregationIndexName(ENTITY_TYPE), ES_COUNT_API), @@ -313,7 +322,7 @@ public class VnfSearchService { // Create query for summary by entity type JsonObject vnfSearch = VnfSearchQueryBuilder.createSummaryByEntityTypeQuery(attributes, groupByKey); - + // Parse response for summary by entity type query OperationResult opResult = search.doPost( getFullUrl(TierSupportUiConstants.getAggregationIndexName(ENTITY_TYPE), ES_SEARCH_API), diff --git a/src/main/java/org/onap/aai/sparky/search/config/SuggestionConfig.java b/src/main/java/org/onap/aai/sparky/search/config/SuggestionConfig.java index 7cffb43..5ce4d3c 100644 --- a/src/main/java/org/onap/aai/sparky/search/config/SuggestionConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/config/SuggestionConfig.java @@ -34,23 +34,26 @@ import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants; public class SuggestionConfig { public static final String CONFIG_FILE = TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION + "suggestive-search.properties"; - + private static SuggestionConfig config; - private static final String INDEX_SEARCH_MAPPER_DEFAULT = "elasticsearch.autosuggestIndexname:SearchServiceWrapper,elasticsearch.indexName:VnfSearchService"; - + private static final String INDEX_SEARCH_MAPPER_DEFAULT = + "elasticsearch.autosuggestIndexname:SearchServiceWrapper,elasticsearch.indexName:VnfSearchService"; + private Map<String, String> searchIndexToSearchService; - - private static final String CALLED_PAIRING_KEY_DEFAULT = "volume-group-id,volume-group-name,physical-location-id,data-center-code,complex-name,tenant-id,tenant-name,vserver-id,vserver-name,vserver-name2,hostname,pserver-name2,pserver-id,global-customer-id,subscriber-name,service-instance-id,service-instance-name,link-name,vpn-id,vpn-name,vpe-id,vnf-id,vnf-name,vnf-name2,vnfc-name,network-id,network-name,network-policy-id,vf-module-id,vf-module-name,vnf-id2,pnf-name,circuit-id"; - private static final String CALLED_PAIRING_VALUE_DEFAULT = "called"; - private static final String AT_PAIRING_KEY_DEFAULT = "street1,street2,postal-code,ipv4-oam-address,network-policy-fqdn"; - private static final String AT_PAIRING_VALUE_DEFAULT = "at"; - private static final String DEFAULT_PAIRING_DEFAULT_VALUE = "with"; + + private static final String CALLED_PAIRING_KEY_DEFAULT = + "volume-group-id,volume-group-name,physical-location-id,data-center-code,complex-name,tenant-id,tenant-name,vserver-id,vserver-name,vserver-name2,hostname,pserver-name2,pserver-id,global-customer-id,subscriber-name,service-instance-id,service-instance-name,link-name,vpn-id,vpn-name,vpe-id,vnf-id,vnf-name,vnf-name2,vnfc-name,network-id,network-name,network-policy-id,vf-module-id,vf-module-name,vnf-id2,pnf-name,circuit-id"; + private static final String CALLED_PAIRING_VALUE_DEFAULT = "called"; + private static final String AT_PAIRING_KEY_DEFAULT = + "street1,street2,postal-code,ipv4-oam-address,network-policy-fqdn"; + private static final String AT_PAIRING_VALUE_DEFAULT = "at"; + private static final String DEFAULT_PAIRING_DEFAULT_VALUE = "with"; private String conjunctionForAt; Map<String, String> pairingList; private Collection<String> stopWords; private String defaultPairingValue; - - + + private SuggestionConfig() {} /** @@ -65,12 +68,12 @@ public class SuggestionConfig { } return config; } - + public void initializeConfigProperties() { - + Properties props = ConfigHelper.loadConfigFromExplicitPath(CONFIG_FILE); Properties suggestionProps = ConfigHelper.getConfigWithPrefix("suggestion", props); - + String indexSearchMapper = suggestionProps.getProperty("routing", INDEX_SEARCH_MAPPER_DEFAULT); String[] indexesToSearchClassesArray = indexSearchMapper.split(","); searchIndexToSearchService = new HashMap<String, String>(); @@ -78,25 +81,30 @@ public class SuggestionConfig { String[] subPair = pair.split(":"); searchIndexToSearchService.put(subPair[0], subPair[1]); } - - defaultPairingValue=suggestionProps.getProperty("pairing.default.value", DEFAULT_PAIRING_DEFAULT_VALUE); - String calledValue = suggestionProps.getProperty("pairing.called.value", CALLED_PAIRING_VALUE_DEFAULT); - String[] calledPairingArray = suggestionProps.getProperty("pairing.called.key", CALLED_PAIRING_KEY_DEFAULT).split(","); + + defaultPairingValue = + suggestionProps.getProperty("pairing.default.value", DEFAULT_PAIRING_DEFAULT_VALUE); + String calledValue = + suggestionProps.getProperty("pairing.called.value", CALLED_PAIRING_VALUE_DEFAULT); + String[] calledPairingArray = + suggestionProps.getProperty("pairing.called.key", CALLED_PAIRING_KEY_DEFAULT).split(","); pairingList = new HashMap<String, String>(); - for(String calledField: calledPairingArray){ + for (String calledField : calledPairingArray) { pairingList.put(calledField, calledValue); } - - this.conjunctionForAt = suggestionProps.getProperty("pairing.at.value", AT_PAIRING_VALUE_DEFAULT); - String[] atPairingArray = suggestionProps.getProperty("pairing.at.key", AT_PAIRING_KEY_DEFAULT).split(","); - for(String atField: atPairingArray){ + + this.conjunctionForAt = + suggestionProps.getProperty("pairing.at.value", AT_PAIRING_VALUE_DEFAULT); + String[] atPairingArray = + suggestionProps.getProperty("pairing.at.key", AT_PAIRING_KEY_DEFAULT).split(","); + for (String atField : atPairingArray) { pairingList.put(atField, conjunctionForAt); } - + stopWords = Arrays.asList(suggestionProps.getProperty("stopwords", "").split(",")); - + } - + public void setSearchIndexToSearchService(Map<String, String> searchIndexToSearchService) { this.searchIndexToSearchService = searchIndexToSearchService; } @@ -104,7 +112,7 @@ public class SuggestionConfig { public Map<String, String> getSearchIndexToSearchService() { return searchIndexToSearchService; } - + public Collection<String> getStopWords() { return stopWords; } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/FilterElasticSearchAdapter.java b/src/main/java/org/onap/aai/sparky/search/filters/FilterElasticSearchAdapter.java index 2fe8a0a..a846e88 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/FilterElasticSearchAdapter.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/FilterElasticSearchAdapter.java @@ -41,22 +41,22 @@ import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants; /** - * Performs all Elasticsearch related queries for filters related to - * the Sparky-FE. + * Performs all Elasticsearch related queries for filters related to the Sparky-FE. */ public class FilterElasticSearchAdapter { - + private static ElasticSearchConfig esConfig = null; private static SearchAdapter search = null; private static final String ES_SEARCH_API = TierSupportUiConstants.ES_SEARCH_API; private static final String APP_JSON = "application/json"; - private static final Logger LOG = LoggerFactory.getInstance().getLogger(FilterElasticSearchAdapter.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(FilterElasticSearchAdapter.class); private static final String AGGS = "aggregations"; private static final String CONTAINER = "default"; private static final String BUCKETS = "buckets"; private static final String FILTER_VALUE_KEY = "key"; - - + + public FilterElasticSearchAdapter() { try { if (esConfig == null) { @@ -69,7 +69,7 @@ public class FilterElasticSearchAdapter { LOG.error(AaiUiMsgs.CONFIGURATION_ERROR, "Search"); } } - + /** * Get Full URL for search using elastic search configuration. * @@ -81,54 +81,60 @@ public class FilterElasticSearchAdapter { final String port = esConfig.getHttpPort(); return String.format("http://%s:%s/%s/%s", host, port, indexName, api); } - + /** - * For a given UiFilterEntity, will attempt to contact an Elasticsearch instance - * and fetch all possible values for filter's field name. + * For a given UiFilterEntity, will attempt to contact an Elasticsearch instance and fetch all + * possible values for filter's field name. * * @param filter - Filter object against which the search will take place. * @param sourceData - If present, contains the index name and field value to search against. * @return - A List of strings if results were found, else empty list. */ - public List<String> fetchValuesForFilter(UiFilterEntity filter, UiFilterDataSourceConfig dataSourceConfig) { + public List<String> fetchValuesForFilter(UiFilterEntity filter, + UiFilterDataSourceConfig dataSourceConfig) { ArrayList<String> filterValues = new ArrayList<String>(); - - if(dataSourceConfig != null) { + + if (dataSourceConfig != null) { JsonObject filterValueQuery = null; - if(dataSourceConfig.getPathToField() != null) { - filterValueQuery = FilterQueryBuilder.createNestedFilterValueQueryObject(dataSourceConfig.getFieldName(), dataSourceConfig.getPathToField()); + if (dataSourceConfig.getPathToField() != null) { + filterValueQuery = FilterQueryBuilder.createNestedFilterValueQueryObject( + dataSourceConfig.getFieldName(), dataSourceConfig.getPathToField()); } else { - filterValueQuery = FilterQueryBuilder.createFilterValueQueryObject(dataSourceConfig.getFieldName()); + filterValueQuery = + FilterQueryBuilder.createFilterValueQueryObject(dataSourceConfig.getFieldName()); } - - org.onap.aai.sparky.dal.rest.OperationResult opResult = search.doPost(getFullUrl(dataSourceConfig.getIndexName(), ES_SEARCH_API), filterValueQuery.toString(), APP_JSON); - + + org.onap.aai.sparky.dal.rest.OperationResult opResult = + search.doPost(getFullUrl(dataSourceConfig.getIndexName(), ES_SEARCH_API), + filterValueQuery.toString(), APP_JSON); + String result = opResult.getResult(); - if(opResult.wasSuccessful() && result != null) { + if (opResult.wasSuccessful() && result != null) { JSONObject responseJson = new JSONObject(result); JSONObject aggJson = responseJson.getJSONObject(AGGS); - + JSONObject containerJson = null; - if(dataSourceConfig.getPathToField() != null) { + if (dataSourceConfig.getPathToField() != null) { JSONObject nestedContainer = aggJson.getJSONObject(dataSourceConfig.getPathToField()); containerJson = nestedContainer.getJSONObject(dataSourceConfig.getFieldName()); } else { containerJson = aggJson.getJSONObject(CONTAINER); } - + JSONArray buckets = containerJson.getJSONArray(BUCKETS); - + int bucketLength = buckets.length(); - for(int i = 0; i < bucketLength; i++) { + for (int i = 0; i < bucketLength; i++) { JSONObject filterBucket = buckets.getJSONObject(i); - + String filterValue = filterBucket.getString(FILTER_VALUE_KEY); - if(filterValue != null && !filterValue.isEmpty()) { + if (filterValue != null && !filterValue.isEmpty()) { filterValues.add(filterValue); } } } else { - LOG.error(AaiUiMsgs.ERROR_FETCHING_FILTER_VALUES, String.valueOf(opResult.getResultCode()), filter.getFilterName()); + LOG.error(AaiUiMsgs.ERROR_FETCHING_FILTER_VALUES, String.valueOf(opResult.getResultCode()), + filter.getFilterName()); } } filterValues.sort(String::compareToIgnoreCase); diff --git a/src/main/java/org/onap/aai/sparky/search/filters/FilterProcessor.java b/src/main/java/org/onap/aai/sparky/search/filters/FilterProcessor.java index 100257b..fdcf6b2 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/FilterProcessor.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/FilterProcessor.java @@ -45,21 +45,21 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class FilterProcessor { - + private static final Logger LOG = LoggerFactory.getInstance().getLogger(FilterProcessor.class); - + private ObjectMapper mapper; private FilteredSearchHelper filteredSearchHelper; - + public FilterProcessor() { this.mapper = new ObjectMapper(); } - + public FilterProcessor(FilteredSearchHelper filteredSearchHelper) { this.mapper = new ObjectMapper(); this.filteredSearchHelper = filteredSearchHelper; } - + public ObjectMapper getMapper() { return mapper; } @@ -67,23 +67,26 @@ public class FilterProcessor { public FilteredSearchHelper getFilteredSearchHelper() { return filteredSearchHelper; } - + public void setFilteredSearchHelper(FilteredSearchHelper filteredSearchHelper) { this.filteredSearchHelper = filteredSearchHelper; } public void getFiltersWithValues(Exchange exchange) { - Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class); + Response response = + exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class); Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class); - /* Disables automatic Apache Camel Restlet component logging which prints out an undesirable log entry - which includes client (e.g. browser) information */ + /* + * Disables automatic Apache Camel Restlet component logging which prints out an undesirable log + * entry which includes client (e.g. browser) information + */ request.setLoggable(false); - + UiFiltersEntity viewFiltersList = null; boolean wasErrorDuringFilterDiscovery = false; - + try { String payload = exchange.getIn().getBody(String.class); @@ -92,7 +95,8 @@ public class FilterProcessor { LOG.error(AaiUiMsgs.SEARCH_SERVLET_ERROR, "Request Payload is empty"); wasErrorDuringFilterDiscovery = true; } else { - String viewName = mapper.readValue(payload, JsonNode.class).get(TierSupportUiConstants.UI_FILTER_VIEW_NAME_PARAMETER).asText(); + String viewName = mapper.readValue(payload, JsonNode.class) + .get(TierSupportUiConstants.UI_FILTER_VIEW_NAME_PARAMETER).asText(); if (viewName == null || viewName.isEmpty()) { wasErrorDuringFilterDiscovery = true; @@ -100,43 +104,48 @@ public class FilterProcessor { viewFiltersList = filteredSearchHelper.doFilterDiscovery(viewName); } } - } catch(Exception exc) { - LOG.error(AaiUiMsgs.ERROR_GENERIC, "FilterProcessor failed to get filter list due to error = " + exc.getMessage()); + } catch (Exception exc) { + LOG.error(AaiUiMsgs.ERROR_GENERIC, + "FilterProcessor failed to get filter list due to error = " + exc.getMessage()); wasErrorDuringFilterDiscovery = true; } - + boolean wasErrorDuringValueSearch = false; - if(!wasErrorDuringFilterDiscovery) { + if (!wasErrorDuringFilterDiscovery) { try { - if(!viewFiltersList.getFilters().isEmpty()) { + if (!viewFiltersList.getFilters().isEmpty()) { List<String> filterIds = new ArrayList<String>(); - - for(UiFilterEntity filterEntity : viewFiltersList.getFilters()) { + + for (UiFilterEntity filterEntity : viewFiltersList.getFilters()) { filterIds.add(filterEntity.getFilterId()); } - + UiFiltersEntity responseFiltersList = filteredSearchHelper.doFilterEnumeration(filterIds); - - JsonObject finalResponse = UiFiltersEntityConverter.convertUiFiltersEntityToUnifiedFilterResponse(responseFiltersList); - + + JsonObject finalResponse = UiFiltersEntityConverter + .convertUiFiltersEntityToUnifiedFilterResponse(responseFiltersList); + response.setStatus(Status.SUCCESS_OK); response.setEntity(finalResponse.toString(), MediaType.APPLICATION_JSON); exchange.getOut().setBody(response); } else { wasErrorDuringValueSearch = true; } - } catch(Exception exc) { - LOG.error(AaiUiMsgs.ERROR_GENERIC, "FilterProcessor failed to generate valid unifiedFilterRequest response due to error, " + exc.getMessage()); + } catch (Exception exc) { + LOG.error(AaiUiMsgs.ERROR_GENERIC, + "FilterProcessor failed to generate valid unifiedFilterRequest response due to error, " + + exc.getMessage()); response.setStatus(Status.SERVER_ERROR_INTERNAL); } - } - + } + // In the case of an error we want to respond with a valid empty response - if(wasErrorDuringFilterDiscovery || wasErrorDuringValueSearch) { + if (wasErrorDuringFilterDiscovery || wasErrorDuringValueSearch) { response.setStatus(Status.SUCCESS_OK); - response.setEntity(UiFiltersEntityConverter.generateEmptyResponse().toString(), MediaType.APPLICATION_JSON); + response.setEntity(UiFiltersEntityConverter.generateEmptyResponse().toString(), + MediaType.APPLICATION_JSON); exchange.getOut().setBody(response); } } - + } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/FilterQueryBuilder.java b/src/main/java/org/onap/aai/sparky/search/filters/FilterQueryBuilder.java index 23f0dce..fb668f0 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/FilterQueryBuilder.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/FilterQueryBuilder.java @@ -42,11 +42,12 @@ import org.onap.aai.sparky.search.filters.entity.SearchFilter; * Used to generate queries against Elasticsearch for filter related queries. */ public class FilterQueryBuilder { - + private static final int EXISTING_FILTERS_LIMIT = 0; private static final int SHOULD_BRANCH_LIMIT = 2; - public static JsonObject createFilteredBoolQueryObject(List<SearchFilter> searchFilters, int minShouldMatch, List<String> fields) { + public static JsonObject createFilteredBoolQueryObject(List<SearchFilter> searchFilters, + int minShouldMatch, List<String> fields) { if (searchFilters == null || searchFilters.size() == 0) { return null; @@ -70,16 +71,16 @@ public class FilterQueryBuilder { if (filter == null || filter.getFilterName() == null) { // log error and continue } else { - + String fieldName = filter.getDataSource().getFieldName(); - if(!fields.contains(fieldName)) { + if (!fields.contains(fieldName)) { fields.add(fieldName); } - + if (searchFilterValueSize >= SHOULD_BRANCH_LIMIT) { // Add should branches for (String filterValue : searchFilter.getValues()) { - boolQueryBuilder.addShouldFilter(new MatchFilterCriteriaEntity(fieldName, filterValue)); + boolQueryBuilder.addShouldFilter(new MatchFilterCriteriaEntity(fieldName, filterValue)); } } else if (searchFilterValueSize > EXISTING_FILTERS_LIMIT) { @@ -92,7 +93,7 @@ public class FilterQueryBuilder { } boolQueryBuilder.setMinShouldMatch(minShouldMatch); - + return boolQueryBuilder.getJsonObject(); } @@ -126,22 +127,31 @@ public class FilterQueryBuilder { return aggQueryBuilder.getJsonObject(); } - public static JsonObject createCombinedBoolAndAggQuery(List<SearchFilter> searchFilters, int minShouldMatch) { + public static JsonObject createCombinedBoolAndAggQuery(List<SearchFilter> searchFilters, + int minShouldMatch) { JsonObjectBuilder wrappedQueryBuilder = Json.createObjectBuilder(); - if(searchFilters != null) { + if (searchFilters != null) { List<String> fields = new ArrayList<String>(); JsonObject boolQuery = createFilteredBoolQueryObject(searchFilters, minShouldMatch, fields); JsonObject aggQuery = createAggregationQueryArray(searchFilters); if (boolQuery != null) { wrappedQueryBuilder.add("size", 0); - - JsonArrayBuilder filedsArrayBuilder = Json.createBuilderFactory(null).createArrayBuilder(); // TODO -> Should we use a class instance factory? - for(String field : fields) { + + JsonArrayBuilder filedsArrayBuilder = Json.createBuilderFactory(null).createArrayBuilder(); // TODO + // -> + // Should + // we + // use + // a + // class + // instance + // factory? + for (String field : fields) { filedsArrayBuilder.add(field); } wrappedQueryBuilder.add("fields", filedsArrayBuilder.build()); - + wrappedQueryBuilder.add("query", boolQuery); } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/FilteredSearchHelper.java b/src/main/java/org/onap/aai/sparky/search/filters/FilteredSearchHelper.java index 825dc5e..67f4d34 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/FilteredSearchHelper.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/FilteredSearchHelper.java @@ -40,12 +40,13 @@ import org.onap.aai.sparky.search.filters.entity.UiFilterValueEntity; import org.onap.aai.sparky.search.filters.entity.UiFiltersEntity; public class FilteredSearchHelper { - private static final Logger LOG = LoggerFactory.getInstance().getLogger(FilteredSearchHelper.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(FilteredSearchHelper.class); private FiltersConfig filtersConfig; private Map<String, UiFilterConfig> filtersMap = null; private FilterElasticSearchAdapter filterSearchAdapter = null; - + public FilteredSearchHelper(FiltersConfig filterConfig) { this.filtersConfig = filterConfig; @@ -53,14 +54,14 @@ public class FilteredSearchHelper { filtersMap = new HashMap<>(); final FiltersDetailsConfig uiFiltersConfig = filterConfig.getFiltersConfig(); - + if (uiFiltersConfig != null) { for (UiFilterConfig filter : uiFiltersConfig.getFilters()) { filtersMap.put(filter.getFilterId(), filter); } } } - + filterSearchAdapter = new FilterElasticSearchAdapter(); } @@ -76,25 +77,25 @@ public class FilteredSearchHelper { List<UiViewListItemConfig> views = filtersConfig.getViewsConfig().getViews(); List<UiFilterListItemConfig> filters = null; UiFiltersEntity viewFiltersList = new UiFiltersEntity(); - - if(viewName != null) { - for (UiViewListItemConfig view: views) { + + if (viewName != null) { + for (UiViewListItemConfig view : views) { if (viewName.equalsIgnoreCase(view.getViewName())) { filters = view.getFilters(); break; } } - + if (filters == null) { LOG.error(AaiUiMsgs.VIEW_NAME_NOT_SUPPORTED, viewName); } else { for (UiFilterListItemConfig filter : filters) { FiltersDetailsConfig filtersDetailsConfig = filtersConfig.getFiltersConfig(); - - for (UiFilterConfig filterConfig: filtersDetailsConfig.getFilters()) { + + for (UiFilterConfig filterConfig : filtersDetailsConfig.getFilters()) { if (filterConfig.getFilterId().equals(filter.getFilterId())) { UiFilterEntity filterEntity = new UiFilterEntity(filterConfig); - if(filter.getDefaultValue() != null) { + if (filter.getDefaultValue() != null) { filterEntity.setDefaultValue(filter.getDefaultValue()); } viewFiltersList.addFilter(filterEntity); @@ -105,7 +106,7 @@ public class FilteredSearchHelper { } return viewFiltersList; } - + public UiFiltersEntity doFilterEnumeration(List<String> requestedFilterIds) { UiFiltersEntity viewFiltersList = new UiFiltersEntity(); @@ -117,22 +118,23 @@ public class FilteredSearchHelper { UiFilterConfig sourceData = filtersMap.get(requestedFilterId); UiFilterEntity filterEntity = new UiFilterEntity(sourceData); this.getFilterEnumeration(filterEntity, sourceData); - viewFiltersList.addFilter(filterEntity); + viewFiltersList.addFilter(filterEntity); } } return viewFiltersList; } - + public void getFilterEnumeration(UiFilterEntity filter, UiFilterConfig sourceData) { - List<String> filterValues = filterSearchAdapter.fetchValuesForFilter(filter, sourceData.getDataSource()); - - for(String value : filterValues) { - UiFilterValueEntity valueEntity = new UiFilterValueEntity(); - valueEntity.setDisplayName(value); - valueEntity.setFilterValue(value); - filter.addFilterValue(valueEntity); - } + List<String> filterValues = + filterSearchAdapter.fetchValuesForFilter(filter, sourceData.getDataSource()); + + for (String value : filterValues) { + UiFilterValueEntity valueEntity = new UiFilterValueEntity(); + valueEntity.setDisplayName(value); + valueEntity.setFilterValue(value); + filter.addFilterValue(valueEntity); + } } public Map<String, UiFilterConfig> getFiltersMap() { @@ -142,15 +144,15 @@ public class FilteredSearchHelper { public void setFiltersMap(Map<String, UiFilterConfig> filtersMap) { this.filtersMap = filtersMap; } - + public UiFilterDataSourceConfig getFilterDataSource(String filterId) { UiFilterConfig filterConfig = filtersMap.get(filterId); UiFilterDataSourceConfig returnValue = null; - - if(filterConfig != null) { + + if (filterConfig != null) { returnValue = filterConfig.getDataSource(); } - + return returnValue; } } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/UiFiltersEntityConverter.java b/src/main/java/org/onap/aai/sparky/search/filters/UiFiltersEntityConverter.java index 24851f7..e8ce534 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/UiFiltersEntityConverter.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/UiFiltersEntityConverter.java @@ -36,7 +36,7 @@ import org.onap.aai.sparky.search.filters.entity.UiFilterValueEntity; import org.onap.aai.sparky.search.filters.entity.UiFiltersEntity; public class UiFiltersEntityConverter { - + private static final String KEY_TYPE = "type"; private static final String KEY_MULTISELECT = "multiSelect"; private static final String KEY_WATERMARK = "watermark"; @@ -46,31 +46,32 @@ public class UiFiltersEntityConverter { private static final String KEY_DECODE = "decode"; private static final String KEY_CODE = "code"; private static final String KEY_DEFAULT_VALUE = "defaultValue"; - + /** - * Converts a UiFiltersEntity into a JSON object to satisfy a new (as of 23 Oct 2017) - * filter library being used in the FE. + * Converts a UiFiltersEntity into a JSON object to satisfy a new (as of 23 Oct 2017) filter + * library being used in the FE. * * @param entityToConvert - The UiFiltersEntity to be converted into a JSON response. * @return A JsonObject representing the passed in UiFiltersEntity. */ - public static JsonObject convertUiFiltersEntityToUnifiedFilterResponse(UiFiltersEntity entityToConvert) { + public static JsonObject convertUiFiltersEntityToUnifiedFilterResponse( + UiFiltersEntity entityToConvert) { JsonObjectBuilder filterBuilder = Json.createObjectBuilder(); - - if(entityToConvert != null) { + + if (entityToConvert != null) { List<UiFilterEntity> filterEntities = entityToConvert.getFilters(); - if(filterEntities != null) { - for(UiFilterEntity entity : filterEntities) { + if (filterEntities != null) { + for (UiFilterEntity entity : filterEntities) { filterBuilder.add(entity.getFilterId(), generateFilterObject(entity)); } } } - + JsonObjectBuilder finalObject = Json.createObjectBuilder(); finalObject.add(KEY_FILTERS, filterBuilder.build()); return finalObject.build(); } - + /** * Generates the core body of the a single filter within the JSON body. * @@ -79,96 +80,101 @@ public class UiFiltersEntityConverter { */ private static JsonObject generateFilterObject(UiFilterEntity entity) { JsonObjectBuilder filterBuilder = Json.createObjectBuilder(); - + filterBuilder.add(KEY_LABEL, entity.getDisplayName()); filterBuilder.add(KEY_CONTROLS, generateControlObject(entity, entity.getFilterValueList())); - + return filterBuilder.build(); } - + /** * Generates the "controls" object within the filter JSON. * * @param filterEntity - The filter entity on which this filter will be based. - * @param filterValues - The list of values associated with the filter - * from data store queries. + * @param filterValues - The list of values associated with the filter from data store queries. * @return A JsonObject representing the "controls" object of the filter JSON. */ - private static JsonObject generateControlObject(UiFilterEntity filterEntity, List<UiFilterValueEntity> filterValues) { + private static JsonObject generateControlObject(UiFilterEntity filterEntity, + List<UiFilterValueEntity> filterValues) { JsonObjectBuilder controls = Json.createObjectBuilder(); JsonObjectBuilder subControl = Json.createObjectBuilder(); - + subControl.add(KEY_TYPE, filterEntity.getDataType()); subControl.add(KEY_MULTISELECT, filterEntity.getMultiSelect()); subControl.add(KEY_WATERMARK, filterEntity.getWatermark()); - - if(filterEntity.getDefaultValue() != null && !filterEntity.getDefaultValue().getCode().isEmpty() && !filterEntity.getDefaultValue().getDecode().isEmpty()) { + + if (filterEntity.getDefaultValue() != null + && !filterEntity.getDefaultValue().getCode().isEmpty() + && !filterEntity.getDefaultValue().getDecode().isEmpty()) { JsonObjectBuilder defaultValueBuilder = Json.createObjectBuilder(); - + defaultValueBuilder.add(KEY_DECODE, filterEntity.getDefaultValue().getDecode()); defaultValueBuilder.add(KEY_CODE, filterEntity.getDefaultValue().getCode()); - + subControl.add(KEY_DEFAULT_VALUE, defaultValueBuilder.build()); } - - if(filterEntity.getOptionsValues() == null || filterEntity.getOptionsValues().isEmpty()) { + + if (filterEntity.getOptionsValues() == null || filterEntity.getOptionsValues().isEmpty()) { subControl.add(filterEntity.getOptionsType(), generateOptionsObject(filterValues)); } else { - subControl.add(filterEntity.getOptionsType(), generateOptionsValuesObject(filterEntity.getOptionsValues())); + subControl.add(filterEntity.getOptionsType(), + generateOptionsValuesObject(filterEntity.getOptionsValues())); } - + controls.add(filterEntity.getFilterName(), subControl.build()); - + return controls.build(); } - + /** - * Creates a JsonArray representing the list of options for a filter. - * Similar to function generateOptionsObject, except using different arguments. + * Creates a JsonArray representing the list of options for a filter. Similar to function + * generateOptionsObject, except using different arguments. * * @param optionsValues - Values that are loaded from config. * @return JsonArray of options for a filter. */ - private static JsonArray generateOptionsValuesObject(List<UiFilterOptionsValuesConfig> optionsValues) { + private static JsonArray generateOptionsValuesObject( + List<UiFilterOptionsValuesConfig> optionsValues) { JsonArrayBuilder optionsBuilder = Json.createArrayBuilder(); - - if(optionsValues != null && !optionsValues.isEmpty()) { - for(UiFilterOptionsValuesConfig optionValue : optionsValues) { + + if (optionsValues != null && !optionsValues.isEmpty()) { + for (UiFilterOptionsValuesConfig optionValue : optionsValues) { JsonObjectBuilder option = Json.createObjectBuilder(); - + option.add(KEY_DECODE, optionValue.getDecode()); option.add(KEY_CODE, optionValue.getCode()); - + optionsBuilder.add(option.build()); } } - + return optionsBuilder.build(); } - + /** * Creates a JsonArray representing the list of options for a filter. * - * @param filterValues - The list of values associates with a filter (likely from a data store query). + * @param filterValues - The list of values associates with a filter (likely from a data store + * query). * @return JsonArray of options for a filter. */ private static JsonArray generateOptionsObject(List<UiFilterValueEntity> filterValues) { JsonArrayBuilder optionsBuilder = Json.createArrayBuilder(); - - if(filterValues != null && !filterValues.isEmpty()) { - for(UiFilterValueEntity valueEntity : filterValues) { + + if (filterValues != null && !filterValues.isEmpty()) { + for (UiFilterValueEntity valueEntity : filterValues) { JsonObjectBuilder option = Json.createObjectBuilder(); - + option.add(KEY_DECODE, valueEntity.getDisplayName()); option.add(KEY_CODE, valueEntity.getFilterValue()); - + optionsBuilder.add(option.build()); } } - + return optionsBuilder.build(); } - + public static JsonObject generateEmptyResponse() { JsonObjectBuilder filterBuilder = Json.createObjectBuilder(); JsonObjectBuilder finalObject = Json.createObjectBuilder(); diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersConfig.java index b1b503c..3853913 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersConfig.java @@ -35,15 +35,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class FiltersConfig { private static final Logger LOG = LoggerFactory.getInstance().getLogger(FiltersConfig.class); - + private static FiltersConfig instance; private String filtersFileName; - + private String filterMappingsFileName; - + private FiltersForViewsConfig viewsConfig; - + private FiltersDetailsConfig filtersConfig; private NetworkStatisticsConfig processorConfig; @@ -112,43 +112,47 @@ public class FiltersConfig { public FiltersDetailsConfig getFiltersConfig() { return filtersConfig; } - + public UiFilterConfig getFilterById(String filterId) { - for ( UiFilterConfig filter : filtersConfig.getFilters()) { - if ( filter.getFilterId().equals(filterId)) { + for (UiFilterConfig filter : filtersConfig.getFilters()) { + if (filter.getFilterId().equals(filterId)) { return filter; } } - + return null; } - + public void setFiltersConfig(FiltersDetailsConfig filtersConfig) { this.filtersConfig = filtersConfig; } - public FiltersDetailsConfig readUiFiltersConfig(){ + public FiltersDetailsConfig readUiFiltersConfig() { ObjectMapper mapper = new ObjectMapper(); FiltersDetailsConfig filtersConfig = null; - try{ - filtersConfig = mapper.readValue(new File(this.getFiltersFileName()), FiltersDetailsConfig.class); + try { + filtersConfig = + mapper.readValue(new File(this.getFiltersFileName()), FiltersDetailsConfig.class); System.out.println(String.valueOf(filtersConfig)); - } catch (Exception e){ - LOG.error(AaiUiMsgs.ERROR_READING_JSON_SCHEMA, TierSupportUiConstants.getConfigPath(this.getFiltersFileName())); + } catch (Exception e) { + LOG.error(AaiUiMsgs.ERROR_READING_JSON_SCHEMA, + TierSupportUiConstants.getConfigPath(this.getFiltersFileName())); } return filtersConfig; } - public FiltersForViewsConfig readUiViewsConfig(){ + public FiltersForViewsConfig readUiViewsConfig() { ObjectMapper mapper = new ObjectMapper(); FiltersForViewsConfig viewsConfig = null; - + try { - viewsConfig = mapper.readValue(new File(this.getFilterMappingsFileName()), FiltersForViewsConfig.class); + viewsConfig = + mapper.readValue(new File(this.getFilterMappingsFileName()), FiltersForViewsConfig.class); System.out.println(String.valueOf(viewsConfig)); - } catch (Exception e){ - LOG.error(AaiUiMsgs.ERROR_READING_JSON_SCHEMA, TierSupportUiConstants.getConfigPath(this.getFilterMappingsFileName())); + } catch (Exception e) { + LOG.error(AaiUiMsgs.ERROR_READING_JSON_SCHEMA, + TierSupportUiConstants.getConfigPath(this.getFilterMappingsFileName())); } return viewsConfig; diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersDetailsConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersDetailsConfig.java index 09eec02..c4905ac 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersDetailsConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersDetailsConfig.java @@ -32,13 +32,13 @@ public class FiltersDetailsConfig { @JsonProperty("filters") private List<UiFilterConfig> filters = new ArrayList<UiFilterConfig>(); - public FiltersDetailsConfig(){} + public FiltersDetailsConfig() {} @JsonCreator public FiltersDetailsConfig(@JsonProperty("filters") final List<UiFilterConfig> filters) { - this.filters = filters; + this.filters = filters; } - + public List<UiFilterConfig> getFilters() { return filters; } @@ -50,6 +50,6 @@ public class FiltersDetailsConfig { @Override public String toString() { return "UiFiltersConfig [filters=" + filters + "]"; - } + } } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersForViewsConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersForViewsConfig.java index 7340758..ea7c305 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersForViewsConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/FiltersForViewsConfig.java @@ -32,13 +32,13 @@ public class FiltersForViewsConfig { private List<UiViewListItemConfig> views = new ArrayList<UiViewListItemConfig>(); - public FiltersForViewsConfig(){} + public FiltersForViewsConfig() {} @JsonCreator public FiltersForViewsConfig(@JsonProperty("views") final List<UiViewListItemConfig> views) { - this.views = views; + this.views = views; } - + @JsonProperty("views") public List<UiViewListItemConfig> getViews() { return views; @@ -46,7 +46,7 @@ public class FiltersForViewsConfig { public void setViews(List<UiViewListItemConfig> views) { this.views = views; - } + } @Override public String toString() { diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterConfig.java index c566565..014407e 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterConfig.java @@ -31,40 +31,40 @@ 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("multiSelect") private String multiSelect; - + @JsonProperty("watermark") private String watermark; - + @JsonProperty("defaultValue") private UiFilterOptionsValuesConfig defaultValue; - + @JsonProperty("optionsType") private String optionsType; - + @JsonProperty("optionsValues") private List<UiFilterOptionsValuesConfig> optionsValues; - + @JsonProperty("dataSource") private UiFilterDataSourceConfig dataSource = new UiFilterDataSourceConfig(); - + @JsonCreator - public UiFilterConfig(@JsonProperty("filterId") final String filterId, - @JsonProperty("filterName") final String filterName, + public UiFilterConfig(@JsonProperty("filterId") final String filterId, + @JsonProperty("filterName") final String filterName, @JsonProperty("displayName") final String displayName, @JsonProperty("dataType") final String dataType, @JsonProperty("multiSelect") final String multiSelect, @@ -72,8 +72,7 @@ public class UiFilterConfig { @JsonProperty("defaultValue") final UiFilterOptionsValuesConfig defaultValue, @JsonProperty("optionsType") final String optionsType, @JsonProperty("optionsValues") final List<UiFilterOptionsValuesConfig> optionsValues, - @JsonProperty("dataSource") final UiFilterDataSourceConfig dataSource - ) { + @JsonProperty("dataSource") final UiFilterDataSourceConfig dataSource) { this.filterId = filterId; this.filterName = filterName; this.displayName = displayName; @@ -139,7 +138,7 @@ public class UiFilterConfig { public void setWatermark(String watermark) { this.watermark = watermark; } - + @JsonProperty("defaultValue") public UiFilterOptionsValuesConfig getDefaultValue() { return defaultValue; @@ -157,6 +156,7 @@ public class UiFilterConfig { public void setOptionsType(String optionsType) { this.optionsType = optionsType; } + @JsonProperty("optionsValues") public List<UiFilterOptionsValuesConfig> getOptionsValues() { return optionsValues; diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterDataSourceConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterDataSourceConfig.java index be0603b..6826dff 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterDataSourceConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterDataSourceConfig.java @@ -29,23 +29,26 @@ 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(){} - + + 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) { + 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; @@ -78,12 +81,12 @@ public class UiFilterDataSourceConfig { public void setFieldName(String fieldName) { this.fieldName = fieldName; } - + @JsonProperty("pathToField") public String getPathToField() { return pathToField; } - + public void setPathToField(String pathToField) { this.pathToField = pathToField; } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterListItemConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterListItemConfig.java index c1ee089..af75bfc 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterListItemConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterListItemConfig.java @@ -31,13 +31,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class UiFilterListItemConfig { @JsonProperty("filterId") private String filterId; - + @JsonProperty("defaultValue") private UiFilterOptionsValuesConfig defaultValue; - + @JsonCreator - public UiFilterListItemConfig(@JsonProperty("filterId") final String filterId, @JsonProperty("defaultValue") final UiFilterOptionsValuesConfig defaultValue) { + public UiFilterListItemConfig(@JsonProperty("filterId") final String filterId, + @JsonProperty("defaultValue") final UiFilterOptionsValuesConfig defaultValue) { this.filterId = filterId; this.defaultValue = defaultValue; } @@ -65,5 +66,5 @@ public class UiFilterListItemConfig { return "FilterListItemEntity [filterId=" + filterId + ", defaultValue=" + defaultValue + "]"; } - + } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterOptionsValuesConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterOptionsValuesConfig.java index 2abdfdd..81da340 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterOptionsValuesConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/UiFilterOptionsValuesConfig.java @@ -31,12 +31,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class UiFilterOptionsValuesConfig { @JsonProperty("decode") private String decode; - + @JsonProperty("code") private String code; - + @JsonCreator - public UiFilterOptionsValuesConfig(@JsonProperty("decode") final String decode, @JsonProperty("code") final String code) { + public UiFilterOptionsValuesConfig(@JsonProperty("decode") final String decode, + @JsonProperty("code") final String code) { this.decode = decode; this.code = code; } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/config/UiViewListItemConfig.java b/src/main/java/org/onap/aai/sparky/search/filters/config/UiViewListItemConfig.java index 3707417..7663693 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/config/UiViewListItemConfig.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/config/UiViewListItemConfig.java @@ -31,11 +31,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class UiViewListItemConfig { @JsonProperty("viewName") private String viewName; - + private List<UiFilterListItemConfig> filters = new ArrayList<UiFilterListItemConfig>(); - + @JsonCreator - public UiViewListItemConfig(@JsonProperty("viewName") final String viewName, @JsonProperty("filters") final List<UiFilterListItemConfig> filters) { + public UiViewListItemConfig(@JsonProperty("viewName") final String viewName, + @JsonProperty("filters") final List<UiFilterListItemConfig> filters) { this.viewName = viewName; this.filters = filters; } @@ -62,5 +63,5 @@ public class UiViewListItemConfig { public String toString() { return "UiViewEntity [viewName=" + viewName + ", filters=" + filters + "]"; } - + } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/entity/AggregationEntity.java b/src/main/java/org/onap/aai/sparky/search/filters/entity/AggregationEntity.java index bf901e2..9e4d6e3 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/entity/AggregationEntity.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/entity/AggregationEntity.java @@ -68,9 +68,8 @@ public class AggregationEntity { JsonBuilderFactory factory = Json.createBuilderFactory(null); return factory.createObjectBuilder() - .add("terms", factory.createObjectBuilder() - .add("field", aggregationFieldName) - .add("size", size)) + .add("terms", + factory.createObjectBuilder().add("field", aggregationFieldName).add("size", size)) .build(); } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/entity/BoolQueryBuilder.java b/src/main/java/org/onap/aai/sparky/search/filters/entity/BoolQueryBuilder.java index dabe061..d376b7d 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/entity/BoolQueryBuilder.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/entity/BoolQueryBuilder.java @@ -36,7 +36,7 @@ public class BoolQueryBuilder { private List<MatchFilterCriteriaEntity> mustFilters; private List<MatchFilterCriteriaEntity> shouldFilters; - + private int minShouldMatch; public BoolQueryBuilder() { @@ -62,15 +62,15 @@ public class BoolQueryBuilder { } } - + public void setMinShouldMatch(int minShouldMatch) { this.minShouldMatch = minShouldMatch; } - + public boolean isMatchAll() { return (mustFilters.isEmpty() && shouldFilters.isEmpty()); } - + public JsonObject getJsonObject() { /* * Specify a null config for now, but if we want normalize all the builders, we can do it at one @@ -80,13 +80,13 @@ public class BoolQueryBuilder { JsonObjectBuilder boolBuilder = factory.createObjectBuilder(); - if(!mustFilters.isEmpty()){ + if (!mustFilters.isEmpty()) { JsonArrayBuilder mustArrayBuilder = factory.createArrayBuilder(); - + for (MatchFilterCriteriaEntity matchCriteria : mustFilters) { mustArrayBuilder.add(matchCriteria.getJsonObject()); } - + JsonArray mustArray = mustArrayBuilder.build(); boolBuilder.add("must", mustArray); } @@ -94,7 +94,7 @@ public class BoolQueryBuilder { if (!shouldFilters.isEmpty()) { JsonArray shouldArray = null; JsonArrayBuilder shouldArrayBuilder = factory.createArrayBuilder(); - + for (MatchFilterCriteriaEntity matchCriteria : shouldFilters) { shouldArrayBuilder.add(matchCriteria.getJsonObject()); } @@ -102,14 +102,14 @@ public class BoolQueryBuilder { shouldArray = shouldArrayBuilder.build(); boolBuilder.add("should", shouldArray).add("min_should_match", minShouldMatch); } - + JsonObjectBuilder queryObjectBuilder = factory.createObjectBuilder(); - - /* - * If both filter lists are empty then we are doing an aggregation - * based off fields. Just match-all for the query. - */ - if(isMatchAll()) { + + /* + * If both filter lists are empty then we are doing an aggregation based off fields. Just + * match-all for the query. + */ + if (isMatchAll()) { JsonObject matchAllObject = factory.createObjectBuilder().build(); queryObjectBuilder.add("match_all", matchAllObject); } else { diff --git a/src/main/java/org/onap/aai/sparky/search/filters/entity/SearchFilter.java b/src/main/java/org/onap/aai/sparky/search/filters/entity/SearchFilter.java index 1b23203..aff4da6 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/entity/SearchFilter.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/entity/SearchFilter.java @@ -43,18 +43,18 @@ public class SearchFilter { public SearchFilter() { values = new ArrayList<String>(); } - + public SearchFilter(String filterId) { this(); this.filterId = filterId; } - + public SearchFilter(String filterId, String... values) { this(); this.filterId = filterId; this.values.addAll(Arrays.asList(values)); } - + public String getFilterId() { return filterId; } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterEntity.java b/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterEntity.java index 2770052..d010bae 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterEntity.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterEntity.java @@ -34,9 +34,10 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * Stores data for a single filter for a given UI view. * <p> - * When a UI view wants to know which filters it should display, an object of this class is created for each - * filter discovered and stores data for that filter. Each filter/object of this class is added to a - * ViewFilterList object which is then serialized to JSON and returned to the view in the response body. + * When a UI view wants to know which filters it should display, an object of this class is created + * for each filter discovered and stores data for that filter. Each filter/object of this class is + * added to a ViewFilterList object which is then serialized to JSON and returned to the view in the + * response body. */ @JsonInclude(Include.NON_NULL) public class UiFilterEntity { @@ -44,18 +45,18 @@ public class UiFilterEntity { private String filterName; private String displayName; private String dataType; - + private String multiSelect; private String watermark; private UiFilterOptionsValuesConfig defaultValue; private String optionsType; - + private List<UiFilterOptionsValuesConfig> optionsValues; - + private List<UiFilterValueEntity> filterValueList; public UiFilterEntity() {} - + public UiFilterEntity(UiFilterConfig filterConfig) { if (filterConfig.getFilterId() != null) { this.setFilterId(filterConfig.getFilterId()); @@ -81,13 +82,13 @@ public class UiFilterEntity { if (filterConfig.getOptionsType() != null) { this.setOptionsType(filterConfig.getOptionsType()); } - if(filterConfig.getOptionsValues() != null && !filterConfig.getOptionsValues().isEmpty()) { + if (filterConfig.getOptionsValues() != null && !filterConfig.getOptionsValues().isEmpty()) { this.setOptionsValues(filterConfig.getOptionsValues()); } else { this.optionsValues = new ArrayList<UiFilterOptionsValuesConfig>(); } } - + public void addFilterValue(UiFilterValueEntity valueEntity) { if (null == filterValueList) { filterValueList = new ArrayList<>(); @@ -103,7 +104,7 @@ public class UiFilterEntity { public String getFilterName() { return filterName; } - + public String getDisplayName() { return displayName; } @@ -111,11 +112,11 @@ public class UiFilterEntity { public String getDataType() { return dataType; } - + public UiFilterOptionsValuesConfig getDefaultValue() { return defaultValue; } - + public List<UiFilterValueEntity> getFilterValueList() { return filterValueList; } @@ -127,7 +128,7 @@ public class UiFilterEntity { public void setFilterName(String filterName) { this.filterName = filterName; } - + public void setDisplayName(String displayName) { this.displayName = displayName; } @@ -135,7 +136,7 @@ public class UiFilterEntity { public void setDataType(String dataType) { this.dataType = dataType; } - + public String getMultiSelect() { return multiSelect; } @@ -159,7 +160,7 @@ public class UiFilterEntity { public void setOptionsType(String optionsType) { this.optionsType = optionsType; } - + public List<UiFilterOptionsValuesConfig> getOptionsValues() { return optionsValues; } @@ -171,7 +172,7 @@ public class UiFilterEntity { public void setDefaultValue(UiFilterOptionsValuesConfig defaultValue) { this.defaultValue = defaultValue; } - + public void setFilterValueList(List<UiFilterValueEntity> values) { this.filterValueList = values; } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterValueEntity.java b/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterValueEntity.java index a0bbd90..f2a238a 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterValueEntity.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFilterValueEntity.java @@ -26,8 +26,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** - * This class represents a single item or value to populate the FE filter component with. - * A drop-down list, for example, may be populated with the values from several instances of this class. + * This class represents a single item or value to populate the FE filter component with. A + * drop-down list, for example, may be populated with the values from several instances of this + * class. */ @JsonInclude(Include.NON_NULL) public class UiFilterValueEntity { @@ -73,6 +74,6 @@ public class UiFilterValueEntity { + (filterValue != null ? "filterValue=" + filterValue + ", " : "") + (displayName != null ? "displayName=" + displayName : "") + "]"; } - - + + } diff --git a/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFiltersEntity.java b/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFiltersEntity.java index 2e8fd17..12036c4 100644 --- a/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFiltersEntity.java +++ b/src/main/java/org/onap/aai/sparky/search/filters/entity/UiFiltersEntity.java @@ -28,15 +28,15 @@ import java.util.List; /** * Represents a list of filters that a given UI view should display. * <p> - * When a UI view wants to know which filters it should display, an object of this class is created to keep - * track of all the filters that are discovered for that view and is then serialized to JSON and returned to - * the view in the response body. + * When a UI view wants to know which filters it should display, an object of this class is created + * to keep track of all the filters that are discovered for that view and is then serialized to JSON + * and returned to the view in the response body. */ public class UiFiltersEntity { private List<UiFilterEntity> filters = new ArrayList<>(); - - + + public void addFilter(UiFilterEntity viewFilter) { filters.add(viewFilter); } diff --git a/src/main/java/org/onap/aai/sparky/security/EcompSso.java b/src/main/java/org/onap/aai/sparky/security/EcompSso.java index 51047cc..16e01c0 100644 --- a/src/main/java/org/onap/aai/sparky/security/EcompSso.java +++ b/src/main/java/org/onap/aai/sparky/security/EcompSso.java @@ -41,7 +41,7 @@ public class EcompSso { public static final String EP_SERVICE = "EPService"; public static final String CSP_COOKIE_NAME = "csp_cookie_name"; public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key"; - public static final String ONAP_ENABLED = "ONAP_ENABLED"; + public static final String ONAP_ENABLED = "ONAP_ENABLED"; private static final Logger LOG = LoggerFactory.getInstance().getLogger(EcompSso.class); /** @@ -87,10 +87,12 @@ public class EcompSso { boolean isOnapEnabled = PortalAuthenticationConfig.getInstance().getIsOnapEnabled(); if (isOnapEnabled) { if (isEPServiceCookiePresent(request)) { - /* This is a "temporary" fix until proper separation - * between closed source and open source code is reached */ + /* + * This is a "temporary" fix until proper separation between closed source and open source + * code is reached + */ return ONAP_ENABLED; - } + } return null; } else { return getLoginIdFromCookie(request); @@ -101,8 +103,8 @@ public class EcompSso { * Searches the specified request for the CSP cookie, decodes it and gets the User ID. * * @param request - * @return User ID if the cookie is present in the request and can be decoded successfully (expired - * cookies do not decode); else null. + * @return User ID if the cookie is present in the request and can be decoded successfully + * (expired cookies do not decode); else null. */ private static String getLoginIdFromCookie(HttpServletRequest request) { String userid = null; @@ -146,10 +148,9 @@ public class EcompSso { String cspCookieDecrypted = ""; try { - cspCookieDecrypted = CipherUtil.decrypt(cspCookieEncrypted,""); + cspCookieDecrypted = CipherUtil.decrypt(cspCookieEncrypted, ""); } catch (Exception e) { - LOG.info(AaiUiMsgs.LOGIN_FILTER_INFO, - "decrypting cookie failed " + e.getLocalizedMessage()); + LOG.info(AaiUiMsgs.LOGIN_FILTER_INFO, "decrypting cookie failed " + e.getLocalizedMessage()); } String[] cspData = cspCookieDecrypted.split("\\|"); diff --git a/src/main/java/org/onap/aai/sparky/security/SecurityContextFactoryImpl.java b/src/main/java/org/onap/aai/sparky/security/SecurityContextFactoryImpl.java index 1e15f11..030309d 100644 --- a/src/main/java/org/onap/aai/sparky/security/SecurityContextFactoryImpl.java +++ b/src/main/java/org/onap/aai/sparky/security/SecurityContextFactoryImpl.java @@ -111,7 +111,7 @@ public class SecurityContextFactoryImpl implements SecurityContextFactory { @Override public void setClientCertFileName(String filename) throws IOException { this.clientCertFileName = filename; - + if (filename == null) { this.clientCertBytes = null; } else { @@ -153,7 +153,7 @@ public class SecurityContextFactoryImpl implements SecurityContextFactory { @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} - } }; + }}; } KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgortihm); @@ -164,7 +164,7 @@ public class SecurityContextFactoryImpl implements SecurityContextFactory { if (clientCertPassword != null) { pwd = clientCertPassword.toCharArray(); } - + if (clientCertBytes != null) { ks.load(new ByteArrayInputStream(clientCertBytes), pwd); } else { diff --git a/src/main/java/org/onap/aai/sparky/security/filter/LoginFilter.java b/src/main/java/org/onap/aai/sparky/security/filter/LoginFilter.java index 6822eba..445cfba 100644 --- a/src/main/java/org/onap/aai/sparky/security/filter/LoginFilter.java +++ b/src/main/java/org/onap/aai/sparky/security/filter/LoginFilter.java @@ -119,7 +119,8 @@ public class LoginFilter implements Filter { final String restApiURI = request.getContextPath() + PortalApiConstants.API_PREFIX; if (request.getRequestURI().startsWith(restApiURI)) { // REST servlet checks credentials - LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: delegating auth to REST servlet for request " + request.getRequestURI()); + LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, + "doFilter: delegating auth to REST servlet for request " + request.getRequestURI()); chain.doFilter(request, response); } else { // All other requests require ECOMP Portal authentication @@ -129,25 +130,25 @@ public class LoginFilter implements Filter { // Redirect to Portal UI redirectURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); logMessage = "Unauthorized login attempt."; - + LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, - logMessage + - " | Remote IP: " + request.getRemoteAddr() + - " | User agent: " + request.getHeader(HttpHeaders.USER_AGENT) + - " | Request URL: " + request.getRequestURL() + - " | Redirecting to: " + redirectURL); - + logMessage + " | Remote IP: " + request.getRemoteAddr() + " | User agent: " + + request.getHeader(HttpHeaders.USER_AGENT) + " | Request URL: " + + request.getRequestURL() + " | Redirecting to: " + redirectURL); + response.sendRedirect(redirectURL); } else { HttpSession session = request.getSession(false); if (session == null) { // New session session = request.getSession(true); - LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: created new session " + session.getId()); + LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, + "doFilter: created new session " + session.getId()); initiateSessionMgtHandler(request); } else { // Existing session - LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: resetting idle in existing session " + session.getId()); + LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, + "doFilter: resetting idle in existing session " + session.getId()); resetSessionMaxIdleTimeOut(request); } // Pass request back down the filter chain @@ -213,14 +214,16 @@ public class LoginFilter implements Filter { try { HttpSession session = request.getSession(false); if (session != null) { - final Object maxIdleAttribute = session - .getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME); + final Object maxIdleAttribute = + session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME); if (maxIdleAttribute != null) { session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString())); } } } catch (Exception e) { - LOG.info(AaiUiMsgs.LOGIN_FILTER_INFO, "resetSessionMaxIdleTimeOut: failed to set session max inactive interval - " + e.getLocalizedMessage()); + LOG.info(AaiUiMsgs.LOGIN_FILTER_INFO, + "resetSessionMaxIdleTimeOut: failed to set session max inactive interval - " + + e.getLocalizedMessage()); } } diff --git a/src/main/java/org/onap/aai/sparky/security/portal/PortalRestAPIServiceImpl.java b/src/main/java/org/onap/aai/sparky/security/portal/PortalRestAPIServiceImpl.java index 9e405b5..050d558 100644 --- a/src/main/java/org/onap/aai/sparky/security/portal/PortalRestAPIServiceImpl.java +++ b/src/main/java/org/onap/aai/sparky/security/portal/PortalRestAPIServiceImpl.java @@ -101,8 +101,8 @@ public class PortalRestAPIServiceImpl implements IPortalRestAPIService { LOG.debug("Push user [loginId:" + user.getLoginId() + "]"); if (userManager.getUser(user.getLoginId()).isPresent()) { - String message = getMessage(ERROR_MESSAGE, "push", user.getLoginId()) - + ", user is already stored"; + String message = + getMessage(ERROR_MESSAGE, "push", user.getLoginId()) + ", user is already stored"; LOG.error(message); throw new PortalAPIException(message); } @@ -245,4 +245,4 @@ public class PortalRestAPIServiceImpl implements IPortalRestAPIService { formatter.applyPattern(message); return formatter.format(args); } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/security/portal/UserManager.java b/src/main/java/org/onap/aai/sparky/security/portal/UserManager.java index acd6f55..9b8e8fc 100644 --- a/src/main/java/org/onap/aai/sparky/security/portal/UserManager.java +++ b/src/main/java/org/onap/aai/sparky/security/portal/UserManager.java @@ -69,8 +69,7 @@ public class UserManager { * @return a list of users. */ public List<EcompUser> getUsers() { - Type collectionType = new TypeToken<List<EcompUser>>() { - }.getType(); + Type collectionType = new TypeToken<List<EcompUser>>() {}.getType(); Optional<String> users = read(usersFile); if (users.isPresent()) { @@ -165,4 +164,4 @@ public class UserManager { READ_LOCK.unlock(); } } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/security/portal/config/PortalAuthenticationConfig.java b/src/main/java/org/onap/aai/sparky/security/portal/config/PortalAuthenticationConfig.java index a4511b2..6f103d0 100644 --- a/src/main/java/org/onap/aai/sparky/security/portal/config/PortalAuthenticationConfig.java +++ b/src/main/java/org/onap/aai/sparky/security/portal/config/PortalAuthenticationConfig.java @@ -40,7 +40,8 @@ public class PortalAuthenticationConfig { public static final String PROP_USERNAME = "username"; public static final String PROP_PASSWORD = "password"; // NOSONAR public static final String PROP_IS_ONAP_ENABLED = "onap_enabled"; // NOSONAR - private static final String AUTHENTICATION_CONFIG_FILE = TierSupportUiConstants.PORTAL_AUTHENTICATION_FILE_LOCATION; + private static final String AUTHENTICATION_CONFIG_FILE = + TierSupportUiConstants.PORTAL_AUTHENTICATION_FILE_LOCATION; private PortalAuthenticationConfig() { // Prevent instantiation @@ -72,7 +73,7 @@ public class PortalAuthenticationConfig { Encryptor encryptor = new Encryptor(); return encryptor.decryptValue(password); } - + public boolean getIsOnapEnabled() { return isOnapEnabled; } @@ -93,4 +94,4 @@ public class PortalAuthenticationConfig { password = props.getProperty(PROP_PASSWORD); isOnapEnabled = Boolean.parseBoolean(props.getProperty(PROP_IS_ONAP_ENABLED, "true")); } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/security/portal/config/RolesConfig.java b/src/main/java/org/onap/aai/sparky/security/portal/config/RolesConfig.java index 4bab100..3ec866e 100644 --- a/src/main/java/org/onap/aai/sparky/security/portal/config/RolesConfig.java +++ b/src/main/java/org/onap/aai/sparky/security/portal/config/RolesConfig.java @@ -79,10 +79,9 @@ public class RolesConfig { } private void load() throws JsonSyntaxException, IOException, URISyntaxException { - Type collectionType = new TypeToken<List<EcompRole>>() { - }.getType(); + Type collectionType = new TypeToken<List<EcompRole>>() {}.getType(); roles = Collections.unmodifiableList(GSON .fromJson(new String(Files.readAllBytes(Paths.get(ROLES_CONFIG_FILE))), collectionType)); } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/suggestivesearch/SuggestionEntity.java b/src/main/java/org/onap/aai/sparky/suggestivesearch/SuggestionEntity.java index 96511c1..92be827 100644 --- a/src/main/java/org/onap/aai/sparky/suggestivesearch/SuggestionEntity.java +++ b/src/main/java/org/onap/aai/sparky/suggestivesearch/SuggestionEntity.java @@ -27,30 +27,34 @@ public class SuggestionEntity { private String hashId;
private String text;
- public SuggestionEntity() {
- }
-
+ public SuggestionEntity() {}
+
public SuggestionEntity(String route, String hashId, String text) {
this.route = route;
this.hashId = hashId;
this.text = text;
}
-
+
public String getRoute() {
return route;
}
+
public void setRoute(String route) {
this.route = route;
}
+
public String getHashId() {
return hashId;
}
+
public void setHashId(String hashId) {
this.hashId = hashId;
}
+
public String getText() {
return text;
}
+
public void setText(String text) {
this.text = text;
}
diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/AbstractEntitySynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/AbstractEntitySynchronizer.java index c6b03ae..dde633c 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/AbstractEntitySynchronizer.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/AbstractEntitySynchronizer.java @@ -60,12 +60,12 @@ public abstract class AbstractEntitySynchronizer { protected ObjectMapper mapper; protected OxmModelLoader oxmModelLoader; protected long syncDurationInMs; + /** * The Enum StatFlag. */ protected enum StatFlag { - AAI_REST_STATS, AAI_ENTITY_STATS, AAI_PROCESSING_EXCEPTION_STATS, - AAI_TASK_PROCESSING_STATS, ES_REST_STATS, ES_ENTITY_STATS, ES_TASK_PROCESSING_STATS + AAI_REST_STATS, AAI_ENTITY_STATS, AAI_PROCESSING_EXCEPTION_STATS, AAI_TASK_PROCESSING_STATS, ES_REST_STATS, ES_ENTITY_STATS, ES_TASK_PROCESSING_STATS } protected EnumSet<StatFlag> enabledStatFlags; @@ -95,8 +95,9 @@ public abstract class AbstractEntitySynchronizer { protected String synchronizerName; protected abstract boolean isSyncDone(); + protected boolean shouldSkipSync; - + public String getActiveInventoryStatisticsReport() { StringBuilder sb = new StringBuilder(128); @@ -255,7 +256,7 @@ public abstract class AbstractEntitySynchronizer { */ protected AbstractEntitySynchronizer(Logger logger, String syncName, int numSyncWorkers, int numActiveInventoryWorkers, int numElasticsearchWorkers, String indexName) - throws Exception { + throws Exception { this.logger = logger; this.synchronizerExecutor = NodeUtils.createNamedExecutor(syncName + "-INTERNAL", numSyncWorkers, logger); @@ -287,11 +288,11 @@ public abstract class AbstractEntitySynchronizer { enabledStatFlags = EnumSet.allOf(StatFlag.class); this.synchronizerName = "Abstact Entity Synchronizer"; - + String txnID = NodeUtils.getRandomTxnId(); - MdcContext.initialize(txnID, "AbstractEntitySynchronizer", "", "Sync", ""); - - this.shouldSkipSync = false; + MdcContext.initialize(txnID, "AbstractEntitySynchronizer", "", "Sync", ""); + + this.shouldSkipSync = false; this.syncStartedTimeStampInMs = System.currentTimeMillis(); this.syncDurationInMs = -1; } @@ -343,7 +344,7 @@ public abstract class AbstractEntitySynchronizer { aaiDataProvider.shutdown(); esDataProvider.shutdown(); } catch (Exception exc) { - logger.error(AaiUiMsgs.ERROR_SHUTDOWN_EXECUTORS, exc ); + logger.error(AaiUiMsgs.ERROR_SHUTDOWN_EXECUTORS, exc); } } diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizer.java index b65a1b4..cd5877a 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizer.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizer.java @@ -102,7 +102,7 @@ public class AggregationSuggestionSynchronizer extends AbstractEntitySynchronize private void syncEntity() { String txnId = NodeUtils.getRandomTxnId(); MdcContext.initialize(txnId, "AggregationSuggestionSynchronizer", "", "Sync", ""); - + AggregationSuggestionEntity syncEntity = new AggregationSuggestionEntity(); syncEntity.deriveFields(); @@ -112,7 +112,7 @@ public class AggregationSuggestionSynchronizer extends AbstractEntitySynchronize } catch (Exception exc) { LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage()); } - + try { String jsonPayload = null; jsonPayload = syncEntity.getIndexDocumentJson(); @@ -124,8 +124,9 @@ public class AggregationSuggestionSynchronizer extends AbstractEntitySynchronize esWorkOnHand.incrementAndGet(); final Map<String, String> contextMap = MDC.getCopyOfContextMap(); - supplyAsync(new PerformElasticSearchPut(jsonPayload, elasticPutTxn, - esDataProvider, contextMap), esPutExecutor).whenComplete((result, error) -> { + supplyAsync( + new PerformElasticSearchPut(jsonPayload, elasticPutTxn, esDataProvider, contextMap), + esPutExecutor).whenComplete((result, error) -> { esWorkOnHand.decrementAndGet(); @@ -171,8 +172,8 @@ public class AggregationSuggestionSynchronizer extends AbstractEntitySynchronize @Override public String getStatReport(boolean shouldDisplayFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return getStatReport(syncDurationInMs, shouldDisplayFinalReport); + syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; + return getStatReport(syncDurationInMs, shouldDisplayFinalReport); } @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSynchronizer.java index dd4daf0..817e633 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSynchronizer.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/AggregationSynchronizer.java @@ -107,7 +107,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer return ae; } } - + private static final Logger LOG = LoggerFactory.getInstance().getLogger(AggregationSynchronizer.class); private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ"; @@ -130,9 +130,9 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer */ public AggregationSynchronizer(String entityType, String indexName) throws Exception { super(LOG, "AGGES-" + indexName.toUpperCase(), 2, 5, 5, indexName); // multiple Autosuggestion - // Entity Synchronizer will - // run for different indices - + // Entity Synchronizer will + // run for different indices + this.entityType = entityType; this.allWorkEnumerated = false; this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>(); @@ -143,14 +143,12 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>(); this.retryQueue = new ConcurrentLinkedDeque<RetryAggregationEntitySyncContainer>(); this.retryLimitTracker = new ConcurrentHashMap<String, Integer>(); - + this.esPutExecutor = NodeUtils.createNamedExecutor("AGGES-ES-PUT", 1, LOG); Map<String, OxmEntityDescriptor> descriptor = new HashMap<String, OxmEntityDescriptor>(); descriptor.put(entityType, oxmModelLoader.getEntityDescriptors().get(entityType)); - this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors( - descriptor); - this.esEntityStats.initializeCountersFromOxmEntityDescriptors( - descriptor); + this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(descriptor); + this.esEntityStats.initializeCountersFromOxmEntityDescriptors(descriptor); this.contextMap = MDC.getCopyOfContextMap(); } @@ -221,8 +219,8 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer return OperationState.OK; } - - + + /** * Perform retry sync. */ @@ -274,7 +272,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer } } } - + /** * Perform document upsert. * @@ -418,7 +416,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer LOG.error(AaiUiMsgs.ERROR_GENERIC, message); } } - + /** * Should allow retry. * @@ -445,7 +443,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer return isRetryAllowed; } - + /** * Process store document result. * @@ -480,7 +478,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer } } } - + /** * Sync entity types. */ @@ -533,7 +531,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer } } - + /** * Fetch document for upsert. * @@ -548,53 +546,53 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer } try { - final String jsonResult = txn.getOperationResult().getResult(); - if (jsonResult != null && jsonResult.length() > 0) { + final String jsonResult = txn.getOperationResult().getResult(); + if (jsonResult != null && jsonResult.length() > 0) { - AggregationEntity ae = new AggregationEntity(oxmModelLoader); - ae.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink())); - populateAggregationEntityDocument(ae, jsonResult, txn.getDescriptor()); - ae.deriveFields(); + AggregationEntity ae = new AggregationEntity(oxmModelLoader); + ae.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink())); + populateAggregationEntityDocument(ae, jsonResult, txn.getDescriptor()); + ae.deriveFields(); - String link = null; - try { - link = getElasticFullUrl("/" + ae.getId(), getIndexName()); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage()); - } + String link = null; + try { + link = getElasticFullUrl("/" + ae.getId(), getIndexName()); + } catch (Exception exc) { + LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage()); + } - if (link != null) { - NetworkTransaction n2 = new NetworkTransaction(); - n2.setLink(link); - n2.setEntityType(txn.getEntityType()); - n2.setDescriptor(txn.getDescriptor()); - n2.setOperationType(HttpMethod.GET); + if (link != null) { + NetworkTransaction n2 = new NetworkTransaction(); + n2.setLink(link); + n2.setEntityType(txn.getEntityType()); + n2.setDescriptor(txn.getDescriptor()); + n2.setOperationType(HttpMethod.GET); - esWorkOnHand.incrementAndGet(); + esWorkOnHand.incrementAndGet(); - supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor) - .whenComplete((result, error) -> { + supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor) + .whenComplete((result, error) -> { - esWorkOnHand.decrementAndGet(); + esWorkOnHand.decrementAndGet(); - if (error != null) { - LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage()); - } else { - updateElasticSearchCounters(result); - performDocumentUpsert(result, ae); - } - }); - } + if (error != null) { + LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage()); + } else { + updateElasticSearchCounters(result); + performDocumentUpsert(result, ae); + } + }); } + } - } catch (JsonProcessingException exc) { + } catch (JsonProcessingException exc) { // TODO -> LOG, waht should be logged here? } catch (IOException exc) { // TODO -> LOG, waht should be logged here? } } - - + + /** * Populate aggregation entity document. * @@ -611,7 +609,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer Map<String, Object> map = mapper.convertValue(entityNode, Map.class); doc.copyAttributeKeyValuePair(map); } - + /** * Process entity type self links. * @@ -628,9 +626,8 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer try { rootNode = mapper.readTree(jsonResult); } catch (IOException exc) { - String message = - "Could not deserialize JSON (representing operation result) as node tree. " + - "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage(); + String message = "Could not deserialize JSON (representing operation result) as node tree. " + + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage(); LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message); return; } @@ -662,8 +659,9 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer continue; } - selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType)); - + selflinks.add(new SelfLinkDescriptor(resourceLink, + SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType)); + } } @@ -679,11 +677,11 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer */ @Override public OperationState doSync() { - this.syncDurationInMs = -1; - syncStartedTimeStampInMs = System.currentTimeMillis(); + this.syncDurationInMs = -1; + syncStartedTimeStampInMs = System.currentTimeMillis(); String txnID = NodeUtils.getRandomTxnId(); MdcContext.initialize(txnID, "AggregationSynchronizer", "", "Sync", ""); - + return collectAllTheWork(); } @@ -705,8 +703,8 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer */ @Override public String getStatReport(boolean showFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return getStatReport(syncDurationInMs, showFinalReport); + syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; + return getStatReport(syncDurationInMs, showFinalReport); } public String getEntityType() { diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/AutosuggestionSynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/AutosuggestionSynchronizer.java index 9da86d5..328fb97 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/AutosuggestionSynchronizer.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/AutosuggestionSynchronizer.java @@ -225,11 +225,11 @@ public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer */ @Override public OperationState doSync() { - this.syncDurationInMs = -1; - syncStartedTimeStampInMs = System.currentTimeMillis(); + this.syncDurationInMs = -1; + syncStartedTimeStampInMs = System.currentTimeMillis(); String txnID = NodeUtils.getRandomTxnId(); MdcContext.initialize(txnID, "AutosuggestionSynchronizer", "", "Sync", ""); - + return collectAllTheWork(); } @@ -343,11 +343,15 @@ public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer } } + /* - * Return a set of valid suggestion attributes for the provided entityName - * that are present in the JSON - * @param node JSON node in which the attributes should be found - * @param entityName Name of the entity + * Return a set of valid suggestion attributes for the provided entityName that are present in the + * JSON + * + * @param node JSON node in which the attributes should be found + * + * @param entityName Name of the entity + * * @return List of all valid suggestion attributes(key's) */ public List<String> getSuggestionFromReponse(JsonNode node, String entityName) { @@ -673,8 +677,8 @@ public class AutosuggestionSynchronizer extends AbstractEntitySynchronizer */ @Override public String getStatReport(boolean showFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return getStatReport(syncDurationInMs, showFinalReport); + syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; + return getStatReport(syncDurationInMs, showFinalReport); } /* diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/CrossEntityReferenceSynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/CrossEntityReferenceSynchronizer.java index 2b2580f..8328627 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/CrossEntityReferenceSynchronizer.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/CrossEntityReferenceSynchronizer.java @@ -103,7 +103,7 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer private static final Logger LOG = LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class); - + private static final String SERVICE_INSTANCE = "service-instance"; private Deque<SelfLinkDescriptor> selflinks; private Deque<RetryCrossEntitySyncContainer> retryQueue; @@ -118,7 +118,8 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer * @param indexName the index name * @throws Exception the exception */ - public CrossEntityReferenceSynchronizer(String indexName, ActiveInventoryConfig aaiConfig) throws Exception { + public CrossEntityReferenceSynchronizer(String indexName, ActiveInventoryConfig aaiConfig) + throws Exception { super(LOG, "CERS", 2, 5, 5, indexName); this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>(); this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>(); @@ -134,15 +135,17 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer this.syncDurationInMs = -1; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync() */ @Override public OperationState doSync() { - this.syncDurationInMs = -1; - String txnID = NodeUtils.getRandomTxnId(); + this.syncDurationInMs = -1; + String txnID = NodeUtils.getRandomTxnId(); MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", ""); - + resetCounters(); syncStartedTimeStampInMs = System.currentTimeMillis(); launchSyncFlow(); @@ -158,16 +161,20 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer return SynchronizerState.IDLE; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean) */ @Override public String getStatReport(boolean showFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return getStatReport(syncDurationInMs, showFinalReport); + syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; + return getStatReport(syncDurationInMs, showFinalReport); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown() */ @Override @@ -192,7 +199,7 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer * @return the operation state */ private OperationState launchSyncFlow() { - final Map<String,String> contextMap = MDC.getCopyOfContextMap(); + final Map<String, String> contextMap = MDC.getCopyOfContextMap(); Map<String, OxmEntityDescriptor> descriptorMap = oxmModelLoader.getCrossReferenceEntityDescriptors(); @@ -219,7 +226,7 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer @Override public Void get() { - MDC.setContextMap(contextMap); + MDC.setContextMap(contextMap); OperationResult typeLinksResult = null; try { typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key); @@ -339,7 +346,7 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer rootNode = mapper.readTree(jsonResult); } catch (IOException exc) { String message = "Could not deserialize JSON (representing operation result) as node tree. " - + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage(); + + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage(); LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message); return; } @@ -370,8 +377,8 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer continue; } if (descriptor.hasCrossEntityReferences()) { - selflinks.add(new SelfLinkDescriptor( - resourceLink,SynchronizerConfiguration.DEPTH_ALL_MODIFIER, resourceType)); + selflinks.add(new SelfLinkDescriptor(resourceLink, + SynchronizerConfiguration.DEPTH_ALL_MODIFIER, resourceType)); } } } @@ -379,46 +386,45 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer } } - - + + /** - * By providing the entity type and a json node for the entity, determine the - * primary key name(s) + primary key value(s) sufficient to build an entity query string - * of the following format: + * By providing the entity type and a json node for the entity, determine the primary key name(s) + * + primary key value(s) sufficient to build an entity query string of the following format: * - * <entityType>.<primaryKeyNames>:<primaryKeyValues> + * <entityType>.<primaryKeyNames>:<primaryKeyValues> * * @return - a composite string in the above format or null */ private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) { - - OxmEntityDescriptor entityDescriptor = - oxmModelLoader.getEntityDescriptor(entityType); - + + OxmEntityDescriptor entityDescriptor = oxmModelLoader.getEntityDescriptor(entityType); + String queryString = null; - - if ( entityDescriptor != null ) { + + if (entityDescriptor != null) { final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeName(); final List<String> keyValues = new ArrayList<String>(); NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues); - queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues); + queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames, "/") + ":" + + NodeUtils.concatArray(keyValues); + + } - } - return queryString; - + } - + /** * Fetch document for upsert. * * @param txn the txn */ private void fetchDocumentForUpsert(NetworkTransaction txn) { - + if (!txn.getOperationResult().wasSuccessful()) { LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult()); return; @@ -427,9 +433,9 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer if (txn.getDescriptor().hasCrossEntityReferences()) { final String jsonResult = txn.getOperationResult().getResult(); - + if (jsonResult != null && jsonResult.length() > 0) { - + /** * Here's what we are going to do: * @@ -444,23 +450,24 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer OxmEntityDescriptor parentEntityDescriptor = oxmModelLoader.getEntityDescriptor(txn.getEntityType()); - - if ( parentEntityDescriptor != null ) { - + + if (parentEntityDescriptor != null) { + CrossEntityReference cerDefinition = parentEntityDescriptor.getCrossEntityReference(); if (cerDefinition != null) { JsonNode convertedNode = null; try { - convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult()); - - final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode); - + convertedNode = + NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult()); + + final String parentEntityQueryString = + determineEntityQueryString(txn.getEntityType(), convertedNode); + List<String> extractedParentEntityAttributeValues = new ArrayList<String>(); NodeUtils.extractFieldValuesFromObject(convertedNode, - cerDefinition.getReferenceAttributes(), - extractedParentEntityAttributeValues); + cerDefinition.getReferenceAttributes(), extractedParentEntityAttributeValues); List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>(); NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(), @@ -468,51 +475,57 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer for (JsonNode targetEntityInstance : nestedTargetEntityInstances) { - OxmEntityDescriptor cerDescriptor = - oxmModelLoader.getSearchableEntityDescriptor(cerDefinition.getTargetEntityType()); + OxmEntityDescriptor cerDescriptor = oxmModelLoader + .getSearchableEntityDescriptor(cerDefinition.getTargetEntityType()); if (cerDescriptor != null) { - + String childEntityType = cerDefinition.getTargetEntityType(); - + List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeName(); - + List<String> childKeyValues = new ArrayList<String>(); - NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues); - - String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues); - + NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, + childKeyValues); + + String childEntityQueryKeyString = + childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames, "/") + ":" + + NodeUtils.concatArray(childKeyValues); + /** * Build generic-query to query child instance self-link from AAI */ List<String> orderedQueryKeyParams = new ArrayList<String>(); if (SERVICE_INSTANCE.equals(childEntityType)) { - orderedQueryKeyParams.clear(); - orderedQueryKeyParams.add(childEntityQueryKeyString); - } else { - orderedQueryKeyParams.add(parentEntityQueryString); - orderedQueryKeyParams.add(childEntityQueryKeyString); - } + orderedQueryKeyParams.clear(); + orderedQueryKeyParams.add(childEntityQueryKeyString); + } else { + orderedQueryKeyParams.add(parentEntityQueryString); + orderedQueryKeyParams.add(childEntityQueryKeyString); + } String genericQueryStr = null; try { - genericQueryStr = aaiDataProvider.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams); - + genericQueryStr = aaiDataProvider.getGenericQueryForSelfLink(childEntityType, + orderedQueryKeyParams); + if (genericQueryStr != null) { aaiWorkOnHand.incrementAndGet(); - OperationResult aaiQueryResult = aaiDataProvider.queryActiveInventoryWithRetries( - genericQueryStr, "application/json", - aaiConfig.getAaiRestConfig().getNumRequestRetries()); + OperationResult aaiQueryResult = aaiDataProvider + .queryActiveInventoryWithRetries(genericQueryStr, "application/json", + aaiConfig.getAaiRestConfig().getNumRequestRetries()); aaiWorkOnHand.decrementAndGet(); - if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) { - + if (aaiQueryResult != null && aaiQueryResult.wasSuccessful()) { + Collection<JsonNode> entityLinks = new ArrayList<JsonNode>(); JsonNode genericQueryResult = null; try { - genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult()); - - if ( genericQueryResult != null ) { - - NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks); + genericQueryResult = + NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult()); + + if (genericQueryResult != null) { + + NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", + entityLinks); String selfLink = null; @@ -521,10 +534,11 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer * an ambiguity exists where we can't reliably determine the self * link, this should be a permanent error */ - LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size())); + LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, + String.valueOf(entityLinks.size())); } else { selfLink = ((JsonNode) entityLinks.toArray()[0]).asText(); - + if (!cerDescriptor.getSearchableAttributes().isEmpty()) { IndexableCrossEntityReference icer = @@ -534,7 +548,7 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer icer.addCrossEntityReferenceValue( parentCrossEntityReferenceAttributeValue); } - + icer.setLink(ActiveInventoryConfig.extractResourcePath(selfLink)); icer.deriveFields(); @@ -543,7 +557,8 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer try { link = getElasticFullUrl("/" + icer.getId(), getIndexName()); } catch (Exception exc) { - LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage()); + LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, + exc.getLocalizedMessage()); } if (link != null) { @@ -561,7 +576,8 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer esWorkOnHand.decrementAndGet(); if (error != null) { - LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage()); + LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, + error.getLocalizedMessage()); } else { updateElasticSearchCounters(result); performDocumentUpsert(result, icer); @@ -575,31 +591,35 @@ public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer } } catch (Exception exc) { - LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage()); + LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), + exc.getLocalizedMessage()); } - + } else { String message = "Entity sync failed because AAI query failed with error "; LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message); } - + } else { - String message = "Entity Sync failed because generic query str could not be determined."; + String message = + "Entity Sync failed because generic query str could not be determined."; LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message); } } catch (Exception exc) { - String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage(); + String message = + "Failed to sync entity because generation of generic query failed with error = " + + exc.getMessage(); LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message); } - + } } - + } catch (IOException ioe) { LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage()); } } - + } else { LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType()); } diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/ElasticSearchIndexCleaner.java b/src/main/java/org/onap/aai/sparky/synchronizer/ElasticSearchIndexCleaner.java index cf18433..59942dc 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/ElasticSearchIndexCleaner.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/ElasticSearchIndexCleaner.java @@ -94,7 +94,9 @@ public class ElasticSearchIndexCleaner implements IndexCleaner { this.numItemsToGetBulkRequest = numItemsToGetBulkRequest; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexCleaner#populatePreOperationCollection() */ @Override @@ -110,7 +112,9 @@ public class ElasticSearchIndexCleaner implements IndexCleaner { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexCleaner#populatePostOperationCollection() */ @Override @@ -124,7 +128,9 @@ public class ElasticSearchIndexCleaner implements IndexCleaner { } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexCleaner#performCleanup() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/IndexIntegrityValidator.java b/src/main/java/org/onap/aai/sparky/synchronizer/IndexIntegrityValidator.java index 0c342bc..b85dabc 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/IndexIntegrityValidator.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/IndexIntegrityValidator.java @@ -39,6 +39,7 @@ public class IndexIntegrityValidator implements IndexValidator { LoggerFactory.getInstance().getLogger(IndexIntegrityValidator.class); private String host; + /** * @return the host */ @@ -139,7 +140,9 @@ public class IndexIntegrityValidator implements IndexValidator { this.indexType = indexType; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexValidator#exists() */ @Override @@ -158,7 +161,9 @@ public class IndexIntegrityValidator implements IndexValidator { } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexValidator#integrityValid() */ @Override @@ -170,7 +175,9 @@ public class IndexIntegrityValidator implements IndexValidator { return true; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexValidator#createOrRepair() */ @Override @@ -195,7 +202,9 @@ public class IndexIntegrityValidator implements IndexValidator { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexValidator#destroyIndex() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/MyErrorHandler.java b/src/main/java/org/onap/aai/sparky/synchronizer/MyErrorHandler.java index 78b6627..7a55b15 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/MyErrorHandler.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/MyErrorHandler.java @@ -77,7 +77,9 @@ public class MyErrorHandler implements ErrorHandler { // The following methods are standard SAX ErrorHandler methods. // See SAX documentation for more info. - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ @Override @@ -85,7 +87,9 @@ public class MyErrorHandler implements ErrorHandler { out.println("Warning: " + getParseExceptionInfo(spe)); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ @Override @@ -94,7 +98,9 @@ public class MyErrorHandler implements ErrorHandler { throw new SAXException(message); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/SearchableEntitySynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/SearchableEntitySynchronizer.java index 32019a6..e10163f 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/SearchableEntitySynchronizer.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/SearchableEntitySynchronizer.java @@ -141,7 +141,7 @@ public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer final Map<String, String> contextMap = MDC.getCopyOfContextMap(); Map<String, OxmEntityDescriptor> descriptorMap = oxmModelLoader.getSearchableEntityDescriptors(); - + if (descriptorMap.isEmpty()) { LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES); LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES); @@ -150,14 +150,15 @@ public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer Collection<String> syncTypes = descriptorMap.keySet(); - /*Collection<String> syncTypes = new ArrayList<String>(); - syncTypes.add("service-instance");*/ + /* + * Collection<String> syncTypes = new ArrayList<String>(); syncTypes.add("service-instance"); + */ try { /* - * launch a parallel async thread to process the documents for each entity-type (to max the - * of the configured executor anyway) + * launch a parallel async thread to process the documents for each entity-type (to max the of + * the configured executor anyway) */ aaiWorkOnHand.set(syncTypes.size()); @@ -222,15 +223,17 @@ public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer return OperationState.OK; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync() */ @Override public OperationState doSync() { - this.syncDurationInMs = -1; + this.syncDurationInMs = -1; String txnID = NodeUtils.getRandomTxnId(); MdcContext.initialize(txnID, "SearchableEntitySynchronizer", "", "Sync", ""); - + resetCounters(); this.allWorkEnumerated = false; syncStartedTimeStampInMs = System.currentTimeMillis(); @@ -255,9 +258,8 @@ public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer try { rootNode = mapper.readTree(jsonResult); } catch (IOException exc) { - String message = - "Could not deserialize JSON (representing operation result) as node tree. " + - "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage(); + String message = "Could not deserialize JSON (representing operation result) as node tree. " + + "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage(); LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message); } @@ -289,7 +291,8 @@ public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer } if (descriptor.hasSearchableAttributes()) { - selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType)); + selflinks.add(new SelfLinkDescriptor(resourceLink, + SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType)); } } @@ -729,16 +732,20 @@ public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean) */ @Override public String getStatReport(boolean showFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return this.getStatReport(syncDurationInMs, showFinalReport); + syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; + return this.getStatReport(syncDurationInMs, showFinalReport); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/SyncController.java b/src/main/java/org/onap/aai/sparky/synchronizer/SyncController.java index 6a6c5e3..0f61923 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/SyncController.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/SyncController.java @@ -47,16 +47,14 @@ public class SyncController { * The Enum InternalState. */ private enum InternalState { - IDLE, PRE_SYNC, SYNC_OPERATION, SELECTIVE_DELETE, ABORTING_SYNC, REPAIRING_INDEX, POST_SYNC, - TEST_INDEX_INTEGRITY, GENERATE_FINAL_REPORT + IDLE, PRE_SYNC, SYNC_OPERATION, SELECTIVE_DELETE, ABORTING_SYNC, REPAIRING_INDEX, POST_SYNC, TEST_INDEX_INTEGRITY, GENERATE_FINAL_REPORT } /** * The Enum SyncActions. */ public enum SyncActions { - SYNCHRONIZE, REPAIR_INDEX, INDEX_INTEGRITY_VALIDATION_COMPLETE, PRE_SYNC_COMPLETE, - SYNC_COMPLETE, SYNC_ABORTED, SYNC_FAILURE, POST_SYNC_COMPLETE, PURGE_COMPLETE, REPORT_COMPLETE + SYNCHRONIZE, REPAIR_INDEX, INDEX_INTEGRITY_VALIDATION_COMPLETE, PRE_SYNC_COMPLETE, SYNC_COMPLETE, SYNC_ABORTED, SYNC_FAILURE, POST_SYNC_COMPLETE, PURGE_COMPLETE, REPORT_COMPLETE } private Collection<IndexSynchronizer> registeredSynchronizers; @@ -90,7 +88,7 @@ public class SyncController { this.currentInternalState = InternalState.IDLE; } - + /** * Change internal state. * @@ -98,8 +96,8 @@ public class SyncController { * @param causedByAction the caused by action */ private void changeInternalState(InternalState newState, SyncActions causedByAction) { - LOG.info(AaiUiMsgs.SYNC_INTERNAL_STATE_CHANGED, controllerName, - currentInternalState.toString(), newState.toString(), causedByAction.toString()); + LOG.info(AaiUiMsgs.SYNC_INTERNAL_STATE_CHANGED, controllerName, currentInternalState.toString(), + newState.toString(), causedByAction.toString()); this.currentInternalState = newState; @@ -426,24 +424,24 @@ public class SyncController { int totalFinished = 0; for (IndexSynchronizer synchronizer : registeredSynchronizers) { - if (dumpPeriodicStatReport) { - if (synchronizer.getState() != SynchronizerState.IDLE) { - String statReport = synchronizer.getStatReport(false); - if (statReport != null) { - LOG.info(AaiUiMsgs.INFO_GENERIC, statReport); - } - } - if (synchronizer.getState() == SynchronizerState.IDLE) { - totalFinished++; - } - } - } - if ( System.currentTimeMillis() > nextReportTimeStampInMs) { - dumpPeriodicStatReport = true; - nextReportTimeStampInMs = System.currentTimeMillis() + 30000L; - } else { - dumpPeriodicStatReport = false; + if (dumpPeriodicStatReport) { + if (synchronizer.getState() != SynchronizerState.IDLE) { + String statReport = synchronizer.getStatReport(false); + if (statReport != null) { + LOG.info(AaiUiMsgs.INFO_GENERIC, statReport); + } + } + if (synchronizer.getState() == SynchronizerState.IDLE) { + totalFinished++; + } } + } + if (System.currentTimeMillis() > nextReportTimeStampInMs) { + dumpPeriodicStatReport = true; + nextReportTimeStampInMs = System.currentTimeMillis() + 30000L; + } else { + dumpPeriodicStatReport = false; + } allDone = (totalFinished == registeredSynchronizers.size()); try { @@ -475,4 +473,4 @@ public class SyncController { } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java b/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java index 617eb08..9081d41 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java @@ -93,14 +93,14 @@ public class SyncHelper { private boolean isInitialSync; public boolean isInitialSync() { - return isInitialSync; - } + return isInitialSync; + } - public void setInitialSync(boolean isInitialSync) { - this.isInitialSync = isInitialSync; - } + public void setInitialSync(boolean isInitialSync) { + this.isInitialSync = isInitialSync; + } - /** + /** * Instantiates a new sync task. * * @param initialSync the initial sync @@ -336,16 +336,15 @@ public class SyncHelper { private List<String> getAutosuggestableEntitiesFromOXM() { Map<String, OxmEntityDescriptor> map = oxmModelLoader.getSuggestionSearchEntityDescriptors(); List<String> suggestableEntities = new ArrayList<String>(); - - for (String entity: map.keySet()){ + + for (String entity : map.keySet()) { suggestableEntities.add(entity); } return suggestableEntities; } /** - * Initialize the AutosuggestionSynchronizer and - * AggregationSuggestionSynchronizer + * Initialize the AutosuggestionSynchronizer and AggregationSuggestionSynchronizer * * @param esConfig * @param aaiAdapter @@ -371,7 +370,7 @@ public class SyncHelper { suggestionSynchronizer.setAaiDataProvider(aaiAdapter); suggestionSynchronizer.setEsDataProvider(esAdapter); syncController.registerEntitySynchronizer(suggestionSynchronizer); - + AggregationSuggestionSynchronizer aggregationSuggestionSynchronizer = new AggregationSuggestionSynchronizer(esConfig.getAutosuggestIndexname()); aggregationSuggestionSynchronizer.setEsDataProvider(esAdapter); @@ -388,7 +387,7 @@ public class SyncHelper { LOG.error(AaiUiMsgs.ERROR_GENERIC, message); } } - + /** * Initialize the AggregationSynchronizer * diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/config/NetworkStatisticsConfig.java b/src/main/java/org/onap/aai/sparky/synchronizer/config/NetworkStatisticsConfig.java index 90429a1..31c8acd 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/config/NetworkStatisticsConfig.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/config/NetworkStatisticsConfig.java @@ -23,7 +23,7 @@ package org.onap.aai.sparky.synchronizer.config; public class NetworkStatisticsConfig { - + private int numSamplesPerThreadForRunningAverage; private String bytesHistogramLabel; @@ -73,7 +73,7 @@ public class NetworkStatisticsConfig { public void setNumSamplesPerThreadForRunningAverage(int numSamplesPerThreadForRunningAverage) { this.numSamplesPerThreadForRunningAverage = numSamplesPerThreadForRunningAverage; } - + public String getBytesHistogramLabel() { return bytesHistogramLabel; } diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java b/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java index a556dc7..8762a0f 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java @@ -24,7 +24,7 @@ package org.onap.aai.sparky.synchronizer.config; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; +import java.text.ParseException; import java.util.Arrays; import java.util.Calendar; import java.util.Date; @@ -47,7 +47,8 @@ import org.onap.aai.cl.eelf.LoggerFactory; */ public class SynchronizerConfiguration { - private static final Logger LOG = LoggerFactory.getInstance().getLogger(SynchronizerConfiguration.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(SynchronizerConfiguration.class); public static final String CONFIG_FILE = TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION + "synchronizer.properties"; @@ -71,20 +72,24 @@ public class SynchronizerConfiguration { /** * Instantiates a new synchronizer configuration. */ - public SynchronizerConfiguration() throws NumberFormatException,PatternSyntaxException,ParseException { - Properties props = ConfigHelper.loadConfigFromExplicitPath(CONFIG_FILE); - initialize(props); - } - - public SynchronizerConfiguration(Properties props) throws NumberFormatException, PatternSyntaxException, ParseException { - initialize(props); - } + public SynchronizerConfiguration() + throws NumberFormatException, PatternSyntaxException, ParseException { + Properties props = ConfigHelper.loadConfigFromExplicitPath(CONFIG_FILE); + initialize(props); + } + + public SynchronizerConfiguration(Properties props) + throws NumberFormatException, PatternSyntaxException, ParseException { + initialize(props); + } + /** * Initialize. * * @throws Exception the exception */ - protected void initialize(Properties props) throws NumberFormatException, PatternSyntaxException, ParseException { + protected void initialize(Properties props) + throws NumberFormatException, PatternSyntaxException, ParseException { // parse config for startup sync try { @@ -124,7 +129,8 @@ public class SynchronizerConfiguration { Pattern pattern = Pattern.compile(SynchronizerConstants.TIMESTAMP24HOURS_PATTERN); Matcher matcher = pattern.matcher(syncTaskStartTime); if (!matcher.matches()) { - throw new PatternSyntaxException("Pattern Mismatch","The erroneous pattern is not available",-1); + throw new PatternSyntaxException("Pattern Mismatch", + "The erroneous pattern is not available", -1); } List<String> timestampVal = Arrays.asList(syncTaskStartTime.split(" ")); @@ -179,7 +185,7 @@ public class SynchronizerConfiguration { autosuggestSynchronizationEnabled = Boolean .parseBoolean(props.getProperty("synchronizer.autosuggestSynchronizationEnabled", "true")); - + if (LOG.isDebugEnabled()) { LOG.debug(AaiUiMsgs.DEBUG_GENERIC, this.toString()); } @@ -243,7 +249,7 @@ public class SynchronizerConfiguration { private boolean nodesOnlyModifierEnabled; - private boolean autosuggestSynchronizationEnabled; + private boolean autosuggestSynchronizationEnabled; private boolean configOkForStartupSync = true; @@ -389,72 +395,70 @@ public class SynchronizerConfiguration { public void setAutosuggestSynchronizationEnabled(boolean autosuggestSynchronizationEnabled) { this.autosuggestSynchronizationEnabled = autosuggestSynchronizationEnabled; } - - public Calendar getTargetSyncTime() { - TimeZone tz = TimeZone.getTimeZone(getSyncTaskStartTimeTimeZone()); - Calendar targetSyncTime = Calendar.getInstance(tz); + public Calendar getTargetSyncTime() { - targetSyncTime.set(Calendar.HOUR_OF_DAY, getSyncTaskStartTimeHr()); - targetSyncTime.set(Calendar.MINUTE, getSyncTaskStartTimeMin()); - targetSyncTime.set(Calendar.SECOND, getSyncTaskStartTimeSec()); + TimeZone tz = TimeZone.getTimeZone(getSyncTaskStartTimeTimeZone()); + Calendar targetSyncTime = Calendar.getInstance(tz); - return targetSyncTime; + targetSyncTime.set(Calendar.HOUR_OF_DAY, getSyncTaskStartTimeHr()); + targetSyncTime.set(Calendar.MINUTE, getSyncTaskStartTimeMin()); + targetSyncTime.set(Calendar.SECOND, getSyncTaskStartTimeSec()); - } + return targetSyncTime; - public long getDefaultInitialSyncDelayInMs(Calendar timeNow) { + } - int taskFrequencyInDays = getSyncTaskFrequencyInDay(); + public long getDefaultInitialSyncDelayInMs(Calendar timeNow) { - long nextSyncTimeInMs = getNextSyncTime(getTargetSyncTime(), timeNow.getTimeInMillis(), - taskFrequencyInDays * 86400); + int taskFrequencyInDays = getSyncTaskFrequencyInDay(); - /* - * If the the current time is after the scheduled start time, then delay - * by the initial task delay configuration value - */ - long delayUntilNextSyncInMs = Math.max(getSyncTaskInitialDelayInMs(), - nextSyncTimeInMs - timeNow.getTimeInMillis()); + long nextSyncTimeInMs = getNextSyncTime(getTargetSyncTime(), timeNow.getTimeInMillis(), + taskFrequencyInDays * 86400); - return delayUntilNextSyncInMs; + /* + * If the the current time is after the scheduled start time, then delay by the initial task + * delay configuration value + */ + long delayUntilNextSyncInMs = + Math.max(getSyncTaskInitialDelayInMs(), nextSyncTimeInMs - timeNow.getTimeInMillis()); - } + return delayUntilNextSyncInMs; - public long getNextSyncTime(Calendar syncTime, int taskFrequencyInSeconds) { + } - TimeZone tz = TimeZone.getTimeZone(getSyncTaskStartTimeTimeZone()); - Calendar timeNow = Calendar.getInstance(tz); + public long getNextSyncTime(Calendar syncTime, int taskFrequencyInSeconds) { - return getNextSyncTime(syncTime, timeNow.getTimeInMillis(), taskFrequencyInSeconds); - } + TimeZone tz = TimeZone.getTimeZone(getSyncTaskStartTimeTimeZone()); + Calendar timeNow = Calendar.getInstance(tz); - /** - * Gets the first sync time. - * - * @param calendar - * the calendar - * @param timeNow - * the time now in ms - * @param taskFrequencyInMs - * task period in ms - * @return the first sync time - */ - public long getNextSyncTime(Calendar syncTime, long timeNowInMs, int taskFrequencyInSeconds) { - if (taskFrequencyInSeconds == 0) { - return 0; - } else if (timeNowInMs > syncTime.getTimeInMillis()) { + return getNextSyncTime(syncTime, timeNow.getTimeInMillis(), taskFrequencyInSeconds); + } - /* - * If current time is after the scheduled sync start time, then - * we'll skip ahead to the next sync time period - */ + /** + * Gets the first sync time. + * + * @param calendar the calendar + * @param timeNow the time now in ms + * @param taskFrequencyInMs task period in ms + * @return the first sync time + */ + public long getNextSyncTime(Calendar syncTime, long timeNowInMs, int taskFrequencyInSeconds) { + if (taskFrequencyInSeconds == 0) { + return 0; + } else if (timeNowInMs > syncTime.getTimeInMillis()) { + + /* + * If current time is after the scheduled sync start time, then we'll skip ahead to the next + * sync time period + */ - syncTime.add(Calendar.SECOND, taskFrequencyInSeconds); - } + syncTime.add(Calendar.SECOND, taskFrequencyInSeconds); + } + + return syncTime.getTimeInMillis(); + } - return syncTime.getTimeInMillis(); - } /** * @return the instance */ @@ -511,7 +515,9 @@ public class SynchronizerConfiguration { return NODES_ONLY_MODIFIER; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override @@ -531,7 +537,7 @@ public class SynchronizerConfiguration { + ", displayVerboseQueueManagerStats=" + displayVerboseQueueManagerStats + ", resourceNotFoundErrorsSupressed=" + resourceNotFoundErrorsSupressed + ", nodesOnlyModifierEnabled=" + nodesOnlyModifierEnabled + ", configOKForStartupSync=" - + configOkForStartupSync + ", configOKForPeriodicSync=" + configOkForPeriodicSync + + configOkForStartupSync + ", configOKForPeriodicSync=" + configOkForPeriodicSync + ", autosuggestSynchronizationEnabled=" + autosuggestSynchronizationEnabled + "]"; } diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationEntity.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationEntity.java index af8159a..b2958b1 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationEntity.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationEntity.java @@ -37,7 +37,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; public class AggregationEntity extends IndexableEntity implements IndexDocument { private Map<String, String> attributes = new HashMap<String, String>(); protected ObjectMapper mapper = new ObjectMapper(); - + /** * Instantiates a new aggregation entity. */ @@ -54,7 +54,9 @@ public class AggregationEntity extends IndexableEntity implements IndexDocument super(loader); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.entity.IndexDocument#deriveFields() */ @Override @@ -66,19 +68,20 @@ public class AggregationEntity extends IndexableEntity implements IndexDocument * The best we can hope for is identification of resources by generated Id until the * Identity-Service UUID is tagged against all resources, then we can use that instead. */ - this.id = - NodeUtils.generateUniqueShaDigest(link); + this.id = NodeUtils.generateUniqueShaDigest(link); } - public void copyAttributeKeyValuePair(Map<String, Object> map){ - for(String key: map.keySet()){ - if (!key.equalsIgnoreCase("relationship-list")){ // ignore relationship data which is not required in aggregation - this.attributes.put(key, map.get(key).toString()); // not sure if entity attribute can contain an object as value + public void copyAttributeKeyValuePair(Map<String, Object> map) { + for (String key : map.keySet()) { + if (!key.equalsIgnoreCase("relationship-list")) { // ignore relationship data which is not + // required in aggregation + this.attributes.put(key, map.get(key).toString()); // not sure if entity attribute can + // contain an object as value } } } - - public void addAttributeKeyValuePair(String key, String value){ + + public void addAttributeKeyValuePair(String key, String value) { this.attributes.put(key, value); } @@ -87,7 +90,7 @@ public class AggregationEntity extends IndexableEntity implements IndexDocument ObjectNode rootNode = mapper.createObjectNode(); rootNode.put("link", this.getLink()); rootNode.put("lastmodTimestamp", this.getEntityTimeStamp()); - for (String key: this.attributes.keySet()){ + for (String key : this.attributes.keySet()) { rootNode.put(key, this.attributes.get(key)); } return rootNode.toString(); @@ -121,13 +124,15 @@ public class AggregationEntity extends IndexableEntity implements IndexDocument this.mapper = mapper; } -@Override + @Override public ObjectNode getBulkImportEntity() { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntity.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntity.java index 145b23f..412798e 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntity.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntity.java @@ -35,6 +35,7 @@ import org.onap.aai.sparky.util.NodeUtils; public class AggregationSuggestionEntity extends IndexableEntity implements IndexDocument { private List<String> inputs = new ArrayList<String>(); + /** * @return the inputs */ @@ -72,13 +73,13 @@ public class AggregationSuggestionEntity extends IndexableEntity implements Inde private final String outputString = "VNFs"; protected ObjectMapper mapper = new ObjectMapper(); - + public AggregationSuggestionEntity() { super(); inputs.add("VNFs"); inputs.add("generic-vnfs"); } - + @Override public void deriveFields() { this.id = NodeUtils.generateUniqueShaDigest(this.outputString); @@ -86,23 +87,23 @@ public class AggregationSuggestionEntity extends IndexableEntity implements Inde @Override public String getIndexDocumentJson() { - + JSONArray inputArray = new JSONArray(); - for (String input: inputs) { - input = input.replace(",","" ); - input = input.replace("[","" ); - input = input.replace("]","" ); + for (String input : inputs) { + input = input.replace(",", ""); + input = input.replace("[", ""); + input = input.replace("]", ""); inputArray.put(input); } - + JSONObject entitySuggest = new JSONObject(); entitySuggest.put("input", inputArray); entitySuggest.put("output", this.outputString); entitySuggest.put("weight", 100); - + JSONObject payloadNode = new JSONObject(); entitySuggest.put("payload", payloadNode); - + JSONObject rootNode = new JSONObject(); rootNode.put("entity_suggest", entitySuggest); diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexDocument.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexDocument.java index 6e23c62..0633da4 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexDocument.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexDocument.java @@ -28,7 +28,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; * The Interface IndexDocument. */ public interface IndexDocument { - + /** * Derive fields. */ diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableCrossEntityReference.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableCrossEntityReference.java index bb564f3..3c454f6 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableCrossEntityReference.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableCrossEntityReference.java @@ -38,9 +38,10 @@ import com.fasterxml.jackson.databind.node.ObjectNode; public class IndexableCrossEntityReference extends IndexableEntity implements IndexDocument { protected String crossReferenceEntityValues; + /** - * @return the crossReferenceEntityValues - */ + * @return the crossReferenceEntityValues + */ public String getCrossReferenceEntityValues() { return crossReferenceEntityValues; } @@ -66,21 +67,21 @@ public class IndexableCrossEntityReference extends IndexableEntity implements In this.crossEntityReferenceCollection = crossEntityReferenceCollection; } -/** - * @return the mapper - */ -public ObjectMapper getMapper() { - return mapper; -} + /** + * @return the mapper + */ + public ObjectMapper getMapper() { + return mapper; + } -/** - * @param mapper the mapper to set - */ -public void setMapper(ObjectMapper mapper) { - this.mapper = mapper; -} + /** + * @param mapper the mapper to set + */ + public void setMapper(ObjectMapper mapper) { + this.mapper = mapper; + } -protected ArrayList<String> crossEntityReferenceCollection = new ArrayList<String>(); + protected ArrayList<String> crossEntityReferenceCollection = new ArrayList<String>(); protected ObjectMapper mapper = new ObjectMapper(); /** @@ -110,7 +111,9 @@ protected ArrayList<String> crossEntityReferenceCollection = new ArrayList<Strin } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.entity.IndexDocument#deriveFields() */ @Override @@ -136,7 +139,9 @@ protected ArrayList<String> crossEntityReferenceCollection = new ArrayList<Strin return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableEntity.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableEntity.java index 4c9a5c6..deeac35 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableEntity.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/IndexableEntity.java @@ -71,7 +71,7 @@ public abstract class IndexableEntity { return TIMESTAMP_FORMAT; } -protected String link; + protected String link; protected OxmModelLoader loader; private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/MergableEntity.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/MergableEntity.java index f709ee0..f998872 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/MergableEntity.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/MergableEntity.java @@ -35,13 +35,13 @@ public class MergableEntity { private Map<String, String> other = new HashMap<String, String>(); /** - * @param other the other to set - */ -public void setOther(Map<String, String> other) { - this.other = other; -} + * @param other the other to set + */ + public void setOther(Map<String, String> other) { + this.other = other; + } -/** + /** * Any. * * @return the map @@ -52,10 +52,10 @@ public void setOther(Map<String, String> other) { } public Map<String, String> getOther() { - return other; -} + return other; + } -/** + /** * Sets the. * * @param name the name diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/ObjectIdCollection.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/ObjectIdCollection.java index e17c430..158cb1d 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/ObjectIdCollection.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/ObjectIdCollection.java @@ -34,24 +34,23 @@ public class ObjectIdCollection { protected ConcurrentHashMap<String, String> importedObjectIds = new ConcurrentHashMap<String, String>(); - /** - * @return the importedObjectIds - */ - public ConcurrentHashMap<String, String> getImportedObjectIds() { - return importedObjectIds; - } + /** + * @return the importedObjectIds + */ + public ConcurrentHashMap<String, String> getImportedObjectIds() { + return importedObjectIds; + } - /** - * @param importedObjectIds - * the importedObjectIds to set - */ - public void setImportedObjectIds(ConcurrentHashMap<String, String> importedObjectIds) { - this.importedObjectIds = importedObjectIds; - } + /** + * @param importedObjectIds the importedObjectIds to set + */ + public void setImportedObjectIds(ConcurrentHashMap<String, String> importedObjectIds) { + this.importedObjectIds = importedObjectIds; + } - public Collection<String> getImportedObjectIdsAsValues() { - return importedObjectIds.values(); - } + public Collection<String> getImportedObjectIdsAsValues() { + return importedObjectIds.values(); + } /** * Adds the object id. diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/SearchableEntity.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/SearchableEntity.java index e7cfab1..08a80ea 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/SearchableEntity.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/SearchableEntity.java @@ -36,6 +36,7 @@ import org.onap.aai.sparky.util.NodeUtils; */ public class SearchableEntity extends IndexableEntity implements IndexDocument { protected List<String> searchTagCollection = new ArrayList<String>(); + /** * @return the mapper */ @@ -102,7 +103,7 @@ public class SearchableEntity extends IndexableEntity implements IndexDocument { */ protected String searchTags; // generated based on searchTagCollection values protected String searchTagIDs; - + /** * Generates the sha based id. */ @@ -110,7 +111,9 @@ public class SearchableEntity extends IndexableEntity implements IndexDocument { this.id = NodeUtils.generateUniqueShaDigest(link); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.onap.aai.sparky.synchronizer.entity.IndexDocument#deriveFields() */ @Override @@ -172,7 +175,9 @@ public class SearchableEntity extends IndexableEntity implements IndexDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/SelfLinkDescriptor.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/SelfLinkDescriptor.java index 453b47c..20e59ef 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/SelfLinkDescriptor.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/SelfLinkDescriptor.java @@ -57,7 +57,7 @@ public class SelfLinkDescriptor { public SelfLinkDescriptor(String selfLink) { this(selfLink, null, null); } - + /** * Instantiates a new self link descriptor. * @@ -74,7 +74,9 @@ public class SelfLinkDescriptor { this.depthModifier = depthModifier; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntity.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntity.java index ffe92cf..d699031 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntity.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntity.java @@ -42,6 +42,7 @@ public class SuggestionSearchEntity extends IndexableEntity implements IndexDocu private String entityType; private List<String> suggestionConnectorWords = new ArrayList<String>(); private List<String> suggestionAttributeTypes = new ArrayList<String>(); + /** * @return the suggestionAttributeTypes */ @@ -129,8 +130,8 @@ public class SuggestionSearchEntity extends IndexableEntity implements IndexDocu public void setPayload(Map<String, String> payload) { this.payload = payload; } - - + + public JSONObject getPayloadJsonNode() { return payloadJsonNode; } @@ -284,22 +285,22 @@ public class SuggestionSearchEntity extends IndexableEntity implements IndexDocu @Override public void deriveFields() { - + int payloadEntryCounter = 1; for (Map.Entry<String, String> payload : getPayload().entrySet()) { // Add the payload(status) only if a valid value is present - if (payload.getValue() != null &&payload.getValue().length() > 0) { + if (payload.getValue() != null && payload.getValue().length() > 0) { this.getPayloadJsonNode().put(payload.getKey(), payload.getValue()); this.outputString.append(payload.getValue()); if (payloadEntryCounter < getPayload().entrySet().size()) { this.outputString.append(" and "); - } else{ + } else { this.outputString.append(" "); } } payloadEntryCounter++; } - + this.outputString.append(this.getAliasToUse()); this.id = NodeUtils.generateUniqueShaDigest(outputString.toString()); } diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/entity/TransactionStorageType.java b/src/main/java/org/onap/aai/sparky/synchronizer/entity/TransactionStorageType.java index 7bb131c..635281e 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/entity/TransactionStorageType.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/entity/TransactionStorageType.java @@ -45,7 +45,7 @@ public enum TransactionStorageType { this.outputFolder = outputFolder; } -private String outputFolder; + private String outputFolder; /** * Instantiates a new transaction storage type. diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/filter/ElasticSearchSynchronizerFilter.java b/src/main/java/org/onap/aai/sparky/synchronizer/filter/ElasticSearchSynchronizerFilter.java index b001abb..ef199f7 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/filter/ElasticSearchSynchronizerFilter.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/filter/ElasticSearchSynchronizerFilter.java @@ -56,11 +56,14 @@ import org.onap.aai.cl.mdc.MdcContext; */ public class ElasticSearchSynchronizerFilter implements Filter { - private static final Logger LOG = LoggerFactory.getInstance().getLogger(ElasticSearchSynchronizerFilter.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(ElasticSearchSynchronizerFilter.class); private SyncHelper syncHelper; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.Filter#destroy() */ @Override @@ -71,8 +74,11 @@ public class ElasticSearchSynchronizerFilter implements Filter { } } - /* (non-Javadoc) - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) + /* + * (non-Javadoc) + * + * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, + * javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) @@ -86,15 +92,17 @@ public class ElasticSearchSynchronizerFilter implements Filter { chain.doFilter(request, response); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { - String txnID = NodeUtils.getRandomTxnId(); - MdcContext.initialize(txnID, "ElasticSearchSynchronizerFilter", "", "Init", ""); - - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "init()"); + String txnID = NodeUtils.getRandomTxnId(); + MdcContext.initialize(txnID, "ElasticSearchSynchronizerFilter", "", "Init", ""); + + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "init()"); try { new SyncHelper(OxmModelLoader.getInstance()); diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntitySelfLinkTask.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntitySelfLinkTask.java index 34561a6..b12a1d9 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntitySelfLinkTask.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntitySelfLinkTask.java @@ -48,7 +48,9 @@ public class CollectEntitySelfLinkTask implements Supplier<NetworkTransaction> { this.provider = provider; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntityTypeSelfLinksTask.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntityTypeSelfLinksTask.java index 9368881..712a2e3 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntityTypeSelfLinksTask.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/CollectEntityTypeSelfLinksTask.java @@ -49,7 +49,9 @@ public class CollectEntityTypeSelfLinksTask implements Supplier<NetworkTransacti this.txn = txn; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/GetCrossEntityReferenceEntityTask.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/GetCrossEntityReferenceEntityTask.java index 7c58147..8c1e0b7 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/GetCrossEntityReferenceEntityTask.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/GetCrossEntityReferenceEntityTask.java @@ -49,7 +49,9 @@ public class GetCrossEntityReferenceEntityTask implements Supplier<NetworkTransa this.provider = provider; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrieval.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrieval.java index f3b1dff..33d3610 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrieval.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrieval.java @@ -62,7 +62,9 @@ public class PerformActiveInventoryRetrieval implements Supplier<NetworkTransact this.contextMap = MDC.getCopyOfContextMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override @@ -75,7 +77,8 @@ public class PerformActiveInventoryRetrieval implements Supplier<NetworkTransact OperationResult result = null; try { // todo: use proper config instead of hard-coding parameters - final String absoluteSelfLink = ActiveInventoryConfig.getConfig().repairSelfLink(txn.getLink()); + final String absoluteSelfLink = + ActiveInventoryConfig.getConfig().repairSelfLink(txn.getLink()); result = aaiProvider.queryActiveInventoryWithRetries(absoluteSelfLink, "application/json", 5); } catch (Exception exc) { logger.error("Failure to resolve self link from AAI. Error = ", exc); diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchPut.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchPut.java index c3ce3f5..e1bbd56 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchPut.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchPut.java @@ -54,7 +54,7 @@ public class PerformElasticSearchPut implements Supplier<NetworkTransaction> { this.restDataProvider = restDataProvider; this.contextMap = MDC.getCopyOfContextMap(); } - + public PerformElasticSearchPut(String jsonPayload, NetworkTransaction txn, RestDataProvider restDataProvider, Map<String, String> contextMap) { this.jsonPayload = jsonPayload; @@ -63,7 +63,9 @@ public class PerformElasticSearchPut implements Supplier<NetworkTransaction> { this.contextMap = contextMap; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override @@ -71,7 +73,7 @@ public class PerformElasticSearchPut implements Supplier<NetworkTransaction> { txn.setTaskAgeInMs(); long startTimeInMs = System.currentTimeMillis(); MDC.setContextMap(contextMap); - + OperationResult or = restDataProvider.doPut(txn.getLink(), jsonPayload, "application/json"); or.setResponseTimeInMs(System.currentTimeMillis() - startTimeInMs); diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchRetrieval.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchRetrieval.java index b11b023..f3f3c16 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchRetrieval.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchRetrieval.java @@ -52,12 +52,14 @@ public class PerformElasticSearchRetrieval implements Supplier<NetworkTransactio this.contextMap = MDC.getCopyOfContextMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override public NetworkTransaction get() { - MDC.setContextMap(contextMap); + MDC.setContextMap(contextMap); OperationResult or = restDataProvider.doGet(txn.getLink(), "application/json"); txn.setOperationResult(or); return txn; diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchUpdate.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchUpdate.java index 956fe35..72b48c9 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchUpdate.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/PerformElasticSearchUpdate.java @@ -61,7 +61,9 @@ public class PerformElasticSearchUpdate implements Supplier<NetworkTransaction> operationTracker.setOperationType(transactionTracker.getOperationType()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/PersistOperationResultToDisk.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/PersistOperationResultToDisk.java index d0a5cc1..0ab331e 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/PersistOperationResultToDisk.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/PersistOperationResultToDisk.java @@ -62,12 +62,14 @@ public class PersistOperationResultToDisk implements Supplier<Void> { this.contextMap = MDC.getCopyOfContextMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override public Void get() { - MDC.setContextMap(contextMap); + MDC.setContextMap(contextMap); File file = new File(fullPath); if (!file.exists()) { try { diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/RetrieveOperationResultFromDisk.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/RetrieveOperationResultFromDisk.java index 7087d38..0e11319 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/RetrieveOperationResultFromDisk.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/RetrieveOperationResultFromDisk.java @@ -58,7 +58,9 @@ public class RetrieveOperationResultFromDisk implements Supplier<OperationResult this.logger = logger; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/task/StoreDocumentTask.java b/src/main/java/org/onap/aai/sparky/synchronizer/task/StoreDocumentTask.java index 2719d92..3e31d12 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/task/StoreDocumentTask.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/task/StoreDocumentTask.java @@ -114,7 +114,9 @@ public class StoreDocumentTask implements Supplier<NetworkTransaction> { this.contextMap = MDC.getCopyOfContextMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/util/Encryptor.java b/src/main/java/org/onap/aai/sparky/util/Encryptor.java index 828a891..80aefd0 100644 --- a/src/main/java/org/onap/aai/sparky/util/Encryptor.java +++ b/src/main/java/org/onap/aai/sparky/util/Encryptor.java @@ -37,9 +37,8 @@ public class Encryptor { /** * Instantiates a new encryptor. */ - public Encryptor() { - } - + public Encryptor() {} + /** * Decrypt value. * @@ -48,9 +47,9 @@ public class Encryptor { */ public String decryptValue(String value) { String decyptedValue = ""; - - decyptedValue = Password.deobfuscate(value); - + + decyptedValue = Password.deobfuscate(value); + return decyptedValue; } diff --git a/src/main/java/org/onap/aai/sparky/util/KeystoreBuilder.java b/src/main/java/org/onap/aai/sparky/util/KeystoreBuilder.java index 4058a0d..d3ae421 100644 --- a/src/main/java/org/onap/aai/sparky/util/KeystoreBuilder.java +++ b/src/main/java/org/onap/aai/sparky/util/KeystoreBuilder.java @@ -96,7 +96,9 @@ public class KeystoreBuilder { this.port = port; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override @@ -258,7 +260,7 @@ public class KeystoreBuilder { private X509Certificate[] getCertificateChainForRemoteEndpoint(String hostname, int port) throws UnknownHostException, IOException { - System.out.println("Opening connection to "+hostname+":"+port+".."); + System.out.println("Opening connection to " + hostname + ":" + port + ".."); SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(hostname, port); socket.setSoTimeout(10000); @@ -270,7 +272,8 @@ public class KeystoreBuilder { System.exit(0); } catch (SSLException exc) { System.out.println("\nCaught SSL exception, we are not authorized to access this server yet"); - throw new SSLException("\nCaught SSL exception, we are not authorized to access this server yet"); + throw new SSLException( + "\nCaught SSL exception, we are not authorized to access this server yet"); // e.printStackTrace(System.out); } @@ -432,8 +435,11 @@ public class KeystoreBuilder { throw new UnsupportedOperationException(); } - /* (non-Javadoc) - * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], + * java.lang.String) */ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) @@ -441,8 +447,11 @@ public class KeystoreBuilder { throw new UnsupportedOperationException(); } - /* (non-Javadoc) - * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], + * java.lang.String) */ @Override public void checkServerTrusted(X509Certificate[] chain, String authType) @@ -520,8 +529,7 @@ public class KeystoreBuilder { */ if (args.length != 4) { - System.out.println( - "Usage: KeyBuilder <[ip:port];*> <keystoreFileName>" + System.out.println("Usage: KeyBuilder <[ip:port];*> <keystoreFileName>" + " <keystorePassword> <dumpCertDetails> "); System.exit(1); } diff --git a/src/main/java/org/onap/aai/sparky/util/NodeUtils.java b/src/main/java/org/onap/aai/sparky/util/NodeUtils.java index 3c2466d..20e547f 100644 --- a/src/main/java/org/onap/aai/sparky/util/NodeUtils.java +++ b/src/main/java/org/onap/aai/sparky/util/NodeUtils.java @@ -67,7 +67,7 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder; */ public class NodeUtils { private static SecureRandom sRandom = new SecureRandom(); - + /** * @return the sRandom */ @@ -96,10 +96,10 @@ public class NodeUtils { return TIME_BREAK_DOWN_FORMAT; } - public static synchronized String getRandomTxnId(){ - byte bytes[] = new byte[6]; - sRandom.nextBytes(bytes); - return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt()); + public static synchronized String getRandomTxnId() { + byte bytes[] = new byte[6]; + sRandom.nextBytes(bytes); + return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt()); } /** @@ -144,7 +144,8 @@ public class NodeUtils { * @param logger the logger * @return the executor service */ - public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) { + public static ExecutorService createNamedExecutor(String name, int numWorkers, + final Logger logger) { UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override @@ -479,7 +480,7 @@ public class NodeUtils { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - + if (pretty) { ow = mapper.writer().withDefaultPrettyPrinter(); @@ -535,10 +536,10 @@ public class NodeUtils { public static void extractObjectsByKey(JsonNode node, String searchKey, Collection<JsonNode> foundObjects) { - if ( node == null ) { + if (node == null) { return; } - + if (node.isObject()) { Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields(); @@ -677,7 +678,7 @@ public class NodeUtils { return timestamp; } } - + /** * Gets the HttpRequest payload. * diff --git a/src/main/java/org/onap/aai/sparky/util/ServletUtils.java b/src/main/java/org/onap/aai/sparky/util/ServletUtils.java index ec8b555..2a8159e 100644 --- a/src/main/java/org/onap/aai/sparky/util/ServletUtils.java +++ b/src/main/java/org/onap/aai/sparky/util/ServletUtils.java @@ -100,8 +100,8 @@ public class ServletUtils { */ public static void handleSearchServletErrors(Logger logger, String errorMsg, Exception exc, HttpServletResponse response) throws IOException { - String errorLogMsg = (exc == null ? errorMsg : errorMsg + ". Error:" - + exc.getLocalizedMessage()); + String errorLogMsg = + (exc == null ? errorMsg : errorMsg + ". Error:" + exc.getLocalizedMessage()); logger.error(AaiUiMsgs.ERROR_GENERIC, errorLogMsg); response.setContentType("application/json"); PrintWriter out = response.getWriter(); diff --git a/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java b/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java index 205534f..463d122 100644 --- a/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java +++ b/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java @@ -26,16 +26,15 @@ import java.util.ArrayList; import java.util.List;
public class SuggestionsPermutation {
-
+
/*
- * Will return all the unique combinations of the suggestions provided.
- * The order of the permutation is not taken into account when computing
- * the uniqueness.
- * eg: A list of A,B,C,D will return
- * [[A], [A, B, C, D], [A, C, D], [A, D], [B], [B, C, D], [B, D], [C], [C, D], [D]]
+ * Will return all the unique combinations of the suggestions provided. The order of the
+ * permutation is not taken into account when computing the uniqueness. eg: A list of A,B,C,D will
+ * return [[A], [A, B, C, D], [A, C, D], [A, D], [B], [B, C, D], [B, D], [C], [C, D], [D]]
*
* @param list The list to create the unique permutations
- * @return A Arraylist which contains a array list of all possible combinations
+ *
+ * @return A Arraylist which contains a array list of all possible combinations
*/
@SuppressWarnings("serial")
public ArrayList<ArrayList<String>> getSuggestionsPermutation(List<String> list) {
@@ -54,7 +53,7 @@ public class SuggestionsPermutation { dupStatusList = truncateListUntill(statusList, mainLoopIndexCounter);
while (dupStatusList.size() > 0) {
- ArrayList<String> suggListInIterate= new ArrayList<>();
+ ArrayList<String> suggListInIterate = new ArrayList<>();
suggListInIterate.add(status);
for (String dupStatus : dupStatusList) {
suggListInIterate.add(dupStatus);
diff --git a/src/main/java/org/onap/aai/sparky/util/test/Encryptor.java b/src/main/java/org/onap/aai/sparky/util/test/Encryptor.java index 9dfc933..c24f2c2 100644 --- a/src/main/java/org/onap/aai/sparky/util/test/Encryptor.java +++ b/src/main/java/org/onap/aai/sparky/util/test/Encryptor.java @@ -37,9 +37,8 @@ public class Encryptor { /** * Instantiates a new encryptor. */ - public Encryptor() { - } - + public Encryptor() {} + /** * Decrypt value. * @@ -48,7 +47,7 @@ public class Encryptor { */ public String decryptValue(String value) { String decyptedValue = ""; - + try { decyptedValue = Password.deobfuscate(value); } catch (Exception exc) { diff --git a/src/main/java/org/onap/aai/sparky/util/test/KeystoreBuilder.java b/src/main/java/org/onap/aai/sparky/util/test/KeystoreBuilder.java index 483c464..e771066 100644 --- a/src/main/java/org/onap/aai/sparky/util/test/KeystoreBuilder.java +++ b/src/main/java/org/onap/aai/sparky/util/test/KeystoreBuilder.java @@ -96,7 +96,9 @@ public class KeystoreBuilder { this.port = port; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override @@ -258,7 +260,7 @@ public class KeystoreBuilder { private X509Certificate[] getCertificateChainForRemoteEndpoint(String hostname, int port) throws UnknownHostException, IOException { - System.out.println("Opening connection to "+hostname+":"+port+".."); + System.out.println("Opening connection to " + hostname + ":" + port + ".."); SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(hostname, port); socket.setSoTimeout(10000); @@ -431,8 +433,11 @@ public class KeystoreBuilder { throw new UnsupportedOperationException(); } - /* (non-Javadoc) - * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], + * java.lang.String) */ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) @@ -440,8 +445,11 @@ public class KeystoreBuilder { throw new UnsupportedOperationException(); } - /* (non-Javadoc) - * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], + * java.lang.String) */ @Override public void checkServerTrusted(X509Certificate[] chain, String authType) @@ -519,8 +527,7 @@ public class KeystoreBuilder { */ if (args.length != 4) { - System.out.println( - "Usage: KeyBuilder <[ip:port];*> <keystoreFileName>" + System.out.println("Usage: KeyBuilder <[ip:port];*> <keystoreFileName>" + " <keystorePassword> <dumpCertDetails> "); System.exit(1); } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/config/TierSupportUiConstants.java b/src/main/java/org/onap/aai/sparky/viewandinspect/config/TierSupportUiConstants.java index 8569712..77a34da 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/config/TierSupportUiConstants.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/config/TierSupportUiConstants.java @@ -35,7 +35,8 @@ public class TierSupportUiConstants { public static String CONFIG_HOME = System.getProperty("CONFIG_HOME") + FILESEP; public static String AJSC_HOME = System.getProperty("AJSC_HOME") + FILESEP; - public static String CONFIG_ROOT_LOCATION = AJSC_HOME + "bundleconfig" + FILESEP + "etc" + FILESEP; + public static String CONFIG_ROOT_LOCATION = + AJSC_HOME + "bundleconfig" + FILESEP + "etc" + FILESEP; public static String STATIC_CONFIG_APP_LOCATION = CONFIG_ROOT_LOCATION + "appprops" + FILESEP; public static String DYNAMIC_CONFIG_APP_LOCATION = CONFIG_HOME; @@ -51,7 +52,8 @@ public class TierSupportUiConstants { public static String USERS_FILE_LOCATION = DYNAMIC_CONFIG_APP_LOCATION + "users.config"; public static String ROLES_FILE_LOCATION = DYNAMIC_CONFIG_APP_LOCATION + "roles.config"; - public static String PORTAL_AUTHENTICATION_FILE_LOCATION = DYNAMIC_CONFIG_APP_LOCATION + "portal" + FILESEP + "portal-authentication.properties"; + public static String PORTAL_AUTHENTICATION_FILE_LOCATION = + DYNAMIC_CONFIG_APP_LOCATION + "portal" + FILESEP + "portal-authentication.properties"; public static final String ES_SUGGEST_API = "_suggest"; public static final String ES_COUNT_API = "_count"; @@ -60,14 +62,13 @@ public class TierSupportUiConstants { public static final String UI_FILTER_VIEW_NAME_PARAMETER = "viewName"; public static final String UI_FILTER_ID_LIST_PARAMETER = "filterIdList"; - public static final String ENTITY_AUTO_SUGGEST_INDEX_NAME_DEFAULT = + public static final String ENTITY_AUTO_SUGGEST_INDEX_NAME_DEFAULT = "entityautosuggestindex-localhost"; public static final String ENTITY_AUTO_SUGGEST_SETTINGS_FILE_DEFAULT = "/etc/autoSuggestSettings.json"; public static final String ENTITY_AUTO_SUGGEST_MAPPINGS_FILE_DEFAULT = "/etc/autoSuggestMappings.json"; - public static final String ENTITY_DYNAMIC_MAPPINGS_FILE_DEFAULT = - "/etc/dynamicMappings.json"; + public static final String ENTITY_DYNAMIC_MAPPINGS_FILE_DEFAULT = "/etc/dynamicMappings.json"; public static final String FILTER_LIST_FILE_DEFAULT = CONFIG_FILTERS_BASE_LOCATION + "filters" + FILESEP + "aaiui_filters.json"; public static final String FILTER_MAPPING_FILE_DEFAULT = @@ -76,18 +77,18 @@ public class TierSupportUiConstants { // JUnit testing synchronizer.properties file public static String TEST_CONFIG_FILE = System.getProperty("user.dir") + FILESEP + "bundleconfig-local" + FILESEP + "etc" + FILESEP - + "appprops" + FILESEP + "synchronizer.properties"; + + "appprops" + FILESEP + "synchronizer.properties"; // Injected Attributes public static String URI_ATTR_NAME = "uri"; public static final String URI_VERSION_REGEX_PATTERN = "aai/v[\\d]+/"; - - public static final String getConfigPath(String configFile){ + + public static final String getConfigPath(String configFile) { return AJSC_HOME + FILESEP + configFile; } - - public static final String getAggregationIndexName(String entityType){ + + public static final String getAggregationIndexName(String entityType) { return "aggregate_" + entityType + "_index"; } @@ -202,8 +203,8 @@ public class TierSupportUiConstants { public static void setCONFIG_FILTERS_BASE_LOCATION(String cONFIG_FILTERS_BASE_LOCATION) { CONFIG_FILTERS_BASE_LOCATION = cONFIG_FILTERS_BASE_LOCATION; } - - + + /** * @return the cONFIG_AUTH_LOCATION */ diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfig.java b/src/main/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfig.java index 7c09da6..77f3d97 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfig.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfig.java @@ -208,7 +208,9 @@ public class VisualizationConfig { + "makeAllNeighborsBidirectional=" + makeAllNeighborsBidirectional + "]"; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNode.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNode.java index d1a289d..d87aad8 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNode.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNode.java @@ -53,8 +53,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; */ public class ActiveInventoryNode { - private static final Logger LOG = LoggerFactory.getInstance().getLogger( - ActiveInventoryNode.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(ActiveInventoryNode.class); private static final String URIRegexPattern = "aai/v[\\d]/"; public static final int DEFAULT_INIT_NODE_DEPTH = 1000; @@ -79,13 +79,12 @@ public class ActiveInventoryNode { private boolean processedNeighbors; private boolean selfLinkPendingResolve; - + /* - * I think we shouldn't be using this crutch flags. If these things are meant - * to represent the current state of the node, then they should be legitimate - * state transitions. + * I think we shouldn't be using this crutch flags. If these things are meant to represent the + * current state of the node, then they should be legitimate state transitions. */ - + private boolean selfLinkDeterminationPending; private AtomicBoolean selfLinkProcessed; @@ -151,19 +150,19 @@ public class ActiveInventoryNode { } - + public void clearQueryParams() { queryParams.clear(); } - + public void addQueryParam(String queryParam) { - if ( queryParam!= null) { - if( !queryParams.contains(queryParam)) { + if (queryParam != null) { + if (!queryParams.contains(queryParam)) { queryParams.add(queryParam); } } } - + public void addQueryParams(Collection<String> params) { if (params != null && !params.isEmpty()) { @@ -174,7 +173,7 @@ public class ActiveInventoryNode { } } - + public List<String> getQueryParams() { return queryParams; } @@ -373,8 +372,8 @@ public class ActiveInventoryNode { boolean nodeDepthWasChanged = false; if (newDepth < nodeDepth) { - LOG.info(AaiUiMsgs.ACTIVE_INV_NODE_CHANGE_DEPTH, nodeId, - String.valueOf(this.nodeDepth), String.valueOf(newDepth)); + LOG.info(AaiUiMsgs.ACTIVE_INV_NODE_CHANGE_DEPTH, nodeId, String.valueOf(this.nodeDepth), + String.valueOf(newDepth)); this.nodeDepth = newDepth; nodeDepthWasChanged = true; } @@ -403,13 +402,15 @@ public class ActiveInventoryNode { */ public void changeState(NodeProcessingState newState, NodeProcessingAction action) { /* - * NodeId may be null depending on the current node life-cycle state + * NodeId may be null depending on the current node life-cycle state */ - + if (getNodeId() != null) { - LOG.info(AaiUiMsgs.ACTIVE_INV_NODE_CHANGE_STATE, state.toString(), newState.toString(), action.toString()); + LOG.info(AaiUiMsgs.ACTIVE_INV_NODE_CHANGE_STATE, state.toString(), newState.toString(), + action.toString()); } else { - LOG.info(AaiUiMsgs.ACTIVE_INV_NODE_CHANGE_STATE_NO_NODE_ID, state.toString(), newState.toString(), action.toString()); + LOG.info(AaiUiMsgs.ACTIVE_INV_NODE_CHANGE_STATE_NO_NODE_ID, state.toString(), + newState.toString(), action.toString()); } this.state = newState; } @@ -716,7 +717,7 @@ public class ActiveInventoryNode { public String dumpNodeTree(boolean showProperties) { return dumpNodeTree(0, showProperties); } - + /** * Dump node tree. * diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/GraphMeta.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/GraphMeta.java index 4c6f1f4..6475fac 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/GraphMeta.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/GraphMeta.java @@ -127,7 +127,9 @@ public class GraphMeta { entitySummary.pegCounter(counterName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessage.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessage.java index 7db12d3..93d5cc9 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessage.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessage.java @@ -57,7 +57,9 @@ public class InlineMessage { this.message = message; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/JsonNodeLink.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/JsonNodeLink.java index 6e1a078..411d728 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/JsonNodeLink.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/JsonNodeLink.java @@ -62,7 +62,9 @@ public class JsonNodeLink { this.target = target; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/NodeProcessingTransaction.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/NodeProcessingTransaction.java index 971a68e..ca55f09 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/NodeProcessingTransaction.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/NodeProcessingTransaction.java @@ -46,15 +46,15 @@ public class NodeProcessingTransaction { public void setRequestParameters(String requestParameters) { this.requestParameters = requestParameters; } - + public String getSelfLink() { - if (processingNode == null) { - return null; - } + if (processingNode == null) { + return null; + } + + return processingNode.getSelfLink(); + } - return processingNode.getSelfLink(); - } - public String getSelfLinkWithModifiers() { if (processingNode == null) { return null; @@ -93,7 +93,9 @@ public class NodeProcessingTransaction { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/QueryParams.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/QueryParams.java index 1a1f24c..43edeaa 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/QueryParams.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/QueryParams.java @@ -36,7 +36,7 @@ public class QueryParams { public QueryParams() { } - + public String getSearchTargetPrimaryKeyValues() { return searchTargetPrimaryKeyValues; } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToProperty.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToProperty.java index 7ce9de0..0e89608 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToProperty.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToProperty.java @@ -49,7 +49,9 @@ public class RelatedToProperty { this.propertyValue = propertyValue; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/Relationship.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/Relationship.java index 2ed8e51..7e5519c 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/Relationship.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/Relationship.java @@ -74,7 +74,9 @@ public class Relationship { this.relatedToProperty = relatedToProperty; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipData.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipData.java index d2400a9..f8e1ed3 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipData.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipData.java @@ -49,7 +49,9 @@ public class RelationshipData { this.relationshipValue = relationshipValue; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDirectionality.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDirectionality.java index 6ceede3..5104072 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDirectionality.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDirectionality.java @@ -25,12 +25,10 @@ package org.onap.aai.sparky.viewandinspect.entity; /** * This enumeration is intended to be used to help us discriminate neighbor relationships for the * purpose of visualization and conceptualization to model in/out relationships between - * ActiveInventoryNodes. - * Possible visualization behaviors could be the following: - IN ( draw a line with 1 arrow ) - OUT - * ( draw a line with 1 arrow ) - BOTH ( draw a line with 2 arrows, or 2 lines with 1 arrow each ) - - * UNKNOWN ( draw a line with no arrows ) - * The UNKNOWN case is what we have at the moment where we have a collection neighbors with no - * knowledge of relationship directionality. + * ActiveInventoryNodes. Possible visualization behaviors could be the following: - IN ( draw a line + * with 1 arrow ) - OUT ( draw a line with 1 arrow ) - BOTH ( draw a line with 2 arrows, or 2 lines + * with 1 arrow each ) - UNKNOWN ( draw a line with no arrows ) The UNKNOWN case is what we have at + * the moment where we have a collection neighbors with no knowledge of relationship directionality. * * @author davea * diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipList.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipList.java index 7ab8f91..8dd61d4 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipList.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipList.java @@ -56,7 +56,9 @@ public class RelationshipList { this.relationship = relationship; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponse.java b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponse.java index 44c828e..7daf471 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponse.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponse.java @@ -31,7 +31,7 @@ import org.onap.aai.sparky.suggestivesearch.SuggestionEntity; * The Class SearchResponse. */ public class SearchResponse { - + private long processingTimeInMs; private int totalFound; @@ -53,11 +53,11 @@ public class SearchResponse { public void setProcessingTimeInMs(long processingTimeInMs) { this.processingTimeInMs = processingTimeInMs; } - + public int getTotalFound() { return totalFound; } - + public void setTotalFound(int totalFound) { this.totalFound = totalFound; } @@ -69,18 +69,18 @@ public class SearchResponse { public void setSuggestions(List<SuggestionEntity> suggestions) { this.suggestions = suggestions; } + /** * Adds the entity entry. * * @param suggestionEntry that will be converted to JSON */ - public void addSuggestion(SuggestionEntity suggestionEntity){ + public void addSuggestion(SuggestionEntity suggestionEntity) { suggestions.add(suggestionEntity); } - + /** - * Increments the total number of hits for this SearchResponse by - * the value passed in. + * Increments the total number of hits for this SearchResponse by the value passed in. * * @param additionalCount - Count to increment the total found */ diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/enumeration/NodeProcessingAction.java b/src/main/java/org/onap/aai/sparky/viewandinspect/enumeration/NodeProcessingAction.java index c85b8d4..2550ed7 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/enumeration/NodeProcessingAction.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/enumeration/NodeProcessingAction.java @@ -26,8 +26,5 @@ package org.onap.aai.sparky.viewandinspect.enumeration; * The Enum NodeProcessingAction. */ public enum NodeProcessingAction { - SELF_LINK_SET, NEW_NODE_PROCESSED, SELF_LINK_RESOLVE_ERROR, SELF_LINK_DETERMINATION_ERROR, - SELF_LINK_RESOLVE_OK, SELF_LINK_RESPONSE_PARSE_ERROR, SELF_LINK_RESPONSE_PARSE_OK, - NEIGHBORS_PROCESSED_ERROR, NEIGHBORS_PROCESSED_OK, COMPLEX_ATTRIBUTE_GROUP_PARSE_ERROR, - COMPLEX_ATTRIBUTE_GROUP_PARSE_OK, NODE_IDENTITY_ERROR, UNEXPECTED_STATE_TRANSITION + SELF_LINK_SET, NEW_NODE_PROCESSED, SELF_LINK_RESOLVE_ERROR, SELF_LINK_DETERMINATION_ERROR, SELF_LINK_RESOLVE_OK, SELF_LINK_RESPONSE_PARSE_ERROR, SELF_LINK_RESPONSE_PARSE_OK, NEIGHBORS_PROCESSED_ERROR, NEIGHBORS_PROCESSED_OK, COMPLEX_ATTRIBUTE_GROUP_PARSE_ERROR, COMPLEX_ATTRIBUTE_GROUP_PARSE_OK, NODE_IDENTITY_ERROR, UNEXPECTED_STATE_TRANSITION } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/services/SearchServiceWrapper.java b/src/main/java/org/onap/aai/sparky/viewandinspect/services/SearchServiceWrapper.java index 6db9c05..ebce18e 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/services/SearchServiceWrapper.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/services/SearchServiceWrapper.java @@ -67,7 +67,8 @@ public class SearchServiceWrapper { private static final long serialVersionUID = 1L; - private static final Logger LOG = LoggerFactory.getInstance().getLogger(SearchServiceWrapper.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(SearchServiceWrapper.class); private SearchServiceConfig sasConfig = null; private SuggestionConfig suggestionConfig = null; @@ -85,9 +86,9 @@ public class SearchServiceWrapper { private static final String VALUE_ANYKEY = "anyKey"; private static final String VALUE_QUERY = "query"; - + private static final String KEY_HASH_ID = "hashId"; - private static final String KEY_GROUP_BY = "groupby"; + private static final String KEY_GROUP_BY = "groupby"; private static final String KEY_SEARCH_RESULT = "searchResult"; private static final String KEY_HITS = "hits"; private static final String KEY_PAYLOAD = "payload"; @@ -97,24 +98,24 @@ public class SearchServiceWrapper { private static final String KEY_SEARCH_TAGS = "searchTags"; private static final String KEY_LINK = "link"; private static final String KEY_ENTITY_TYPE = "entityType"; - + private static final String VI_SUGGESTION_ROUTE = "viewInspect"; // TODO -> Read route from // suggestive-search.properties // instead of hard coding - + private static final String VIUI_SEARCH_TEMPLATE = "{ " + "\"results-start\": 0," + "\"results-size\": %d," + "\"queries\": [{" + "\"must\": {" + "\"match\": {" + "\"field\": \"entityType searchTags crossEntityReferenceValues\"," + "\"value\": \"%s\"," + "\"operator\": \"and\", " - + "\"analyzer\": \"whitespace_analyzer\"" + "}" + "}" + "}]" + "}"; - + + "\"analyzer\": \"whitespace_analyzer\"" + "}" + "}" + "}]" + "}"; + /** * Instantiates a new search service wrapper */ public SearchServiceWrapper() { this.mapper = new ObjectMapper(); vnfSearch = new VnfSearchService(); - + try { if (sasConfig == null) { sasConfig = SearchServiceConfig.getConfig(); @@ -134,10 +135,11 @@ public class SearchServiceWrapper { if (OxmModelLoader.getInstance().getSearchableEntityDescriptors().isEmpty()) { LOG.error(AaiUiMsgs.ENTITY_NOT_FOUND_IN_OXM, "searchable entity"); } - } - } catch (Exception exc) { + } + } catch (Exception exc) { new ServletException( - "Caught an exception while getting an instance of servlet configuration from SearchServlet.", exc); + "Caught an exception while getting an instance of servlet configuration from SearchServlet.", + exc); } } @@ -230,7 +232,7 @@ public class SearchServiceWrapper { HttpServletResponse response) throws Exception { JSONObject parameters = getRequestParamsFromHeader(request); String hashId = null; - if (parameters.has(KEY_HASH_ID)){ + if (parameters.has(KEY_HASH_ID)) { hashId = parameters.get(KEY_HASH_ID).toString(); } else { vnfSearch.setZeroCountResponse(response); @@ -245,9 +247,9 @@ public class SearchServiceWrapper { } else { vnfSearch.setZeroCountResponse(response); LOG.error(AaiUiMsgs.ERROR_INVALID_HASH, hashId); - } + } } - + protected Map<String, String> getPayloadParams(String parameters) { Map<String, String> payloadParams = new HashMap<String, String>(); try { @@ -264,7 +266,8 @@ public class SearchServiceWrapper { return payloadParams; } - protected HashQueryResponse getResponseForQueryByHash(String hashId, HttpServletResponse response){ + protected HashQueryResponse getResponseForQueryByHash(String hashId, + HttpServletResponse response) { return vnfSearch.getJSONPayloadFromHash(hashId); } @@ -272,7 +275,7 @@ public class SearchServiceWrapper { throws Exception { JSONObject parameters = getRequestParamsFromHeader(request); String hashId = null; - if (parameters.has(KEY_HASH_ID)){ + if (parameters.has(KEY_HASH_ID)) { hashId = parameters.get(KEY_HASH_ID).toString(); } else { vnfSearch.setZeroCountResponse(response); @@ -283,14 +286,14 @@ public class SearchServiceWrapper { Map<String, String> hashQueryResponsePayloadParams = new HashMap<String, String>(); if (hashQueryResponse.getJsonPayload() != null) { hashQueryResponsePayloadParams = getPayloadParams(hashQueryResponse.getJsonPayload()); - if (parameters.has(KEY_GROUP_BY)){ + if (parameters.has(KEY_GROUP_BY)) { String groupByKey = parameters.getString(KEY_GROUP_BY); vnfSearch.getSummaryByEntityType(response, hashQueryResponsePayloadParams, groupByKey); } } else { LOG.error(AaiUiMsgs.ERROR_INVALID_HASH, hashId); vnfSearch.setEmptyAggResponse(response); - } + } } /** @@ -516,7 +519,8 @@ public class SearchServiceWrapper { } } } else { - String errorMessage = "Search tags length did not match search tag ID length for entity type " + entityType; + String errorMessage = + "Search tags length did not match search tag ID length for entity type " + entityType; LOG.error(AaiUiMsgs.ENTITY_SYNC_SEARCH_TAG_ANNOTATION_FAILED, errorMessage); } @@ -556,7 +560,8 @@ public class SearchServiceWrapper { } Collection<String> stopWords = suggestionConfig.getStopWords(); - ArrayList<String> queryTerms = new ArrayList<String>(Arrays.asList(queryStr.toLowerCase().split(" "))); + ArrayList<String> queryTerms = + new ArrayList<String>(Arrays.asList(queryStr.toLowerCase().split(" "))); queryTerms.removeAll(stopWords); @@ -675,12 +680,12 @@ public class SearchServiceWrapper { String api = null; try { - + // set default response response.setStatus(200); if (request.getRequestURI().contains(QUERY_SEARCH)) { - api = QUERY_SEARCH; + api = QUERY_SEARCH; handleQuerySearch(request, response); return; } else if (request.getRequestURI().contains(SUMMARY_BY_ENTITY_TYPE_COUNT_API)) { @@ -700,12 +705,12 @@ public class SearchServiceWrapper { PrintWriter out = response.getWriter(); out.println(generateJsonErrorResponse(errorMessage)); out.close(); - - + + } - } catch (JSONException je){ - handleSearchServletErrors("Caught an exception while parsing json in processing for " + api, je, - response); + } catch (JSONException je) { + handleSearchServletErrors("Caught an exception while parsing json in processing for " + api, + je, response); } catch (Exception e1) { handleSearchServletErrors("Caught an exception while communicating with elasticsearch", e1, response); @@ -969,7 +974,7 @@ public class SearchServiceWrapper { public static String getViuiSearchTemplate() { return VIUI_SEARCH_TEMPLATE; } - - -}
\ No newline at end of file + + +} diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContext.java b/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContext.java index a803283..e3f469f 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContext.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContext.java @@ -66,7 +66,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; -/** +/** * The Class SelfLinkNodeCollector. */ public class VisualizationContext { @@ -76,8 +76,8 @@ public class VisualizationContext { private static final String NODES_ONLY_MODIFIER = "?nodes-only"; private static final String SERVICE_INSTANCE = "service-instance"; - private static final Logger LOG = LoggerFactory.getInstance().getLogger( - VisualizationContext.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(VisualizationContext.class); private final ActiveInventoryDataProvider aaiProvider; private int maxSelfLinkTraversalDepth; @@ -117,13 +117,13 @@ public class VisualizationContext { */ public VisualizationContext(long contextId, ActiveInventoryDataProvider aaiDataProvider, ExecutorService aaiExecutorService, OxmModelLoader loader) throws Exception { - + this.contextId = contextId; this.contextIdStr = "[Context-Id=" + contextId + "]"; this.aaiProvider = aaiDataProvider; this.aaiExecutorService = aaiExecutorService; this.loader = loader; - + this.nodeCache = new ConcurrentHashMap<String, ActiveInventoryNode>(); this.numLinksDiscovered = new AtomicInteger(0); this.totalLinksRetrieved = new AtomicInteger(0); @@ -142,7 +142,7 @@ public class VisualizationContext { mapper.setSerializationInclusion(Include.NON_EMPTY); mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.KebabCaseStrategy()); } - + public long getContextId() { return contextId; } @@ -216,7 +216,7 @@ public class VisualizationContext { return queryParams; } - + /** * Decode complex attribute group. * @@ -252,8 +252,8 @@ public class VisualizationContext { entity = entityCollection.next(); if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "decodeComplexAttributeGroup()," - + " entity = " + entity.toString()); + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + "decodeComplexAttributeGroup()," + " entity = " + entity.toString()); } /** @@ -280,13 +280,13 @@ public class VisualizationContext { newNode.setSelfLinkProcessed(true); newNode.changeState(NodeProcessingState.SELF_LINK_RESPONSE_UNPROCESSED, NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_OK); - + /* * copy parent query params into new child */ - + if (SERVICE_INSTANCE.equals(entityType)) { - + /* * 1707 AAI has an issue being tracked with AAI-8932 where the generic-query cannot be * resolved if all the service-instance path keys are provided. The query only works @@ -294,14 +294,14 @@ public class VisualizationContext { * A fix is being worked on for 1707, and when it becomes available we can revert this * small change. */ - + newNode.clearQueryParams(); - + } else { /* - * For all other entity-types we want to copy the parent query parameters into the new node - * query parameters. + * For all other entity-types we want to copy the parent query parameters into the new + * node query parameters. */ for (String queryParam : ain.getQueryParams()) { @@ -309,15 +309,17 @@ public class VisualizationContext { } } - - + + if (!addComplexGroupToNode(newNode, entity)) { - LOG.error(AaiUiMsgs.ATTRIBUTE_GROUP_FAILURE, "Failed to add child to parent for child = " + entity.toString()); + LOG.error(AaiUiMsgs.ATTRIBUTE_GROUP_FAILURE, + "Failed to add child to parent for child = " + entity.toString()); } if (!addNodeQueryParams(newNode)) { - LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE_NODE_ID, "Error determining node id and key for node = " + newNode.dumpNodeTree(true) - + " skipping relationship processing"); + LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE_NODE_ID, + "Error determining node id and key for node = " + newNode.dumpNodeTree(true) + + " skipping relationship processing"); newNode.changeState(NodeProcessingState.ERROR, NodeProcessingAction.NODE_IDENTITY_ERROR); return false; @@ -327,7 +329,7 @@ public class VisualizationContext { NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_OK); } - + /* * Order matters for the query params. We need to set the parent ones before the child @@ -388,7 +390,8 @@ public class VisualizationContext { genericQueryResult = NodeUtils.convertJsonStrToJsonNode(nodeTxn.getOpResult().getResult()); } catch (Exception exc) { - LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getMessage()); + LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), + exc.getMessage()); } NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", @@ -398,8 +401,9 @@ public class VisualizationContext { if (entityLinks.size() != 1) { - LOG.error(AaiUiMsgs.SELF_LINK_DETERMINATION_FAILED_UNEXPECTED_LINKS, String.valueOf(entityLinks.size())); - + LOG.error(AaiUiMsgs.SELF_LINK_DETERMINATION_FAILED_UNEXPECTED_LINKS, + String.valueOf(entityLinks.size())); + } else { selfLink = ((JsonNode) entityLinks.toArray()[0]).asText(); selfLink = ActiveInventoryConfig.extractResourcePath(selfLink); @@ -411,7 +415,7 @@ public class VisualizationContext { if (uri != null) { newChildNode.addProperty(TierSupportUiConstants.URI_ATTR_NAME, uri); } - + ActiveInventoryNode parent = nodeCache.get(txn.getParentNodeId()); if (parent != null) { @@ -424,14 +428,15 @@ public class VisualizationContext { newChildNode.changeState(NodeProcessingState.NEIGHBORS_UNPROCESSED, NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_OK); - + nodeCache.putIfAbsent(newChildNode.getNodeId(), newChildNode); - + } } else { LOG.error(AaiUiMsgs.SELF_LINK_RETRIEVAL_FAILED, txn.getQueryString(), - String.valueOf(nodeTxn.getOpResult().getResultCode()), nodeTxn.getOpResult().getResult()); + String.valueOf(nodeTxn.getOpResult().getResultCode()), + nodeTxn.getOpResult().getResult()); newChildNode.setSelflinkRetrievalFailure(true); newChildNode.setSelfLinkProcessed(true); newChildNode.setSelfLinkPendingResolve(false); @@ -455,8 +460,8 @@ public class VisualizationContext { } } catch (Exception exc) { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Exception caught while" - + " decoding complex attribute group - " + exc.getMessage()); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, + "Exception caught while" + " decoding complex attribute group - " + exc.getMessage()); } return false; @@ -471,16 +476,16 @@ public class VisualizationContext { private void processSelfLinkResponse(String nodeId) { if (nodeId == null) { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Cannot process self link" - + " response because nodeId is null"); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, + "Cannot process self link" + " response because nodeId is null"); return; } ActiveInventoryNode ain = nodeCache.get(nodeId); if (ain == null) { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Cannot process self link response" - + " because can't find node for id = " + nodeId); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, + "Cannot process self link response" + " because can't find node for id = " + nodeId); return; } @@ -497,8 +502,8 @@ public class VisualizationContext { } if (jsonNode == null) { - LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, "Failed to parse json node str." - + " Parse resulted a null value."); + LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, + "Failed to parse json node str." + " Parse resulted a null value."); ain.changeState(NodeProcessingState.ERROR, NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_ERROR); return; @@ -582,39 +587,38 @@ public class VisualizationContext { /* * We need a special behavior for intermediate entities from the REST model * - * Tenants are not top level entities, and when we want to visualization - * their children, we need to construct keys that include the parent entity query - * keys, the current entity type keys, and the child keys. We'll always have the - * current entity and children, but never the parent entity in the current (1707) REST - * data model. + * Tenants are not top level entities, and when we want to visualization their children, we need + * to construct keys that include the parent entity query keys, the current entity type keys, + * and the child keys. We'll always have the current entity and children, but never the parent + * entity in the current (1707) REST data model. * * We have two possible solutions: * - * 1) Try to use the custom-query approach to learn about the entity keys - * - this could be done, but it could be very expensive for large objects. When we do the first - * query to get a tenant, it will list all the in and out edges related to this entity, - * there is presently no way to filter this. But the approach could be made to work and it would be - * somewhat data-model driven, other than the fact that we have to first realize that the entity - * that is being searched for is not top-level entity. Once we have globally unique ids for resources - * this logic will not be needed and everything will be simpler. The only reason we are in this logic - * at all is to be able to calculate a url for the child entities so we can hash it to generate - * a globally unique id that can be safely used for the node. - * - * *2* Extract the keys from the pathed self-link. - * This is a bad solution and I don't like it but it will be fast for all resource types, as the - * information is already encoded in the URI. When we get to a point where we switch to a better - * globally unique entity identity model, then a lot of the code being used to calculate an entity url - * to in-turn generate a deterministic globally unique id will disappear. - * + * 1) Try to use the custom-query approach to learn about the entity keys - this could be done, + * but it could be very expensive for large objects. When we do the first query to get a tenant, + * it will list all the in and out edges related to this entity, there is presently no way to + * filter this. But the approach could be made to work and it would be somewhat data-model + * driven, other than the fact that we have to first realize that the entity that is being + * searched for is not top-level entity. Once we have globally unique ids for resources this + * logic will not be needed and everything will be simpler. The only reason we are in this logic + * at all is to be able to calculate a url for the child entities so we can hash it to generate + * a globally unique id that can be safely used for the node. + * + * *2* Extract the keys from the pathed self-link. This is a bad solution and I don't like it + * but it will be fast for all resource types, as the information is already encoded in the URI. + * When we get to a point where we switch to a better globally unique entity identity model, + * then a lot of the code being used to calculate an entity url to in-turn generate a + * deterministic globally unique id will disappear. + * * * right now we have the following: * * - cloud-regions/cloud-region/{cloud-region-id}/{cloud-owner-id}/tenants/tenant/{tenant-id} - * + * */ /* - * For all entity types use the self-link extraction method to be consistent. Once we have a + * For all entity types use the self-link extraction method to be consistent. Once we have a * globally unique identity mechanism for entities, this logic can be revisited. */ ain.clearQueryParams(); @@ -633,8 +637,8 @@ public class VisualizationContext { private void performSelfLinkResolve(String nodeId) { if (nodeId == null) { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Resolve of self-link" - + " has been skipped because provided nodeId is null"); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, + "Resolve of self-link" + " has been skipped because provided nodeId is null"); return; } @@ -653,7 +657,7 @@ public class VisualizationContext { // kick off async self-link resolution if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "About to process node in SELF_LINK_UNPROCESSED State, link = " + ain.getSelfLink()); } @@ -674,8 +678,7 @@ public class VisualizationContext { txn.setProcessingNode(ain); txn.setRequestParameters(depthModifier); aaiWorkOnHand.incrementAndGet(); - supplyAsync( - new PerformNodeSelfLinkProcessingTask(txn, depthModifier, aaiProvider, aaiConfig), + supplyAsync(new PerformNodeSelfLinkProcessingTask(txn, depthModifier, aaiProvider, aaiConfig), aaiExecutorService).whenComplete((nodeTxn, error) -> { aaiWorkOnHand.decrementAndGet(); if (error != null) { @@ -722,10 +725,10 @@ public class VisualizationContext { nodeTxn.getProcessingNode().setSelfLinkPendingResolve(false); } else { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Self Link retrieval for link," - + txn.getSelfLinkWithModifiers() + ", failed with error code," - + nodeTxn.getOpResult().getResultCode() + ", and message," - + nodeTxn.getOpResult().getResult()); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, + "Self Link retrieval for link," + txn.getSelfLinkWithModifiers() + + ", failed with error code," + nodeTxn.getOpResult().getResultCode() + + ", and message," + nodeTxn.getOpResult().getResult()); nodeTxn.getProcessingNode().setSelflinkRetrievalFailure(true); nodeTxn.getProcessingNode().setSelfLinkProcessed(true); @@ -751,10 +754,10 @@ public class VisualizationContext { * @param nodeId the node id */ private void processNeighbors(String nodeId) { - + if (nodeId == null) { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESS_NEIGHBORS_ERROR, "Failed to process" - + " neighbors because nodeId is null."); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESS_NEIGHBORS_ERROR, + "Failed to process" + " neighbors because nodeId is null."); return; } @@ -786,7 +789,7 @@ public class VisualizationContext { } else { ain.changeState(NodeProcessingState.ERROR, NodeProcessingAction.NEIGHBORS_PROCESSED_ERROR); } - + /* * If neighbors fail to process, there is already a call to change the state within the @@ -834,8 +837,7 @@ public class VisualizationContext { for (ActiveInventoryNode cacheNode : nodeCache.values()) { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, - "processCurrentNodeState(), nid = " + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "processCurrentNodeState(), nid = " + cacheNode.getNodeId() + " , nodeDepth = " + cacheNode.getNodeDepth()); } @@ -868,19 +870,19 @@ public class VisualizationContext { * node is identified. Then the evaluative depth calculations should re-balance the graph * around the root node. */ - + if (!rootNodeDiscovered || cacheNode.getNodeDepth() < VisualizationConfig.getConfig() .getMaxSelfLinkTraversalDepth()) { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "SLNC::processCurrentNodeState() -- Node at max depth," - + " halting processing at current state = -- " - + cacheNode.getState() + " nodeId = " + cacheNode.getNodeId()); + + " halting processing at current state = -- " + cacheNode.getState() + + " nodeId = " + cacheNode.getNodeId()); } - - + + processNeighbors(cacheNode.getNodeId()); } @@ -940,9 +942,9 @@ public class VisualizationContext { } } catch (Exception exc) { - LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, "Failed to parse" - + " relationship-list attribute. Parse resulted in error, " - + exc.getLocalizedMessage()); + LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, + "Failed to parse" + " relationship-list attribute. Parse resulted in error, " + + exc.getLocalizedMessage()); targetNode.changeState(NodeProcessingState.ERROR, NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_ERROR); return false; @@ -954,8 +956,7 @@ public class VisualizationContext { } else if (fieldValue.isArray()) { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, - "Unexpected array type with a key = " + fieldName); + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Unexpected array type with a key = " + fieldName); } } else if (fieldValue.isValueNode()) { if (loader.getEntityDescriptor(field.getKey()) == null) { @@ -970,19 +971,19 @@ public class VisualizationContext { } else if (attributeGroup.isArray()) { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Unexpected array type for attributeGroup = " + attributeGroup); } } else if (attributeGroup.isValueNode()) { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Unexpected value type for attributeGroup = " + attributeGroup); } } - + return true; } - + public int getNumSuccessfulLinkResolveFromCache() { return numSuccessfulLinkResolveFromCache.get(); } @@ -1038,9 +1039,8 @@ public class VisualizationContext { // this should be a fatal error because unless we can // successfully retrieve all the expected keys we'll end up // with a garbage node - LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract" - + " keyName, " + entityType + "." + pkeyNames.get(0) - + ", from relationship data, " + r.toString()); + LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract" + " keyName, " + entityType + + "." + pkeyNames.get(0) + ", from relationship data, " + r.toString()); return null; } @@ -1053,9 +1053,8 @@ public class VisualizationContext { // this should be a fatal error because unless we can // successfully retrieve all the expected keys we'll end up // with a garbage node - LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: failed to extract keyName, " - + entityType + "." + pkeyNames.get(i) - + ", from relationship data, " + r.toString()); + LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: failed to extract keyName, " + entityType + + "." + pkeyNames.get(i) + ", from relationship data, " + r.toString()); return null; } } @@ -1120,8 +1119,8 @@ public class VisualizationContext { // this should be a fatal error because unless we can // successfully retrieve all the expected keys we'll end up // with a garbage node - LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract keyName, " - + pkeyNames.get(0) + ", from entity properties"); + LOG.error(AaiUiMsgs.EXTRACTION_ERROR, + "ERROR: Failed to extract keyName, " + pkeyNames.get(0) + ", from entity properties"); return false; } @@ -1134,19 +1133,21 @@ public class VisualizationContext { // this should be a fatal error because unless we can // successfully retrieve all the expected keys we'll end up // with a garbage node - LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract keyName, " - + pkeyNames.get(i) + ", from entity properties"); + LOG.error(AaiUiMsgs.EXTRACTION_ERROR, + "ERROR: Failed to extract keyName, " + pkeyNames.get(i) + ", from entity properties"); return false; } } - /*final String nodeId = NodeUtils.generateUniqueShaDigest(ain.getEntityType(), - NodeUtils.concatArray(pkeyNames, "/"), sb.toString());*/ + /* + * final String nodeId = NodeUtils.generateUniqueShaDigest(ain.getEntityType(), + * NodeUtils.concatArray(pkeyNames, "/"), sb.toString()); + */ - //ain.setNodeId(nodeId); + // ain.setNodeId(nodeId); ain.setPrimaryKeyName(NodeUtils.concatArray(pkeyNames, "/")); ain.setPrimaryKeyValue(sb.toString()); - + if (ain.getEntityType() != null && ain.getPrimaryKeyName() != null && ain.getPrimaryKeyValue() != null) { ain.addQueryParam( @@ -1191,7 +1192,7 @@ public class VisualizationContext { for (Relationship r : relationshipArray) { resourcePath = ActiveInventoryConfig.extractResourcePath(r.getRelatedLink()); - + String nodeId = NodeUtils.generateUniqueShaDigest(resourcePath); if (nodeId == null) { @@ -1274,14 +1275,14 @@ public class VisualizationContext { ActiveInventoryNode cachedNode = nodeCache.get(nodeId); if (cachedNode == null) { - LOG.error(AaiUiMsgs.FAILED_TO_PROCESS_INITIAL_STATE, "Node cannot be" - + " found for nodeId, " + nodeId); + LOG.error(AaiUiMsgs.FAILED_TO_PROCESS_INITIAL_STATE, + "Node cannot be" + " found for nodeId, " + nodeId); return; } if (cachedNode.getSelfLink() == null) { - if (cachedNode.getNodeId() == null ) { + if (cachedNode.getNodeId() == null) { /* * if the self link is null at the INIT state, which could be valid if this node is a @@ -1323,7 +1324,8 @@ public class VisualizationContext { * @param skeletonNode the skeleton node * @param queryParams the query params */ - private void processSearchableEntity(SearchableEntity searchTargetEntity, QueryParams queryParams) { + private void processSearchableEntity(SearchableEntity searchTargetEntity, + QueryParams queryParams) { if (searchTargetEntity == null) { return; @@ -1341,11 +1343,11 @@ public class VisualizationContext { newNode.setEntityType(searchTargetEntity.getEntityType()); newNode.setPrimaryKeyName(getEntityTypePrimaryKeyName(searchTargetEntity.getEntityType())); newNode.setPrimaryKeyValue(searchTargetEntity.getEntityPrimaryKeyValue()); - + if (newNode.getEntityType() != null && newNode.getPrimaryKeyName() != null && newNode.getPrimaryKeyValue() != null) { - newNode.addQueryParam( - newNode.getEntityType() + "." + newNode.getPrimaryKeyName() + ":" + newNode.getPrimaryKeyValue()); + newNode.addQueryParam(newNode.getEntityType() + "." + newNode.getPrimaryKeyName() + ":" + + newNode.getPrimaryKeyValue()); } /* * This code may need some explanation. In any graph there will be a single root node. The root @@ -1437,8 +1439,8 @@ public class VisualizationContext { try { if (searchtargetEntity == null) { - LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, contextIdStr + " - Failed to" - + " processSelfLinks, searchtargetEntity is null"); + LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, + contextIdStr + " - Failed to" + " processSelfLinks, searchtargetEntity is null"); return; } @@ -1457,15 +1459,15 @@ public class VisualizationContext { long guardTimeInMs = 0; boolean foundRootNode = false; - + /* - * TODO: Put a count-down-latch in place of the while loop, but if we do that then - * we'll need to decouple the visualization processing from the main thread so it can continue to process while - * the main thread is waiting on for count-down-latch gate to open. This may also be easier once we move to the - * VisualizationService + VisualizationContext ideas. + * TODO: Put a count-down-latch in place of the while loop, but if we do that then we'll need + * to decouple the visualization processing from the main thread so it can continue to process + * while the main thread is waiting on for count-down-latch gate to open. This may also be + * easier once we move to the VisualizationService + VisualizationContext ideas. */ - - + + while (hasOutstandingWork || !outstandingWorkGuardTimerFired) { if (!foundRootNode) { @@ -1597,17 +1599,17 @@ public class VisualizationContext { if (LOG.isDebugEnabled()) { if (numAttempts > 0) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Evaluate node depths completed in " + numAttempts + " attempts"); } else { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Evaluate node depths completed in 0 attempts because all nodes at correct depth"); } } } - - + + /** * Gets the entity type primary key name. * @@ -1615,28 +1617,28 @@ public class VisualizationContext { * @return the entity type primary key name */ - + private String getEntityTypePrimaryKeyName(String entityType) { if (entityType == null) { - LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, "node primary key" - + " name because entity type is null"); + LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, + "node primary key" + " name because entity type is null"); return null; } OxmEntityDescriptor descriptor = loader.getEntityDescriptor(entityType); if (descriptor == null) { - LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, "oxm entity" - + " descriptor for entityType = " + entityType); + LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, + "oxm entity" + " descriptor for entityType = " + entityType); return null; } List<String> pkeyNames = descriptor.getPrimaryKeyAttributeName(); if (pkeyNames == null || pkeyNames.size() == 0) { - LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, "node primary" - + " key because descriptor primary key names is empty"); + LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, + "node primary" + " key because descriptor primary key names is empty"); return null; } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationService.java b/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationService.java index 924d026..0a9797f 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationService.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationService.java @@ -62,10 +62,10 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class VisualizationService { - + private static final Logger LOG = LoggerFactory.getInstance().getLogger(VisualizationService.class); - + private OxmModelLoader loader; private ObjectMapper mapper = new ObjectMapper(); @@ -74,13 +74,13 @@ public class VisualizationService { private final ElasticSearchDataProvider esProvider; private final ElasticSearchConfig esConfig; private final ExecutorService aaiExecutorService; - + private ConcurrentHashMap<Long, VisualizationContext> contextMap; private final SecureRandom secureRandom; - + private ActiveInventoryConfig aaiConfig; private VisualizationConfig visualizationConfig; - + public VisualizationService(OxmModelLoader loader) throws Exception { this.loader = loader; @@ -106,17 +106,17 @@ public class VisualizationService { RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(esClientBuilder); this.esConfig = ElasticSearchConfig.getConfig(); this.esProvider = new ElasticSearchAdapter(nonCachingRestProvider, this.esConfig); - + this.mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - + this.contextMap = new ConcurrentHashMap<Long, VisualizationContext>(); this.visualizationConfig = VisualizationConfig.getConfig(); this.aaiConfig = ActiveInventoryConfig.getConfig(); this.aaiExecutorService = NodeUtils.createNamedExecutor("SLNC-WORKER", aaiConfig.getAaiRestConfig().getNumResolverWorkers(), LOG); } - + public OxmModelLoader getLoader() { return loader; } @@ -124,7 +124,7 @@ public class VisualizationService { public void setLoader(OxmModelLoader loader) { this.loader = loader; } - + /** * Analyze query request body. * @@ -153,7 +153,7 @@ public class VisualizationService { return queryBody; } - + /** * Log optime. * @@ -164,13 +164,14 @@ public class VisualizationService { LOG.info(AaiUiMsgs.OPERATION_TIME, method, String.valueOf(System.currentTimeMillis() - opStartTimeInMs)); } - - private SearchableEntity extractSearchableEntityFromElasticEntity(OperationResult operationResult) { + + private SearchableEntity extractSearchableEntityFromElasticEntity( + OperationResult operationResult) { if (operationResult == null || !operationResult.wasSuccessful()) { // error, return empty collection return null; } - + SearchableEntity sourceEntity = null; if (operationResult.wasSuccessful()) { @@ -182,14 +183,16 @@ public class VisualizationService { if (sourceField != null) { sourceEntity = new SearchableEntity(); - - String entityType = NodeUtils.extractFieldValueFromObject(sourceField, "entityType"); - sourceEntity.setEntityType(entityType); - String entityPrimaryKeyValue = NodeUtils.extractFieldValueFromObject(sourceField, "entityPrimaryKeyValue"); + + String entityType = NodeUtils.extractFieldValueFromObject(sourceField, "entityType"); + sourceEntity.setEntityType(entityType); + String entityPrimaryKeyValue = + NodeUtils.extractFieldValueFromObject(sourceField, "entityPrimaryKeyValue"); sourceEntity.setEntityPrimaryKeyValue(entityPrimaryKeyValue); - String link = NodeUtils.extractFieldValueFromObject(sourceField, "link"); + String link = NodeUtils.extractFieldValueFromObject(sourceField, "link"); sourceEntity.setLink(link); - String lastmodTimestamp = NodeUtils.extractFieldValueFromObject(sourceField, "lastmodTimestamp"); + String lastmodTimestamp = + NodeUtils.extractFieldValueFromObject(sourceField, "lastmodTimestamp"); sourceEntity.setEntityTimeStamp(lastmodTimestamp); } } @@ -266,7 +269,7 @@ public class VisualizationService { return returnValue; } - + /** * Gets the visualization output basedon generic query. * @@ -334,13 +337,12 @@ public class VisualizationService { transformer.buildLinksFromGraphCollection(cachedNodeMap); /* - * - Apply configuration-driven styling - * - Build the final transformation response object - * - Use information we have to populate the GraphMeta object + * - Apply configuration-driven styling - Build the final transformation response object - Use + * information we have to populate the GraphMeta object */ transformer.addSearchTargetAttributesToRootNode(); - + GraphMeta graphMeta = new GraphMeta(); D3VisualizationOutput output = null; @@ -368,13 +370,13 @@ public class VisualizationService { logOptime("[build flat node array, add relationship data, search target," + " color scheme, and generate visualization output]", overlayDataStartTimeInMs); - + logOptime("doFilter()", opStartTimeInMs); return jsonResponse; } - + public void shutdown() { aaiProvider.shutdown(); aaiExecutorService.shutdown(); diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationTransformer.java b/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationTransformer.java index f15640a..fdc078e 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationTransformer.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/services/VisualizationTransformer.java @@ -59,8 +59,8 @@ import com.fasterxml.jackson.databind.ObjectWriter; public class VisualizationTransformer { - private static final Logger LOG = LoggerFactory.getInstance().getLogger( - VisualizationTransformer.class); + private static final Logger LOG = + LoggerFactory.getInstance().getLogger(VisualizationTransformer.class); List<JsonNode> flatNodeArray = new ArrayList<JsonNode>(); Set<String> enrichableUriPrefixes = null; @@ -74,7 +74,7 @@ public class VisualizationTransformer { List<JsonNodeLink> linkArrayOutput = new ArrayList<JsonNodeLink>(); - + private VisualizationConfig visualizationConfig; @@ -85,7 +85,7 @@ public class VisualizationTransformer { */ public VisualizationTransformer() throws Exception { visualizationConfig = VisualizationConfig.getConfig(); - + } @@ -139,7 +139,7 @@ public class VisualizationTransformer { output.setGraphMeta(graphMeta); for (JsonNode n : flatNodeArray) { - if ( n.getItemType()!= null) { + if (n.getItemType() != null) { output.pegCounter(n.getItemType()); } } @@ -154,8 +154,7 @@ public class VisualizationTransformer { String.valueOf(numLinks)); if (numLinks < (numNodes - 1)) { - LOG.warn(AaiUiMsgs.DANGLING_NODE_WARNING, String.valueOf(numLinks), - String.valueOf(numNodes)); + LOG.warn(AaiUiMsgs.DANGLING_NODE_WARNING, String.valueOf(numLinks), String.valueOf(numNodes)); } ObjectMapper mapper = new ObjectMapper(); @@ -245,9 +244,8 @@ public class VisualizationTransformer { } else { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "buildLinks()," - + " Filtering node = " + ain.getNodeId() + " @ depth = " - + ain.getNodeDepth()); + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "buildLinks()," + " Filtering node = " + + ain.getNodeId() + " @ depth = " + ain.getNodeDepth()); } } @@ -290,9 +288,8 @@ public class VisualizationTransformer { flatNodeArray.add(jsonNode); } else { if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, - "Filtering node from visualization: " + n.getNodeId() + " @ depth = " - + n.getNodeDepth()); + LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Filtering node from visualization: " + n.getNodeId() + + " @ depth = " + n.getNodeDepth()); } } } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/SearchServlet.java b/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/SearchServlet.java index c9fbc61..5a84346 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/SearchServlet.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/SearchServlet.java @@ -96,12 +96,11 @@ public class SearchServlet extends HttpServlet { private SearchServiceWrapper searchWrapper = null; private static final String KEY_PAYLOAD = "payload"; - + /** * Instantiates a new search servlet. */ - public SearchServlet() { - } + public SearchServlet() {} /* * (non-Javadoc) @@ -115,11 +114,11 @@ public class SearchServlet extends HttpServlet { doPost(request, response); } - public void destroy() { + public void destroy() { // TODO Auto-generated method stub super.destroy(); } - + public void init() throws ServletException { super.init(); searchWrapper = new SearchServiceWrapper(); @@ -150,7 +149,7 @@ public class SearchServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String txnID = request.getHeader("X-TransactionId"); - if (txnID == null) { + if (txnID == null) { txnID = NodeUtils.getRandomTxnId(); } @@ -220,7 +219,6 @@ public class SearchServlet extends HttpServlet { } } - - + } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/VisualizationServlet.java b/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/VisualizationServlet.java index f51eeac..85ebe50 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/VisualizationServlet.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/servlet/VisualizationServlet.java @@ -59,8 +59,9 @@ public class VisualizationServlet extends HttpServlet { private static final long serialVersionUID = 4678831934652478571L; private static final Logger LOG = LoggerFactory.getInstance().getLogger(VisualizationServlet.class); - private static final String VISUALIZATION_API_ENDPOINT = "prepareVisualization"; + private static final String VISUALIZATION_API_ENDPOINT = "prepareVisualization"; private final VisualizationService visualizationService; + /** * Instantiates a new visualization servlet. * @@ -190,10 +191,10 @@ public class VisualizationServlet extends HttpServlet { out.print("\n"); } } - + @Override public void destroy() { - super.destroy(); - visualizationService.shutdown(); + super.destroy(); + visualizationService.shutdown(); } } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/task/CollectNodeSelfLinkTask.java b/src/main/java/org/onap/aai/sparky/viewandinspect/task/CollectNodeSelfLinkTask.java index 7205119..3b750b3 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/task/CollectNodeSelfLinkTask.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/task/CollectNodeSelfLinkTask.java @@ -33,6 +33,7 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class CollectNodeSelfLinkTask implements Supplier<OperationResult> { private String selfLink; + /** * @return the selfLink */ @@ -74,7 +75,9 @@ public class CollectNodeSelfLinkTask implements Supplier<OperationResult> { this.aaiProvider = aaiProvider; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTask.java b/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTask.java index 54d4d6a..518d569 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTask.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTask.java @@ -62,7 +62,9 @@ public class PerformNodeSelfLinkProcessingTask implements Supplier<NodeProcessin this.aaiConfig = aaiConfig; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override @@ -77,7 +79,7 @@ public class PerformNodeSelfLinkProcessingTask implements Supplier<NodeProcessin } /** * Rebuild the self link: - * + * * <li>build the base url with the configured scheme + authority (server:port) * <li>recombine baseUrl + originalEncodedLink + queryStringParameters * @@ -87,13 +89,13 @@ public class PerformNodeSelfLinkProcessingTask implements Supplier<NodeProcessin String parameters = txn.getRequestParameters(); link = urlSchemeAndAuthority + link; - + if (parameters != null) { link += parameters; } - + if (logger.isDebugEnabled()) { logger.debug(AaiUiMsgs.DEBUG_GENERIC, "Collecting " + link); } diff --git a/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformSelfLinkDeterminationTask.java b/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformSelfLinkDeterminationTask.java index 3433bbd..1b71971 100644 --- a/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformSelfLinkDeterminationTask.java +++ b/src/main/java/org/onap/aai/sparky/viewandinspect/task/PerformSelfLinkDeterminationTask.java @@ -34,7 +34,8 @@ import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.slf4j.MDC; -public class PerformSelfLinkDeterminationTask implements Supplier<SelfLinkDeterminationTransaction> { +public class PerformSelfLinkDeterminationTask + implements Supplier<SelfLinkDeterminationTransaction> { private static final Logger logger = LoggerFactory.getInstance().getLogger(PerformSelfLinkDeterminationTask.class); @@ -51,15 +52,17 @@ public class PerformSelfLinkDeterminationTask implements Supplier<SelfLinkDeterm * @param requestParameters the request parameters * @param aaiProvider the aai provider */ - public PerformSelfLinkDeterminationTask(SelfLinkDeterminationTransaction txn, String requestParameters, - ActiveInventoryDataProvider aaiProvider) { - + public PerformSelfLinkDeterminationTask(SelfLinkDeterminationTransaction txn, + String requestParameters, ActiveInventoryDataProvider aaiProvider) { + this.aaiProvider = aaiProvider; this.txn = txn; this.contextMap = MDC.getCopyOfContextMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.function.Supplier#get() */ @Override @@ -74,8 +77,9 @@ public class PerformSelfLinkDeterminationTask implements Supplier<SelfLinkDeterm OperationResult opResult = null; try { - opResult = aaiProvider.queryActiveInventoryWithRetries(txn.getQueryString(), "application/json", - ActiveInventoryConfig.getConfig().getAaiRestConfig().getNumRequestRetries()); + opResult = + aaiProvider.queryActiveInventoryWithRetries(txn.getQueryString(), "application/json", + ActiveInventoryConfig.getConfig().getAaiRestConfig().getNumRequestRetries()); } catch (Exception exc) { opResult = new OperationResult(); opResult.setResult(500, "Querying AAI with retry failed due to an exception."); @@ -91,4 +95,4 @@ public class PerformSelfLinkDeterminationTask implements Supplier<SelfLinkDeterm } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sparky/FilterByContainsClassName.java b/src/test/java/org/onap/aai/sparky/FilterByContainsClassName.java index 1f55628..bfcc1c7 100644 --- a/src/test/java/org/onap/aai/sparky/FilterByContainsClassName.java +++ b/src/test/java/org/onap/aai/sparky/FilterByContainsClassName.java @@ -4,7 +4,7 @@ import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.PojoClassFilter; public class FilterByContainsClassName implements PojoClassFilter { - //Since Pattern doesn't implement equals, relying on String for equals & hashCode instead. + // Since Pattern doesn't implement equals, relying on String for equals & hashCode instead. private final String className; public FilterByContainsClassName(String regex) { @@ -19,4 +19,4 @@ public class FilterByContainsClassName implements PojoClassFilter { public int hashCode() { return className.hashCode(); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sparky/SparkyPojoTest.java b/src/test/java/org/onap/aai/sparky/SparkyPojoTest.java index ce50718..bc56223 100644 --- a/src/test/java/org/onap/aai/sparky/SparkyPojoTest.java +++ b/src/test/java/org/onap/aai/sparky/SparkyPojoTest.java @@ -16,178 +16,206 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; public class SparkyPojoTest { -//The package to be tested + // The package to be tested private String packageName = "org.onap.aai.sparky"; private List<PojoClass> pojoClasses; -@Test + @Test public void validateAnalytics() { - - String packageName = "org.onap.aai.sparky.analytics"; - List<PojoClass> analyticsPojoClasses; - - FilterChain filterChainByClassNameForAnalytics = new FilterChain(new FilterByContainsClassName("AveragingRingBuffer"), - new FilterByContainsClassName("AbstractStatistics"), new FilterByContainsClassName("HistogramSampler"), - new FilterByContainsClassName("Test")); - analyticsPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForAnalytics); - validateAll(analyticsPojoClasses); - + + String packageName = "org.onap.aai.sparky.analytics"; + List<PojoClass> analyticsPojoClasses; + + FilterChain filterChainByClassNameForAnalytics = new FilterChain( + new FilterByContainsClassName("AveragingRingBuffer"), + new FilterByContainsClassName("AbstractStatistics"), + new FilterByContainsClassName("HistogramSampler"), new FilterByContainsClassName("Test")); + analyticsPojoClasses = + PojoClassFactory.getPojoClassesRecursively(packageName, filterChainByClassNameForAnalytics); + validateAll(analyticsPojoClasses); + } -@Test -public void validateAAIConfig() { - - String packageName = "org.onap.aai.sparky.dal.aai.config"; - List<PojoClass> aaiConfigPojoClasses; - // activeinventory config mught come back - FilterChain filterChainByClassNameForConfig = new FilterChain(new FilterByContainsClassName("ActiveInventoryConfig"), - new FilterByContainsClassName("Test")); - aaiConfigPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForConfig); - validateAll(aaiConfigPojoClasses); - - - -} + @Test + public void validateAAIConfig() { + String packageName = "org.onap.aai.sparky.dal.aai.config"; + List<PojoClass> aaiConfigPojoClasses; + // activeinventory config mught come back + FilterChain filterChainByClassNameForConfig = + new FilterChain(new FilterByContainsClassName("ActiveInventoryConfig"), + new FilterByContainsClassName("Test")); + aaiConfigPojoClasses = + PojoClassFactory.getPojoClassesRecursively(packageName, filterChainByClassNameForConfig); + validateAll(aaiConfigPojoClasses); -@Test -public void validateElasticSearch(){ - - String packageName = "org.onap.aai.sparky.dal.elasticsearch"; - List<PojoClass> elasticSearchPojoClasses; - - FilterChain filterChainByClassNameForElasticSearch = new FilterChain(new FilterByContainsClassName("ElasticSearchEntityStatistics"), - new FilterByContainsClassName("Test")); - elasticSearchPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForElasticSearch); - validateAll(elasticSearchPojoClasses); - - -} -@Test -public void validateElasticSearchEntity(){ - - String packageName = "org.onap.aai.sparky.dal.elasticsearch.entity"; - List<PojoClass> elasticSearchConfigPojoClasses; - - //FilterChain filterChainByClassNameForElasticSearchConfig = new FilterChain(new FilterByContainsClassName("ElasticSearchEntityStatistics"), - // new FilterByContainsClassName("Test")); - elasticSearchConfigPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,null); - validateAll(elasticSearchConfigPojoClasses); - -} + } -@Test -public void validateRest(){ - - String packageName = "org.onap.aai.sparky.dal.rest"; - List<PojoClass> restPojoClasses; - - FilterChain filterChainByClassNameForRest = new FilterChain(new FilterByContainsClassName("RestfulDataAccessor"), - new FilterByContainsClassName("Test"),new FilterByContainsClassName("RestOperationalStatistics"), - new FilterByContainsClassName("RestClientBuilder")); - restPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForRest); - validateAll(restPojoClasses); -} + @Test + public void validateElasticSearch() { + String packageName = "org.onap.aai.sparky.dal.elasticsearch"; + List<PojoClass> elasticSearchPojoClasses; -@Test -public void validateSASEntity(){ + FilterChain filterChainByClassNameForElasticSearch = + new FilterChain(new FilterByContainsClassName("ElasticSearchEntityStatistics"), + new FilterByContainsClassName("Test")); + elasticSearchPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName, + filterChainByClassNameForElasticSearch); + validateAll(elasticSearchPojoClasses); - String packageName = "org.onap.aai.sparky.dal.sas.entity"; - List<PojoClass> sasEntityPojoClasses; - - sasEntityPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,null); - validateAll(sasEntityPojoClasses); - -} + } -@Test -public void validateSecurity(){ - String packageName = "org.onap.aai.sparky.security"; - List<PojoClass> securityPojoClasses; - - FilterChain filterChainByClassNameForSecurity = new FilterChain(new FilterByContainsClassName("SecurityContextFactoryImpl"), - new FilterByContainsClassName("Test"), new FilterByContainsClassName("UserManager"), - new FilterByContainsClassName("RolesConfig"),new FilterByContainsClassName("PortalAuthenticationConfig")); - securityPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForSecurity); - validateAll(securityPojoClasses); -} + @Test + public void validateElasticSearchEntity() { + String packageName = "org.onap.aai.sparky.dal.elasticsearch.entity"; + List<PojoClass> elasticSearchConfigPojoClasses; -@Test -public void validateSecurityPortal(){ + // FilterChain filterChainByClassNameForElasticSearchConfig = new FilterChain(new + // FilterByContainsClassName("ElasticSearchEntityStatistics"), + // new FilterByContainsClassName("Test")); + elasticSearchConfigPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName, null); + validateAll(elasticSearchConfigPojoClasses); - String packageName = "org.onap.aai.sparky.security.portal"; - List<PojoClass> securityPortalPojoClasses; - - FilterChain filterChainByClassNameForSecurityPortal = new FilterChain(new FilterByContainsClassName("Test"), - new FilterByContainsClassName("UserManager"),new FilterByContainsClassName("RolesConfig"), - new FilterByContainsClassName("PortalAuthenticationConfig")); - securityPortalPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForSecurityPortal); - validateAll(securityPortalPojoClasses); -} + } -@Test -public void validateSynchronizer(){ - - String packageName = "org.onap.aai.sparky.synchronizer"; - List<PojoClass> synchronizerPojoClasses; - - FilterChain filterChainByClassNameForSynchronizer = new FilterChain(new FilterByContainsClassName("Test"), - new FilterByContainsClassName("AggregationSynchronizer"),new FilterByContainsClassName("SearchableEntitySynchronizer"), - new FilterByContainsClassName("AutosuggestionSynchronizer"),new FilterByContainsClassName("CrossEntityReferenceSynchronizer"), - new FilterByContainsClassName("SyncController"),new FilterByContainsClassName("SyncHelper"), - new FilterByContainsClassName("TransactionRateController"),new FilterByContainsClassName("AggregationSuggestionSynchronizer"), - new FilterByContainsClassName("AbstractEntitySynchronizer"),new FilterByContainsClassName("SynchronizerConfiguration")); - synchronizerPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForSynchronizer); - validateAll(synchronizerPojoClasses); -} + @Test + public void validateRest() { -@Test -public void validateUtil(){ - - String packageName = "org.onap.aai.sparky.util"; - List<PojoClass> utilPojoClasses; - - FilterChain filterChainByClassNameForUtil = new FilterChain(new FilterByContainsClassName("KeystoreBuilder"), - new FilterByContainsClassName("Test"),new FilterByContainsClassName("HttpServletHelper"),new FilterByContainsClassName("NodeUtils"), - new FilterByContainsClassName("CaptureLoggerAppender"),new FilterByContainsClassName("ElasticEntitySummarizer"), - new FilterByContainsClassName("ElasticGarbageInjector"),new FilterByContainsClassName("SuggestionsPermutation"), - new FilterByContainsClassName("savingTrustManager")); - utilPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForUtil); - validateAll(utilPojoClasses); -} + String packageName = "org.onap.aai.sparky.dal.rest"; + List<PojoClass> restPojoClasses; -@Test -public void validateViewAndInspect(){ - - String packageName = "org.onap.aai.sparky.viewandinspect"; - List<PojoClass> viewAndInspectPojoClasses; - - FilterChain filterChainByClassNameForViewAndInspect = new FilterChain(new FilterByContainsClassName("Test"), - new FilterByContainsClassName("PerformSelfLinkDetermination"),new FilterByContainsClassName("PerformNodeSelfLinkProcessingTask"), - new FilterByContainsClassName("ActiveInventoryNode"),new FilterByContainsClassName("NodeProcessingTransaction"), - new FilterByContainsClassName("VisualizationServlet"),new FilterByContainsClassName("VisualizationService"), - new FilterByContainsClassName("VisualizationContext")); - viewAndInspectPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName,filterChainByClassNameForViewAndInspect); - validateAll(viewAndInspectPojoClasses); -} + FilterChain filterChainByClassNameForRest = new FilterChain( + new FilterByContainsClassName("RestfulDataAccessor"), new FilterByContainsClassName("Test"), + new FilterByContainsClassName("RestOperationalStatistics"), + new FilterByContainsClassName("RestClientBuilder")); + restPojoClasses = + PojoClassFactory.getPojoClassesRecursively(packageName, filterChainByClassNameForRest); + validateAll(restPojoClasses); + } -public void validateAll(List<PojoClass> pojoClasses){ - - Validator validator = ValidatorBuilder.create() - .with(new SetterMustExistRule(), - new GetterMustExistRule()) - .with(new SetterTester(), - new GetterTester()) - .build(); -validator.validate(pojoClasses); -} -}
\ No newline at end of file + @Test + public void validateSASEntity() { + + String packageName = "org.onap.aai.sparky.dal.sas.entity"; + List<PojoClass> sasEntityPojoClasses; + + sasEntityPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName, null); + validateAll(sasEntityPojoClasses); + + } + + + @Test + public void validateSecurity() { + + String packageName = "org.onap.aai.sparky.security"; + List<PojoClass> securityPojoClasses; + + FilterChain filterChainByClassNameForSecurity = + new FilterChain(new FilterByContainsClassName("SecurityContextFactoryImpl"), + new FilterByContainsClassName("Test"), new FilterByContainsClassName("UserManager"), + new FilterByContainsClassName("RolesConfig"), + new FilterByContainsClassName("PortalAuthenticationConfig")); + securityPojoClasses = + PojoClassFactory.getPojoClassesRecursively(packageName, filterChainByClassNameForSecurity); + validateAll(securityPojoClasses); + } + + + @Test + public void validateSecurityPortal() { + + String packageName = "org.onap.aai.sparky.security.portal"; + List<PojoClass> securityPortalPojoClasses; + + FilterChain filterChainByClassNameForSecurityPortal = new FilterChain( + new FilterByContainsClassName("Test"), new FilterByContainsClassName("UserManager"), + new FilterByContainsClassName("RolesConfig"), + new FilterByContainsClassName("PortalAuthenticationConfig")); + securityPortalPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName, + filterChainByClassNameForSecurityPortal); + validateAll(securityPortalPojoClasses); + } + + + @Test + public void validateSynchronizer() { + + String packageName = "org.onap.aai.sparky.synchronizer"; + List<PojoClass> synchronizerPojoClasses; + + FilterChain filterChainByClassNameForSynchronizer = + new FilterChain(new FilterByContainsClassName("Test"), + new FilterByContainsClassName("AggregationSynchronizer"), + new FilterByContainsClassName("SearchableEntitySynchronizer"), + new FilterByContainsClassName("AutosuggestionSynchronizer"), + new FilterByContainsClassName("CrossEntityReferenceSynchronizer"), + new FilterByContainsClassName("SyncController"), + new FilterByContainsClassName("SyncHelper"), + new FilterByContainsClassName("TransactionRateController"), + new FilterByContainsClassName("AggregationSuggestionSynchronizer"), + new FilterByContainsClassName("AbstractEntitySynchronizer"), + new FilterByContainsClassName("SynchronizerConfiguration")); + synchronizerPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName, + filterChainByClassNameForSynchronizer); + validateAll(synchronizerPojoClasses); + } + + @Test + public void validateUtil() { + + String packageName = "org.onap.aai.sparky.util"; + List<PojoClass> utilPojoClasses; + + FilterChain filterChainByClassNameForUtil = new FilterChain( + new FilterByContainsClassName("KeystoreBuilder"), new FilterByContainsClassName("Test"), + new FilterByContainsClassName("HttpServletHelper"), + new FilterByContainsClassName("NodeUtils"), + new FilterByContainsClassName("CaptureLoggerAppender"), + new FilterByContainsClassName("ElasticEntitySummarizer"), + new FilterByContainsClassName("ElasticGarbageInjector"), + new FilterByContainsClassName("SuggestionsPermutation"), + new FilterByContainsClassName("savingTrustManager")); + utilPojoClasses = + PojoClassFactory.getPojoClassesRecursively(packageName, filterChainByClassNameForUtil); + validateAll(utilPojoClasses); + } + + @Test + public void validateViewAndInspect() { + + String packageName = "org.onap.aai.sparky.viewandinspect"; + List<PojoClass> viewAndInspectPojoClasses; + + FilterChain filterChainByClassNameForViewAndInspect = + new FilterChain(new FilterByContainsClassName("Test"), + new FilterByContainsClassName("PerformSelfLinkDetermination"), + new FilterByContainsClassName("PerformNodeSelfLinkProcessingTask"), + new FilterByContainsClassName("ActiveInventoryNode"), + new FilterByContainsClassName("NodeProcessingTransaction"), + new FilterByContainsClassName("VisualizationServlet"), + new FilterByContainsClassName("VisualizationService"), + new FilterByContainsClassName("VisualizationContext")); + viewAndInspectPojoClasses = PojoClassFactory.getPojoClassesRecursively(packageName, + filterChainByClassNameForViewAndInspect); + validateAll(viewAndInspectPojoClasses); + } + + public void validateAll(List<PojoClass> pojoClasses) { + + Validator validator = + ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate(pojoClasses); + } + +} diff --git a/src/test/java/org/onap/aai/sparky/analytics/AbstractStatisticsTest.java b/src/test/java/org/onap/aai/sparky/analytics/AbstractStatisticsTest.java index a420e1d..c2ab18f 100644 --- a/src/test/java/org/onap/aai/sparky/analytics/AbstractStatisticsTest.java +++ b/src/test/java/org/onap/aai/sparky/analytics/AbstractStatisticsTest.java @@ -5,42 +5,42 @@ import org.junit.Test; public class AbstractStatisticsTest {
- @Test
- public void testAllMethods() {
- AbstractStatistics abs = new AbstractStatistics();
-
- int counterValue1 = abs.getCounterValue("key");
- Assert.assertEquals(-1, counterValue1);
-
- abs.addCounter("key");
- int counterValue2 = abs.getCounterValue("key");
- Assert.assertEquals(0, counterValue2);
-
- abs.pegCounter("key");
- int counterValue3 = abs.getCounterValue("key");
- Assert.assertEquals(1, counterValue3);
-
- abs.incrementCounter("key", 2);
- int counterValue4 = abs.getCounterValue("key");
- Assert.assertEquals(3, counterValue4);
-
- String histStat1 = abs.getHistogramStats("key", false, " ");
- Assert.assertNull(histStat1);
-
- abs.addHistogram("key", "hist1", 10, 1, 2);
- String histStat2 = abs.getHistogramStats("key", false, " ");
- Assert.assertEquals(" hist1,-1,0,0,0,1,10.00,0",histStat2);
-
- abs.updateHistogram("key", 3);
- String histStat3 = abs.getHistogramStats("key", false, " ");
- Assert.assertEquals(" hist1,3,3,3,1,1,10.00,1",histStat3);
-
- abs.reset();
- int counterValue5 = abs.getCounterValue("key");
- String histStat4 = abs.getHistogramStats("key", false, " ");
- Assert.assertEquals(0, counterValue5);
- Assert.assertEquals(" hist1,-1,0,0,0,1,10.00,0",histStat4);
-
-
- }
+ @Test
+ public void testAllMethods() {
+ AbstractStatistics abs = new AbstractStatistics();
+
+ int counterValue1 = abs.getCounterValue("key");
+ Assert.assertEquals(-1, counterValue1);
+
+ abs.addCounter("key");
+ int counterValue2 = abs.getCounterValue("key");
+ Assert.assertEquals(0, counterValue2);
+
+ abs.pegCounter("key");
+ int counterValue3 = abs.getCounterValue("key");
+ Assert.assertEquals(1, counterValue3);
+
+ abs.incrementCounter("key", 2);
+ int counterValue4 = abs.getCounterValue("key");
+ Assert.assertEquals(3, counterValue4);
+
+ String histStat1 = abs.getHistogramStats("key", false, " ");
+ Assert.assertNull(histStat1);
+
+ abs.addHistogram("key", "hist1", 10, 1, 2);
+ String histStat2 = abs.getHistogramStats("key", false, " ");
+ Assert.assertEquals(" hist1,-1,0,0,0,1,10.00,0", histStat2);
+
+ abs.updateHistogram("key", 3);
+ String histStat3 = abs.getHistogramStats("key", false, " ");
+ Assert.assertEquals(" hist1,3,3,3,1,1,10.00,1", histStat3);
+
+ abs.reset();
+ int counterValue5 = abs.getCounterValue("key");
+ String histStat4 = abs.getHistogramStats("key", false, " ");
+ Assert.assertEquals(0, counterValue5);
+ Assert.assertEquals(" hist1,-1,0,0,0,1,10.00,0", histStat4);
+
+
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/analytics/AveragingRingBufferTest.java b/src/test/java/org/onap/aai/sparky/analytics/AveragingRingBufferTest.java index 4c37c08..89d32ef 100644 --- a/src/test/java/org/onap/aai/sparky/analytics/AveragingRingBufferTest.java +++ b/src/test/java/org/onap/aai/sparky/analytics/AveragingRingBufferTest.java @@ -38,7 +38,7 @@ import org.mockito.runners.MockitoJUnitRunner; /** * The Class AveragingRingBufferTest. */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class AveragingRingBufferTest { protected SecureRandom random = new SecureRandom(); diff --git a/src/test/java/org/onap/aai/sparky/analytics/HistogramSamplerTest.java b/src/test/java/org/onap/aai/sparky/analytics/HistogramSamplerTest.java index 60a67d5..63d24a6 100644 --- a/src/test/java/org/onap/aai/sparky/analytics/HistogramSamplerTest.java +++ b/src/test/java/org/onap/aai/sparky/analytics/HistogramSamplerTest.java @@ -36,7 +36,7 @@ import org.mockito.runners.MockitoJUnitRunner; /** * The Class HistogramSamplerTest. */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class HistogramSamplerTest { protected SecureRandom random = new SecureRandom(); diff --git a/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java b/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java index 9816fff..f8f4b99 100644 --- a/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java +++ b/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java @@ -5,48 +5,48 @@ import org.junit.Test; public class HistoricalCounterTest {
-
- @Test
- public void testAllMethods() {
- HistoricalCounter hc = new HistoricalCounter(true);
-
- boolean maintainSingleValue = hc.isSingleValue();
- Assert.assertTrue(maintainSingleValue);
-
- hc.update(1.0);
- double value = hc.getValue();
- Assert.assertEquals(1.0, value, 0.1);
-
- double min = hc.getMin();
- Assert.assertEquals(-1, min, 0.1);
-
- double max = hc.getMax();
- Assert.assertEquals(0, max, 0.1);
-
- long numOfSamples = hc.getNumSamples();
- Assert.assertEquals(0, numOfSamples, 0.1);
-
- double avg = hc.getAvg();
- Assert.assertEquals(0, avg, 0.1);
-
- String stringValue = hc.toString();
- Assert.assertNotNull(stringValue);
-
- hc.reset();
-
- double valueReset = hc.getValue();
- Assert.assertEquals(0.0, valueReset, 0.1);
-
- double minReset = hc.getMin();
- Assert.assertEquals(-1, minReset, 0.1);
-
- double maxReset = hc.getMax();
- Assert.assertEquals(0, maxReset, 0.1);
-
- long numOfSamplesReset = hc.getNumSamples();
- Assert.assertEquals(0, numOfSamplesReset, 0.1);
-
- double avgReset = hc.getAvg();
- Assert.assertEquals(0, avgReset, 0.1);
- }
+
+ @Test
+ public void testAllMethods() {
+ HistoricalCounter hc = new HistoricalCounter(true);
+
+ boolean maintainSingleValue = hc.isSingleValue();
+ Assert.assertTrue(maintainSingleValue);
+
+ hc.update(1.0);
+ double value = hc.getValue();
+ Assert.assertEquals(1.0, value, 0.1);
+
+ double min = hc.getMin();
+ Assert.assertEquals(-1, min, 0.1);
+
+ double max = hc.getMax();
+ Assert.assertEquals(0, max, 0.1);
+
+ long numOfSamples = hc.getNumSamples();
+ Assert.assertEquals(0, numOfSamples, 0.1);
+
+ double avg = hc.getAvg();
+ Assert.assertEquals(0, avg, 0.1);
+
+ String stringValue = hc.toString();
+ Assert.assertNotNull(stringValue);
+
+ hc.reset();
+
+ double valueReset = hc.getValue();
+ Assert.assertEquals(0.0, valueReset, 0.1);
+
+ double minReset = hc.getMin();
+ Assert.assertEquals(-1, minReset, 0.1);
+
+ double maxReset = hc.getMax();
+ Assert.assertEquals(0, maxReset, 0.1);
+
+ long numOfSamplesReset = hc.getNumSamples();
+ Assert.assertEquals(0, numOfSamplesReset, 0.1);
+
+ double avgReset = hc.getAvg();
+ Assert.assertEquals(0, avgReset, 0.1);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/config/oxm/CrossEntityReferenceTest.java b/src/test/java/org/onap/aai/sparky/config/oxm/CrossEntityReferenceTest.java index 205cefd..0ef0458 100644 --- a/src/test/java/org/onap/aai/sparky/config/oxm/CrossEntityReferenceTest.java +++ b/src/test/java/org/onap/aai/sparky/config/oxm/CrossEntityReferenceTest.java @@ -6,22 +6,22 @@ import org.onap.aai.sparky.config.oxm.CrossEntityReference; public class CrossEntityReferenceTest {
-
- @Test
- public void testCrossEntityReferenceAllMethods() {
- CrossEntityReference cer = new CrossEntityReference();
-
- Assert.assertNull(cer.getTargetEntityType());
-
- cer.setTargetEntityType("TET");
- Assert.assertEquals(cer.getTargetEntityType(), "TET");
-
- Assert.assertEquals(cer.getReferenceAttributes().size(), 0);
-
- cer.addReferenceAttribute("AT");
-
- Assert.assertEquals(cer.getReferenceAttributes().size(), 1);
-
- Assert.assertNotNull(cer.toString());
- }
+
+ @Test
+ public void testCrossEntityReferenceAllMethods() {
+ CrossEntityReference cer = new CrossEntityReference();
+
+ Assert.assertNull(cer.getTargetEntityType());
+
+ cer.setTargetEntityType("TET");
+ Assert.assertEquals(cer.getTargetEntityType(), "TET");
+
+ Assert.assertEquals(cer.getReferenceAttributes().size(), 0);
+
+ cer.addReferenceAttribute("AT");
+
+ Assert.assertEquals(cer.getReferenceAttributes().size(), 1);
+
+ Assert.assertNotNull(cer.toString());
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilterTest.java b/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilterTest.java index 0c21c03..d971084 100644 --- a/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilterTest.java +++ b/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderFilterTest.java @@ -18,38 +18,40 @@ import org.onap.aai.sparky.config.oxm.OxmModelLoaderFilter; public class OxmModelLoaderFilterTest {
- @Mock
- ServletRequest servletRequest;
-
- @Mock
- ServletResponse servletResponse;
-
- @Mock
- FilterChain filterChain;
-
- @Mock
- FilterConfig filterConfig;
-
- @InjectMocks
- OxmModelLoaderFilter oxmModelLoaderFilter;
-
- @Before
- public void init() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void testDoFilter() throws IOException, ServletException{
- Mockito.doNothing().when(filterChain).doFilter(Mockito.any(ServletRequest.class), Mockito.any(ServletResponse.class));
- oxmModelLoaderFilter.doFilter(servletRequest, servletResponse, filterChain);
- Mockito.verify(filterChain, Mockito.times(1)).doFilter(Mockito.any(ServletRequest.class), Mockito.any(ServletResponse.class));
- }
-
- /*This test is taking more than 5 secs. Commented out
- @Test
- public void testInit() throws ServletException {
- OxmModelLoaderFilter oxmFilter = new OxmModelLoaderFilter();
- oxmFilter.init(filterConfig);
- }*/
-
+ @Mock
+ ServletRequest servletRequest;
+
+ @Mock
+ ServletResponse servletResponse;
+
+ @Mock
+ FilterChain filterChain;
+
+ @Mock
+ FilterConfig filterConfig;
+
+ @InjectMocks
+ OxmModelLoaderFilter oxmModelLoaderFilter;
+
+ @Before
+ public void init() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testDoFilter() throws IOException, ServletException {
+ Mockito.doNothing().when(filterChain).doFilter(Mockito.any(ServletRequest.class),
+ Mockito.any(ServletResponse.class));
+ oxmModelLoaderFilter.doFilter(servletRequest, servletResponse, filterChain);
+ Mockito.verify(filterChain, Mockito.times(1)).doFilter(Mockito.any(ServletRequest.class),
+ Mockito.any(ServletResponse.class));
+ }
+
+ /*
+ * This test is taking more than 5 secs. Commented out
+ *
+ * @Test public void testInit() throws ServletException { OxmModelLoaderFilter oxmFilter = new
+ * OxmModelLoaderFilter(); oxmFilter.init(filterConfig); }
+ */
+
}
diff --git a/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderTest.java b/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderTest.java index 3ef571e..5ff9e85 100644 --- a/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderTest.java +++ b/src/test/java/org/onap/aai/sparky/config/oxm/OxmModelLoaderTest.java @@ -32,19 +32,19 @@ import org.mockito.Mockito; public class OxmModelLoaderTest {
- OxmModelLoader loader;
-
- @Test
- public void testLoadModel_ShouldSucceed() throws IOException {
- String version = "v11";
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ OxmModelLoader loader;
- loader = Mockito.spy(new OxmModelLoader());
- Mockito.when(loader.loadOxmFileName(version)).thenReturn(
- System.getProperty("AJSC_HOME") + "/bundleconfig-local/oxm/aai_oxm_" + version + ".xml");
+ @Test
+ public void testLoadModel_ShouldSucceed() throws IOException {
+ String version = "v11";
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- loader.loadModel(version);
+ loader = Mockito.spy(new OxmModelLoader());
+ Mockito.when(loader.loadOxmFileName(version)).thenReturn(
+ System.getProperty("AJSC_HOME") + "/bundleconfig-local/oxm/aai_oxm_" + version + ".xml");
- assertNotEquals(null, loader.getOxmModel());
- }
+ loader.loadModel(version);
+
+ assertNotEquals(null, loader.getOxmModel());
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/NetworkTransactionTest.java b/src/test/java/org/onap/aai/sparky/dal/NetworkTransactionTest.java index 0e3c398..f2098fb 100644 --- a/src/test/java/org/onap/aai/sparky/dal/NetworkTransactionTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/NetworkTransactionTest.java @@ -8,29 +8,29 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class NetworkTransactionTest {
- @Test
- public void testAllMethods() {
- NetworkTransaction ntt = new NetworkTransaction();
- ntt.setOperationType(HttpMethod.GET);
- Assert.assertEquals(HttpMethod.GET, ntt.getOperationType());
-
- ntt.setTaskAgeInMs();
- Assert.assertNotNull(ntt.getTaskAgeInMs());
-
- ntt.setOperationResult(new OperationResult());
- Assert.assertNotNull(ntt.getOperationResult());
-
- ntt.setEntityType("entity");
- Assert.assertEquals(ntt.getEntityType(), "entity");
-
- ntt.setLink("link");
- Assert.assertEquals(ntt.getLink(), "link");
-
- ntt.setDescriptor(new OxmEntityDescriptor());
- Assert.assertNotNull(ntt.getDescriptor());
-
- Assert.assertNotNull(ntt.toString());
- }
-
-
+ @Test
+ public void testAllMethods() {
+ NetworkTransaction ntt = new NetworkTransaction();
+ ntt.setOperationType(HttpMethod.GET);
+ Assert.assertEquals(HttpMethod.GET, ntt.getOperationType());
+
+ ntt.setTaskAgeInMs();
+ Assert.assertNotNull(ntt.getTaskAgeInMs());
+
+ ntt.setOperationResult(new OperationResult());
+ Assert.assertNotNull(ntt.getOperationResult());
+
+ ntt.setEntityType("entity");
+ Assert.assertEquals(ntt.getEntityType(), "entity");
+
+ ntt.setLink("link");
+ Assert.assertEquals(ntt.getLink(), "link");
+
+ ntt.setDescriptor(new OxmEntityDescriptor());
+ Assert.assertNotNull(ntt.getDescriptor());
+
+ Assert.assertNotNull(ntt.toString());
+ }
+
+
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapterTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapterTest.java index 9f18ab2..936bc72 100644 --- a/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapterTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryAdapterTest.java @@ -35,68 +35,70 @@ import org.onap.aai.sparky.dal.rest.RestClientBuilder; import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants;
public class ActiveInventoryAdapterTest {
-
- OxmModelLoader oxmModelLoader;
- ActiveInventoryAdapter adapter;
-
- @Before
- public void init() throws IOException, ElasticSearchOperationException {
- String version = "v11";
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/";
- oxmModelLoader = Mockito.spy(new OxmModelLoader());
- Mockito.when(oxmModelLoader.loadOxmFileName(version)).thenReturn(
+
+ OxmModelLoader oxmModelLoader;
+ ActiveInventoryAdapter adapter;
+
+ @Before
+ public void init() throws IOException, ElasticSearchOperationException {
+ String version = "v11";
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/";
+ oxmModelLoader = Mockito.spy(new OxmModelLoader());
+ Mockito.when(oxmModelLoader.loadOxmFileName(version)).thenReturn(
System.getProperty("AJSC_HOME") + "/bundleconfig-local/oxm/aai_oxm_" + version + ".xml");
-
- adapter = new ActiveInventoryAdapter(new RestClientBuilder());
- }
-
- @Test
- public void testQueryActiveInventoryWithRetries() {
-
- adapter.queryActiveInventoryWithRetries("https://localhost:9517/model/aai/webapp/index.html", "response-type-1", 1);
- }
-
- @Test(expected=NullPointerException.class)
- public void testGetSelfLinkForEntity_NullEntityType() throws Exception {
-
- adapter.getSelfLinkForEntity(null, "key", "value");
- }
-
- @Test(expected=NullPointerException.class)
- public void testGetSelfLinkForEntity_NullKeyName() throws Exception {
-
- adapter.getSelfLinkForEntity("entity", null, "value");
- }
-
- @Test(expected=NullPointerException.class)
- public void testGetSelfLinkForEntity_NullKeyValue() throws Exception {
-
- adapter.getSelfLinkForEntity("entity", "key", null);
- }
-
- @Test
- public void testGetSelfLinkForEntity_ServiceInstance() throws Exception {
-
- adapter.getSelfLinkForEntity("service-instance", "key", "value");
- }
-
- @Test
- public void testGetSelfLinkForEntity_NotServiceInstance() throws Exception {
-
- adapter.getSelfLinkForEntity("service", "key", "value");
- }
-
- @Test(expected=NullPointerException.class)
- public void testGetSelfLinkByEntityType_NullEntity() throws Exception {
-
- adapter.getSelfLinksByEntityType(null);
- }
-
- @Test(expected=NoSuchElementException.class)
- public void testGetSelfLinkByEntityType_NullEntityDescriptor() throws Exception {
-
- adapter.getSelfLinksByEntityType("entity-1");
- }
+
+ adapter = new ActiveInventoryAdapter(new RestClientBuilder());
+ }
+
+ @Test
+ public void testQueryActiveInventoryWithRetries() {
+
+ adapter.queryActiveInventoryWithRetries("https://localhost:9517/model/aai/webapp/index.html",
+ "response-type-1", 1);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testGetSelfLinkForEntity_NullEntityType() throws Exception {
+
+ adapter.getSelfLinkForEntity(null, "key", "value");
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testGetSelfLinkForEntity_NullKeyName() throws Exception {
+
+ adapter.getSelfLinkForEntity("entity", null, "value");
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testGetSelfLinkForEntity_NullKeyValue() throws Exception {
+
+ adapter.getSelfLinkForEntity("entity", "key", null);
+ }
+
+ @Test
+ public void testGetSelfLinkForEntity_ServiceInstance() throws Exception {
+
+ adapter.getSelfLinkForEntity("service-instance", "key", "value");
+ }
+
+ @Test
+ public void testGetSelfLinkForEntity_NotServiceInstance() throws Exception {
+
+ adapter.getSelfLinkForEntity("service", "key", "value");
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testGetSelfLinkByEntityType_NullEntity() throws Exception {
+
+ adapter.getSelfLinksByEntityType(null);
+ }
+
+ @Test(expected = NoSuchElementException.class)
+ public void testGetSelfLinkByEntityType_NullEntityDescriptor() throws Exception {
+
+ adapter.getSelfLinksByEntityType("entity-1");
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatisticsTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatisticsTest.java index b1357c4..f861a68 100644 --- a/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatisticsTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryEntityStatisticsTest.java @@ -14,62 +14,62 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class ActiveInventoryEntityStatisticsTest {
- OxmModelLoader oxmModelLoader;
-
- @Before
- public void init() {
- oxmModelLoader = OxmModelLoader.getInstance();
- }
-
- @Test
- public void testInitializeCountersFromOxmEntityDescriptors_NotNullDescriptors() {
- ActiveInventoryEntityStatistics aies = new ActiveInventoryEntityStatistics(oxmModelLoader);
-
- Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
-
- OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
- oxmEd.setEntityName("entity-1");
- oxmEd.setGeoLatName("geoLatName-1");
-
- descriptors.put("entity-1", oxmEd);
-
- aies.initializeCountersFromOxmEntityDescriptors(descriptors);
-
- aies.reset();
-
- }
-
- @Test
- public void testInitializeCountersFromOxmEntityDescriptors_NullDescriptors() {
- ActiveInventoryEntityStatistics aies = new ActiveInventoryEntityStatistics(oxmModelLoader);
-
- Map<String, OxmEntityDescriptor> descriptors = null;
-
- aies.initializeCountersFromOxmEntityDescriptors(descriptors);
-
- }
-
- @Test
- public void testUpdateCounters() {
-
- ActiveInventoryEntityStatistics aies = new ActiveInventoryEntityStatistics(oxmModelLoader);
- Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
- OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
- oxmEd.setEntityName("entity-1");
- oxmEd.setGeoLatName("geoLatName-1");
- descriptors.put("entity-1", oxmEd);
- aies.initializeCountersFromOxmEntityDescriptors(descriptors);
-
- OperationResult result = new OperationResult();
- result.setResultCode(200);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
-
- aies.updateCounters(ntwTxn);
-
- String statistics = aies.getStatisticsReport();
- Assert.assertNotNull(statistics);
-
- }
+ OxmModelLoader oxmModelLoader;
+
+ @Before
+ public void init() {
+ oxmModelLoader = OxmModelLoader.getInstance();
+ }
+
+ @Test
+ public void testInitializeCountersFromOxmEntityDescriptors_NotNullDescriptors() {
+ ActiveInventoryEntityStatistics aies = new ActiveInventoryEntityStatistics(oxmModelLoader);
+
+ Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
+
+ OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
+ oxmEd.setEntityName("entity-1");
+ oxmEd.setGeoLatName("geoLatName-1");
+
+ descriptors.put("entity-1", oxmEd);
+
+ aies.initializeCountersFromOxmEntityDescriptors(descriptors);
+
+ aies.reset();
+
+ }
+
+ @Test
+ public void testInitializeCountersFromOxmEntityDescriptors_NullDescriptors() {
+ ActiveInventoryEntityStatistics aies = new ActiveInventoryEntityStatistics(oxmModelLoader);
+
+ Map<String, OxmEntityDescriptor> descriptors = null;
+
+ aies.initializeCountersFromOxmEntityDescriptors(descriptors);
+
+ }
+
+ @Test
+ public void testUpdateCounters() {
+
+ ActiveInventoryEntityStatistics aies = new ActiveInventoryEntityStatistics(oxmModelLoader);
+ Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
+ OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
+ oxmEd.setEntityName("entity-1");
+ oxmEd.setGeoLatName("geoLatName-1");
+ descriptors.put("entity-1", oxmEd);
+ aies.initializeCountersFromOxmEntityDescriptors(descriptors);
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(200);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+
+ aies.updateCounters(ntwTxn);
+
+ String statistics = aies.getStatisticsReport();
+ Assert.assertNotNull(statistics);
+
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryProcessingExceptionStatisticsTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryProcessingExceptionStatisticsTest.java index 5677f4c..2b65655 100644 --- a/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryProcessingExceptionStatisticsTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/aai/ActiveInventoryProcessingExceptionStatisticsTest.java @@ -8,53 +8,55 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class ActiveInventoryProcessingExceptionStatisticsTest {
-
- @Test
- public void testUpdateCounters() {
- ActiveInventoryProcessingExceptionStatistics aipes = new ActiveInventoryProcessingExceptionStatistics();
-
- aipes.incrementCounter("NativeSocketConnectException", 1);
- aipes.incrementCounter("NativeSocketConnectionReset", 1);
- aipes.incrementCounter("NativeSocketConnectionRefused", 1);
- aipes.incrementCounter("JerseyClientTimoutException", 1);
- aipes.incrementCounter("UnknownException", 1);
-
- OperationResult result = new OperationResult();
- result.setResultCode(310);
- result.setResult("java.net.SocketTimeoutException: connect timed out");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- aipes.updateCounters(ntwTxn1);
-
- result.setResult("result-1");
- NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- aipes.updateCounters(ntwTxn2);
-
- result.setResult("java.net.ConnectException: Connection timed out: connect");
- NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- aipes.updateCounters(ntwTxn3);
-
- result.setResult("java.net.ConnectException: Connection refused: connect");
- NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- aipes.updateCounters(ntwTxn4);
-
- result.setResult("java.net.SocketException: Connection reset");
- NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- aipes.updateCounters(ntwTxn5);
-
- }
-
- @Test
- public void testGetStatisticsReport() {
- ActiveInventoryProcessingExceptionStatistics aipes = new ActiveInventoryProcessingExceptionStatistics();
-
- aipes.incrementCounter("NativeSocketConnectException", 1);
- aipes.incrementCounter("NativeSocketConnectionReset", 1);
- aipes.incrementCounter("NativeSocketConnectionRefused", 1);
- aipes.incrementCounter("JerseyClientTimoutException", 1);
- aipes.incrementCounter("UnknownException", 1);
-
- String statReport = aipes.getStatisticsReport();
- Assert.assertNotNull(statReport);
- }
+
+ @Test
+ public void testUpdateCounters() {
+ ActiveInventoryProcessingExceptionStatistics aipes =
+ new ActiveInventoryProcessingExceptionStatistics();
+
+ aipes.incrementCounter("NativeSocketConnectException", 1);
+ aipes.incrementCounter("NativeSocketConnectionReset", 1);
+ aipes.incrementCounter("NativeSocketConnectionRefused", 1);
+ aipes.incrementCounter("JerseyClientTimoutException", 1);
+ aipes.incrementCounter("UnknownException", 1);
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(310);
+ result.setResult("java.net.SocketTimeoutException: connect timed out");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ aipes.updateCounters(ntwTxn1);
+
+ result.setResult("result-1");
+ NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ aipes.updateCounters(ntwTxn2);
+
+ result.setResult("java.net.ConnectException: Connection timed out: connect");
+ NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ aipes.updateCounters(ntwTxn3);
+
+ result.setResult("java.net.ConnectException: Connection refused: connect");
+ NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ aipes.updateCounters(ntwTxn4);
+
+ result.setResult("java.net.SocketException: Connection reset");
+ NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ aipes.updateCounters(ntwTxn5);
+
+ }
+
+ @Test
+ public void testGetStatisticsReport() {
+ ActiveInventoryProcessingExceptionStatistics aipes =
+ new ActiveInventoryProcessingExceptionStatistics();
+
+ aipes.incrementCounter("NativeSocketConnectException", 1);
+ aipes.incrementCounter("NativeSocketConnectionReset", 1);
+ aipes.incrementCounter("NativeSocketConnectionRefused", 1);
+ aipes.incrementCounter("JerseyClientTimoutException", 1);
+ aipes.incrementCounter("UnknownException", 1);
+
+ String statReport = aipes.getStatisticsReport();
+ Assert.assertNotNull(statReport);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java index 0166550..9a590b8 100644 --- a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java @@ -42,83 +42,83 @@ public class ActiveInventoryConfigTest { assertNotNull(config); } - + private Properties getTestProperties() { - + Properties props = new Properties(); - - props.put("aai.rest.host","aai-host"); - props.put("aai.rest.port","8443"); - props.put("aai.rest.resourceBasePath","/aai/v10"); - props.put("aai.rest.connectTimeoutInMs","30000"); - props.put("aai.rest.readTimeoutInMs","60000"); - props.put("aai.rest.numRequestRetries","5"); - props.put("aai.rest.numResolverWorkers","15"); - - props.put("aai.rest.cache.enabled","false"); - props.put("aai.rest.cache.numWorkers","10"); - props.put("aai.rest.cache.cacheFailures","false"); - props.put("aai.rest.cache.useCacheOnly","false"); - props.put("aai.rest.cache.storageFolderOverride",""); - props.put("aai.rest.cache.maxTimeToLiveInMs","-1"); - - props.put("aai.rest.shallowEntities","cloud-region,complex,vnf-image,image"); - - props.put("aai.ssl.truststore.filename","synchronizer.jks"); - props.put("aai.ssl.truststore.type","jks"); - - props.put("aai.ssl.keystore.filename","aai-client-cert.p12"); - props.put("aai.ssl.keystore.pass","70c87528c88dcd9f9c2558d30e817868"); - props.put("aai.ssl.keystore.type","pkcs12"); - - props.put("aai.ssl.enableDebug","false"); - props.put("aai.ssl.validateServerHostName","false"); - props.put("aai.ssl.validateServerCertificateChain","false"); - - props.put("aai.rest.authenticationMode","SSL_CERT"); - props.put("aai.ssl.basicAuth.username",""); - props.put("aai.ssl.basicAuth.password",""); - - props.put("aai.taskProcessor.maxConcurrentWorkers","5"); - - props.put("aai.taskProcessor.transactionRateControllerEnabled","false"); - props.put("aai.taskProcessor.numSamplesPerThreadForRunningAverage","100"); - props.put("aai.taskProcessor.targetTPS","100"); - - props.put("aai.taskProcessor.bytesHistogramLabel","[Response Size In Bytes]"); - props.put("aai.taskProcessor.bytesHistogramMaxYAxis","1000000"); - props.put("aai.taskProcessor.bytesHistogramNumBins","20"); - props.put("aai.taskProcessor.bytesHistogramNumDecimalPoints","2"); - - props.put("aai.taskProcessor.queueLengthHistogramLabel","[Queue Item Length]"); - props.put("aai.taskProcessor.queueLengthHistogramMaxYAxis","20000"); - props.put("aai.taskProcessor.queueLengthHistogramNumBins","20"); - props.put("aai.taskProcessor.queueLengthHistogramNumDecimalPoints","2"); - - props.put("aai.taskProcessor.taskAgeHistogramLabel","[Task Age In Ms]"); - props.put("aai.taskProcessor.taskAgeHistogramMaxYAxis","600000"); - props.put("aai.taskProcessor.taskAgeHistogramNumBins","20"); - props.put("aai.taskProcessor.taskAgeHistogramNumDecimalPoints","2"); - - props.put("aai.taskProcessor.responseTimeHistogramLabel","[Response Time In Ms]"); - props.put("aai.taskProcessor.responseTimeHistogramMaxYAxis","10000"); - props.put("aai.taskProcessor.responseTimeHistogramNumBins","20"); - props.put("aai.taskProcessor.responseTimeHistogramNumDecimalPoints","2"); - - props.put("aai.taskProcessor.tpsHistogramLabel","[Transactions Per Second]"); - props.put("aai.taskProcessor.tpsHistogramMaxYAxis","100"); - props.put("aai.taskProcessor.tpsHistogramNumBins","20"); - props.put("aai.taskProcessor.tpsHistogramNumDecimalPoints","2"); - - + + props.put("aai.rest.host", "aai-host"); + props.put("aai.rest.port", "8443"); + props.put("aai.rest.resourceBasePath", "/aai/v10"); + props.put("aai.rest.connectTimeoutInMs", "30000"); + props.put("aai.rest.readTimeoutInMs", "60000"); + props.put("aai.rest.numRequestRetries", "5"); + props.put("aai.rest.numResolverWorkers", "15"); + + props.put("aai.rest.cache.enabled", "false"); + props.put("aai.rest.cache.numWorkers", "10"); + props.put("aai.rest.cache.cacheFailures", "false"); + props.put("aai.rest.cache.useCacheOnly", "false"); + props.put("aai.rest.cache.storageFolderOverride", ""); + props.put("aai.rest.cache.maxTimeToLiveInMs", "-1"); + + props.put("aai.rest.shallowEntities", "cloud-region,complex,vnf-image,image"); + + props.put("aai.ssl.truststore.filename", "synchronizer.jks"); + props.put("aai.ssl.truststore.type", "jks"); + + props.put("aai.ssl.keystore.filename", "aai-client-cert.p12"); + props.put("aai.ssl.keystore.pass", "70c87528c88dcd9f9c2558d30e817868"); + props.put("aai.ssl.keystore.type", "pkcs12"); + + props.put("aai.ssl.enableDebug", "false"); + props.put("aai.ssl.validateServerHostName", "false"); + props.put("aai.ssl.validateServerCertificateChain", "false"); + + props.put("aai.rest.authenticationMode", "SSL_CERT"); + props.put("aai.ssl.basicAuth.username", ""); + props.put("aai.ssl.basicAuth.password", ""); + + props.put("aai.taskProcessor.maxConcurrentWorkers", "5"); + + props.put("aai.taskProcessor.transactionRateControllerEnabled", "false"); + props.put("aai.taskProcessor.numSamplesPerThreadForRunningAverage", "100"); + props.put("aai.taskProcessor.targetTPS", "100"); + + props.put("aai.taskProcessor.bytesHistogramLabel", "[Response Size In Bytes]"); + props.put("aai.taskProcessor.bytesHistogramMaxYAxis", "1000000"); + props.put("aai.taskProcessor.bytesHistogramNumBins", "20"); + props.put("aai.taskProcessor.bytesHistogramNumDecimalPoints", "2"); + + props.put("aai.taskProcessor.queueLengthHistogramLabel", "[Queue Item Length]"); + props.put("aai.taskProcessor.queueLengthHistogramMaxYAxis", "20000"); + props.put("aai.taskProcessor.queueLengthHistogramNumBins", "20"); + props.put("aai.taskProcessor.queueLengthHistogramNumDecimalPoints", "2"); + + props.put("aai.taskProcessor.taskAgeHistogramLabel", "[Task Age In Ms]"); + props.put("aai.taskProcessor.taskAgeHistogramMaxYAxis", "600000"); + props.put("aai.taskProcessor.taskAgeHistogramNumBins", "20"); + props.put("aai.taskProcessor.taskAgeHistogramNumDecimalPoints", "2"); + + props.put("aai.taskProcessor.responseTimeHistogramLabel", "[Response Time In Ms]"); + props.put("aai.taskProcessor.responseTimeHistogramMaxYAxis", "10000"); + props.put("aai.taskProcessor.responseTimeHistogramNumBins", "20"); + props.put("aai.taskProcessor.responseTimeHistogramNumDecimalPoints", "2"); + + props.put("aai.taskProcessor.tpsHistogramLabel", "[Transactions Per Second]"); + props.put("aai.taskProcessor.tpsHistogramMaxYAxis", "100"); + props.put("aai.taskProcessor.tpsHistogramNumBins", "20"); + props.put("aai.taskProcessor.tpsHistogramNumDecimalPoints", "2"); + + return props; - - + + } @Test public void validateAccessors() throws Exception { - + ActiveInventoryConfig config = new ActiveInventoryConfig(getTestProperties()); ActiveInventoryRestConfig airc = config.getAaiRestConfig(); @@ -190,7 +190,7 @@ public class ActiveInventoryConfigTest { assertEquals("https://aai-host:9191/aai/v10/business/customers/customer/1234", config.repairSelfLink("/aai/v10/business/customers/customer/1234")); } - + @Test public void validateResourcePathExtraction() throws Exception { // https with API version @@ -210,15 +210,14 @@ public class ActiveInventoryConfigTest { .extractResourcePath("http://aai-host:9191/business/customers/customer/1234")); // no scheme, host, or port - assertEquals("business/customers/customer/1234", ActiveInventoryConfig - .extractResourcePath("business/customers/customer/1234")); + assertEquals("business/customers/customer/1234", + ActiveInventoryConfig.extractResourcePath("business/customers/customer/1234")); // no scheme, host, or port with API version - assertEquals("/aai/v10/business/customers/customer/1234", ActiveInventoryConfig - .extractResourcePath("/aai/v10/business/customers/customer/1234")); + assertEquals("/aai/v10/business/customers/customer/1234", + ActiveInventoryConfig.extractResourcePath("/aai/v10/business/customers/customer/1234")); // no scheme, host, or port with API version - assertEquals("", ActiveInventoryConfig - .extractResourcePath("")); + assertEquals("", ActiveInventoryConfig.extractResourcePath("")); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java index e02a6a7..d6bcf99 100644 --- a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java @@ -65,8 +65,11 @@ public class ActiveInventorySslConfigTest { props.put("aai.ssl.validateServiceCertificateChain", "false"); props.put("aai.ssl.keystore.type", "pkcs12"); props.put("aai.ssl.keystore.filename", "/opt/app/applocal/etc/cert.crt"); - /*props.put("aai.ssl.keystore.pass", encryptor.decryptValue(value)EncryptedConfiguration.encryptToTriple("AES", - Long.toString(123456789 % 10000), "aa1admin", "password"));*/ + /* + * props.put("aai.ssl.keystore.pass", + * encryptor.decryptValue(value)EncryptedConfiguration.encryptToTriple("AES", + * Long.toString(123456789 % 10000), "aa1admin", "password")); + */ props.put("aai.ssl.truststore.type", "jks"); props.put("aai.ssl.truststore.filename", "/opt/app/applocal/etc/cert.crt"); props.put("aai.ssl.basicAuth.username", "username"); @@ -196,15 +199,15 @@ public class ActiveInventorySslConfigTest { assertFalse(config.isValidateServerHostName()); assertFalse(config.isValidateServerCertificateChain()); - assertEquals(config.getKeystoreType(),"invalid"); + assertEquals(config.getKeystoreType(), "invalid"); assertTrue(config.getKeystoreFilename().contains("null")); - assertEquals(config.getKeystorePassword(),""); + assertEquals(config.getKeystorePassword(), ""); - assertEquals(config.getTruststoreType(),"invalid"); + assertEquals(config.getTruststoreType(), "invalid"); assertTrue(config.getTruststoreFilename().contains("null")); - assertEquals(config.getBasicAuthUsername(),"invalid"); - assertEquals(config.getBasicAuthPassword(),"invalid"); + assertEquals(config.getBasicAuthUsername(), "invalid"); + assertEquals(config.getBasicAuthPassword(), "invalid"); assertEquals(config.getBasicAuthenticationCredentials(), generateAuthorizationHeaderValue("invalid", "invalid")); @@ -240,30 +243,30 @@ public class ActiveInventorySslConfigTest { config.setEncryptor(encryptorMock); config.setValidateServerCertificateChain(true); config.setValidateServerHostName(true); - + assertEquals(System.getProperty("javax.net.debug"), "ssl"); assertTrue(config.isValidateServerHostName()); assertTrue(config.isValidateServerCertificateChain()); - assertEquals(config.getKeystoreType(),"test"); + assertEquals(config.getKeystoreType(), "test"); assertTrue(config.getKeystoreFilename().contains("test")); - assertEquals(config.getKeystorePassword(),"test"); + assertEquals(config.getKeystorePassword(), "test"); - assertEquals(config.getTruststoreType(),"test"); + assertEquals(config.getTruststoreType(), "test"); assertTrue(config.getTruststoreFilename().contains("test")); - assertEquals(config.getBasicAuthUsername(),"test"); - assertEquals(config.getBasicAuthPassword(),"test"); + assertEquals(config.getBasicAuthUsername(), "test"); + assertEquals(config.getBasicAuthPassword(), "test"); assertEquals(config.getBasicAuthenticationCredentials(), generateAuthorizationHeaderValue("test", "test")); - + assertNotNull(config.getEncryptor()); - + assertTrue(config.toString().contains("ActiveInventorySslConfig")); - - + + } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCacheTest.java b/src/test/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCacheTest.java index 45481ce..2beb36b 100644 --- a/src/test/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCacheTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/cache/InMemoryEntityCacheTest.java @@ -6,21 +6,21 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class InMemoryEntityCacheTest {
- @Test
- public void testInMemoryEntityCache_AllMethods() {
-
- InMemoryEntityCache imec = new InMemoryEntityCache();
-
- imec.put("key-1", null);
- Assert.assertNull(imec.get("entity-1", "key-1"));
- Assert.assertNull(imec.get("entity-1", null));
-
- OperationResult result = new OperationResult();
- result.setResultCode(200);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
-
- imec.put("key-1", result);
- Assert.assertNotNull(imec.get("entity-1", "key-1"));
- }
+ @Test
+ public void testInMemoryEntityCache_AllMethods() {
+
+ InMemoryEntityCache imec = new InMemoryEntityCache();
+
+ imec.put("key-1", null);
+ Assert.assertNull(imec.get("entity-1", "key-1"));
+ Assert.assertNull(imec.get("entity-1", null));
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(200);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+
+ imec.put("key-1", result);
+ Assert.assertNotNull(imec.get("entity-1", "key-1"));
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java index 5de9e2f..01a5bb0 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java @@ -48,30 +48,30 @@ import ch.qos.logback.classic.Level; public class ElasticSearchConfigTest {
private static final String GOOD_MAPPINGS_FILE =
- "{" + "\"properties\": {" + "\"entityType\": {" + "\"type\": \"string\"" + "},"
- + "\"edgeTagQueryEntityFieldName\": {" + "\"type\": \"string\"," + "\"index\": \"no\""
- + "}," + "\"edgeTagQueryEntityFieldValue\": {" + "\"type\": \"string\","
- + "\"index\": \"no\"" + "}," + "\"searchTagIDs\" : {" + "\"type\" : \"string\"" + "},"
- + "\"searchTags\": {" + "\"type\": \"string\"," + "\"analyzer\": \"nGram_analyzer\","
- + "\"search_analyzer\": \"whitespace_analyzer\"}" + "}" + "}";
+ "{" + "\"properties\": {" + "\"entityType\": {" + "\"type\": \"string\"" + "},"
+ + "\"edgeTagQueryEntityFieldName\": {" + "\"type\": \"string\"," + "\"index\": \"no\""
+ + "}," + "\"edgeTagQueryEntityFieldValue\": {" + "\"type\": \"string\","
+ + "\"index\": \"no\"" + "}," + "\"searchTagIDs\" : {" + "\"type\" : \"string\"" + "},"
+ + "\"searchTags\": {" + "\"type\": \"string\"," + "\"analyzer\": \"nGram_analyzer\","
+ + "\"search_analyzer\": \"whitespace_analyzer\"}" + "}" + "}";
private static final String GOOD_SETTINGS_FILE = "{\"analysis\": {" + "\"filter\": {"
- + "\"nGram_filter\": {" + "\"type\": \"nGram\"," + "\"min_gram\": 1," + "\"max_gram\": 50,"
- + "\"token_chars\": [" + "\"letter\"," + "\"digit\"," + "\"punctuation\"," + "\"symbol\""
- + "]}}," + "\"analyzer\": {" + "\"nGram_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\"," + "\"asciifolding\","
- + "\"nGram_filter\"]}," + "\"whitespace_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\","
- + "\"asciifolding\"]}}}}";
+ + "\"nGram_filter\": {" + "\"type\": \"nGram\"," + "\"min_gram\": 1," + "\"max_gram\": 50,"
+ + "\"token_chars\": [" + "\"letter\"," + "\"digit\"," + "\"punctuation\"," + "\"symbol\""
+ + "]}}," + "\"analyzer\": {" + "\"nGram_analyzer\": {" + "\"type\": \"custom\","
+ + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\"," + "\"asciifolding\","
+ + "\"nGram_filter\"]}," + "\"whitespace_analyzer\": {" + "\"type\": \"custom\","
+ + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\","
+ + "\"asciifolding\"]}}}}";
private static final String BAD_SETTINGS_FILE = "{\"analysis\": {" + "\"filter\": {"
- + "\"nGram_filter\": {" + "\"type\": \"nGram\"," + "\"min_gram\": 1," + "\"max_gram\": 50,"
- + "\"token_chars\": [" + "\"letter\"," + "\"digit\"," + "\"punctuation\"," + "\"symbol\""
- + "]}}," + "\"analyzer\": {" + "\"nGram_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\"," + "\"asciifolding\","
- + "\"nGram_filter\"]}," + "\"whitespace_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\","
- + "\"asciifolding\"]}}";
+ + "\"nGram_filter\": {" + "\"type\": \"nGram\"," + "\"min_gram\": 1," + "\"max_gram\": 50,"
+ + "\"token_chars\": [" + "\"letter\"," + "\"digit\"," + "\"punctuation\"," + "\"symbol\""
+ + "]}}," + "\"analyzer\": {" + "\"nGram_analyzer\": {" + "\"type\": \"custom\","
+ + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\"," + "\"asciifolding\","
+ + "\"nGram_filter\"]}," + "\"whitespace_analyzer\": {" + "\"type\": \"custom\","
+ + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\","
+ + "\"asciifolding\"]}}";
ElasticSearchConfig elasticSearchConfig;
@@ -130,12 +130,12 @@ public class ElasticSearchConfigTest { *
* @return the elastic search settings expect valid config
* @throws IOException Signals that an I/O exception has occurred.
- * @throws ElasticSearchOperationException the elastic search operation exception
- * Need to revisit this test case and change the way this class works
+ * @throws ElasticSearchOperationException the elastic search operation exception Need to revisit
+ * this test case and change the way this class works
*/
@Ignore
public void getElasticSearchSettings_expectValidConfig()
- throws IOException, ElasticSearchOperationException {
+ throws IOException, ElasticSearchOperationException {
System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
ElasticSearchConfig esConfig = new ElasticSearchConfig();
@@ -152,11 +152,11 @@ public class ElasticSearchConfigTest { * @throws IOException Signals that an I/O exception has occurred.
* @throws ElasticSearchOperationException the elastic search operation exception
*
- * Need to revisit this test case and change the way this class works
+ * Need to revisit this test case and change the way this class works
*/
@Ignore
public void getElasticSearchSettings_expectFileNotFoundException()
- throws IOException, ElasticSearchOperationException {
+ throws IOException, ElasticSearchOperationException {
System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
ElasticSearchConfig esConfig = new ElasticSearchConfig();
@@ -174,11 +174,11 @@ public class ElasticSearchConfigTest { * @throws IOException Signals that an I/O exception has occurred.
* @throws ElasticSearchOperationException the elastic search operation exception
*
- * Need to revisit this test case and change the way this class works
+ * Need to revisit this test case and change the way this class works
*/
@Ignore
public void getElasticSearchMappings_expectValidConfig()
- throws IOException, ElasticSearchOperationException {
+ throws IOException, ElasticSearchOperationException {
System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
ElasticSearchConfig esConfig = new ElasticSearchConfig();
@@ -197,7 +197,7 @@ public class ElasticSearchConfigTest { */
@Test(expected = ElasticSearchOperationException.class)
public void getElasticSearchMappings_expectFileNotFoundException()
- throws IOException, ElasticSearchOperationException {
+ throws IOException, ElasticSearchOperationException {
System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
ElasticSearchConfig esConfig = new ElasticSearchConfig();
@@ -216,7 +216,7 @@ public class ElasticSearchConfigTest { */
@Test
public void buildElasticSearchTableConfig_expectValidResult()
- throws ElasticSearchOperationException, IOException {
+ throws ElasticSearchOperationException, IOException {
ElasticSearchConfig spyEsConfig = Mockito.spy(new ElasticSearchConfig());
Mockito.doReturn(GOOD_MAPPINGS_FILE).when(spyEsConfig).getElasticSearchMappings();
Mockito.doReturn(GOOD_SETTINGS_FILE).when(spyEsConfig).getElasticSearchSettings();
@@ -233,7 +233,7 @@ public class ElasticSearchConfigTest { */
@Test(expected = ElasticSearchOperationException.class)
public void buildElasticSearchTableConfig_expectException()
- throws ElasticSearchOperationException, IOException {
+ throws ElasticSearchOperationException, IOException {
ElasticSearchConfig spyEsConfig = Mockito.spy(new ElasticSearchConfig());
Mockito.doReturn(GOOD_MAPPINGS_FILE).when(spyEsConfig).getElasticSearchMappings();
Mockito.doReturn(BAD_SETTINGS_FILE).when(spyEsConfig).getElasticSearchSettings();
@@ -246,7 +246,8 @@ public class ElasticSearchConfigTest { public void testGetFullUrl_ThreeParams() throws Exception {
Mockito.when(elasticSearchConfig.getIpAddress()).thenReturn("http://localhost");
Mockito.when(elasticSearchConfig.getHttpPort()).thenReturn("5443");
- String fullUrl = elasticSearchConfig.getElasticFullUrl("http://localhost:5443/aai/model/index", "entity-index", "entity");
+ String fullUrl = elasticSearchConfig.getElasticFullUrl("http://localhost:5443/aai/model/index",
+ "entity-index", "entity");
Assert.assertNotNull(fullUrl);
}
@@ -260,7 +261,7 @@ public class ElasticSearchConfigTest { }
@Test
- public void testGetBulkUrl() throws Exception {
+ public void testGetBulkUrl() throws Exception {
Mockito.when(elasticSearchConfig.getIpAddress()).thenReturn("http://localhost");
Mockito.when(elasticSearchConfig.getHttpPort()).thenReturn("5443");
String fullUrl = elasticSearchConfig.getBulkUrl();
@@ -270,7 +271,8 @@ public class ElasticSearchConfigTest { @Test
public void testGetConfigAsString() throws IOException, ElasticSearchOperationException {
System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- String retStr = elasticSearchConfig.getConfigAsString("item-1", System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/roles.config");
+ String retStr = elasticSearchConfig.getConfigAsString("item-1",
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/roles.config");
Assert.assertNotNull(retStr);
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatisticsTest.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatisticsTest.java index 6e4cf8a..92360c7 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatisticsTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchEntityStatisticsTest.java @@ -35,67 +35,67 @@ import org.onap.aai.sparky.dal.rest.OperationResult; public class ElasticSearchEntityStatisticsTest {
- @Test
- public void testInitializeCountersFromOxmEntityDescriptors_NotNullDescriptors() {
-
- ElasticSearchEntityStatistics eses = new ElasticSearchEntityStatistics(new OxmModelLoader());
- Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
-
- OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
- oxmEd.setEntityName("entity-1");
- oxmEd.setGeoLatName("geoLatName-1");
-
- descriptors.put("entity-1", oxmEd);
-
- eses.initializeCountersFromOxmEntityDescriptors(descriptors);
- eses.reset();
- }
-
- @Test
- public void testInitializeCountersFromOxmEntityDescriptors_NullDescriptors() {
-
- ElasticSearchEntityStatistics eses = new ElasticSearchEntityStatistics(new OxmModelLoader());
- Map<String, OxmEntityDescriptor> descriptors = null;
- eses.initializeCountersFromOxmEntityDescriptors(descriptors);
- }
-
- @Test
- public void testUpdateCounters() {
-
- ElasticSearchEntityStatistics eses = new ElasticSearchEntityStatistics(new OxmModelLoader());
- Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
-
- OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
- oxmEd.setEntityName("entity-1");
- oxmEd.setGeoLatName("geoLatName-1");
- descriptors.put("entity-1", oxmEd);
-
- eses.initializeCountersFromOxmEntityDescriptors(descriptors);
-
- OperationResult result = new OperationResult();
- result.setResultCode(200);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- eses.updateCounters(ntwTxn);
-
- result.setResultCode(201);
- NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- eses.updateCounters(ntwTxn1);
-
- result.setResultCode(202);
- NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- eses.updateCounters(ntwTxn2);
- NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- eses.updateCounters(ntwTxn3);
-
- result.setResultCode(101);
- NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- eses.updateCounters(ntwTxn4);
- NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- eses.updateCounters(ntwTxn5);
-
- String statistics = eses.getStatisticsReport();
- Assert.assertNotNull(statistics);
- }
+ @Test
+ public void testInitializeCountersFromOxmEntityDescriptors_NotNullDescriptors() {
+
+ ElasticSearchEntityStatistics eses = new ElasticSearchEntityStatistics(new OxmModelLoader());
+ Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
+
+ OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
+ oxmEd.setEntityName("entity-1");
+ oxmEd.setGeoLatName("geoLatName-1");
+
+ descriptors.put("entity-1", oxmEd);
+
+ eses.initializeCountersFromOxmEntityDescriptors(descriptors);
+ eses.reset();
+ }
+
+ @Test
+ public void testInitializeCountersFromOxmEntityDescriptors_NullDescriptors() {
+
+ ElasticSearchEntityStatistics eses = new ElasticSearchEntityStatistics(new OxmModelLoader());
+ Map<String, OxmEntityDescriptor> descriptors = null;
+ eses.initializeCountersFromOxmEntityDescriptors(descriptors);
+ }
+
+ @Test
+ public void testUpdateCounters() {
+
+ ElasticSearchEntityStatistics eses = new ElasticSearchEntityStatistics(new OxmModelLoader());
+ Map<String, OxmEntityDescriptor> descriptors = new HashMap<>();
+
+ OxmEntityDescriptor oxmEd = new OxmEntityDescriptor();
+ oxmEd.setEntityName("entity-1");
+ oxmEd.setGeoLatName("geoLatName-1");
+ descriptors.put("entity-1", oxmEd);
+
+ eses.initializeCountersFromOxmEntityDescriptors(descriptors);
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(200);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ eses.updateCounters(ntwTxn);
+
+ result.setResultCode(201);
+ NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ eses.updateCounters(ntwTxn1);
+
+ result.setResultCode(202);
+ NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ eses.updateCounters(ntwTxn2);
+ NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ eses.updateCounters(ntwTxn3);
+
+ result.setResultCode(101);
+ NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ eses.updateCounters(ntwTxn4);
+ NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ eses.updateCounters(ntwTxn5);
+
+ String statistics = eses.getStatisticsReport();
+ Assert.assertNotNull(statistics);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java index dd04248..bab190c 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java @@ -38,7 +38,7 @@ public class AutoSuggestDocumentEntity { public void setFields(AutoSuggestDocumentEntityFields fields) { this.fields = fields; } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java index eafef21..7c4c2db 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java @@ -37,7 +37,7 @@ public class AutoSuggestDocumentEntityFields { private List<String> input; private PayloadEntity payload; private int weight; - + public AutoSuggestDocumentEntityFields() { input = new ArrayList<String>(); } @@ -73,9 +73,9 @@ public class AutoSuggestDocumentEntityFields { public void setWeight(int weight) { this.weight = weight; } - + public void addInput(String input) { this.input.add(input); } - + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java index 18dfdc4..13326ab 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java @@ -28,9 +28,9 @@ import java.util.ArrayList; import java.util.List; public class AutoSuggestElasticHitsEntity { - + private List<AutoSuggestElasticHitEntity> hits; - + public AutoSuggestElasticHitsEntity() { hits = new ArrayList<AutoSuggestElasticHitEntity>(); } @@ -42,7 +42,7 @@ public class AutoSuggestElasticHitsEntity { public void setHits(List<AutoSuggestElasticHitEntity> hits) { this.hits = hits; } - + public void addHit(AutoSuggestElasticHitEntity hit) { this.hits.add(hit); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java index 40c9b6d..9dc9709 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java @@ -30,19 +30,19 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; public class AutoSuggestElasticSearchResponse { - + private int took; - + @JsonProperty("timed_out") private boolean timedOut; - + @JsonProperty("_shards") - private Map<String,String> shards; - + private Map<String, String> shards; + private AutoSuggestElasticHitsEntity hits; - public AutoSuggestElasticSearchResponse(){ - this.shards = new HashMap<String,String>(); + public AutoSuggestElasticSearchResponse() { + this.shards = new HashMap<String, String>(); } public int getTook() { @@ -68,7 +68,7 @@ public class AutoSuggestElasticSearchResponse { public void setShards(Map<String, String> shards) { this.shards = shards; } - + public void addShard(String name, String value) { shards.put(name, value); } @@ -80,6 +80,6 @@ public class AutoSuggestElasticSearchResponse { public void setHits(AutoSuggestElasticHitsEntity hits) { this.hits = hits; } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java index 5a578aa..9b5d27e 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java @@ -28,19 +28,19 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class BucketEntity { private String key; - + @JsonProperty("doc_count") private int docCount; public BucketEntity() { - + } - + public BucketEntity(String name, int value) { this.key = name; this.docCount = value; } - + public String getKey() { return key; } @@ -56,6 +56,6 @@ public class BucketEntity { public void setDocCount(int docCount) { this.docCount = docCount; } - - -} + + +} diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java index 4158903..dcd5b98 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java @@ -30,17 +30,17 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class ElasticHitsEntity { - + private int total; @JsonProperty("max_score") private int maxScore; - + private List<ElasticHit> hits; - + public ElasticHitsEntity() { this.hits = new ArrayList<ElasticHit>(); } - + public void addHit(ElasticHit hit) { this.hits.add(hit); } @@ -68,7 +68,7 @@ public class ElasticHitsEntity { public void setHits(List<ElasticHit> hits) { this.hits = hits; } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java index 6dd2d11..4306f6b 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java @@ -45,7 +45,7 @@ public class ElasticSearchAggegrationResponse { public ElasticSearchAggegrationResponse() { this.shards = new HashMap<String, String>(); - this.aggregations = new HashMap<String,ElasticSearchAggregation>(); + this.aggregations = new HashMap<String, ElasticSearchAggregation>(); } @@ -89,7 +89,7 @@ public class ElasticSearchAggegrationResponse { } public void addShard(String key, String value) { - this.shards.put(key,value); + this.shards.put(key, value); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java index 7bcd318..44794cd 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java @@ -30,15 +30,15 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class ElasticSearchAggregation { - + @JsonProperty("doc_count_error_upper_bound") private int docCountErrorUpperBound; - + @JsonProperty("sum_other_doc_count") private int sumOtherDocCount; - + private List<BucketEntity> buckets; - + public ElasticSearchAggregation() { buckets = new ArrayList<BucketEntity>(); } @@ -66,7 +66,7 @@ public class ElasticSearchAggregation { public void setBuckets(List<BucketEntity> buckets) { this.buckets = buckets; } - + public void addBucket(BucketEntity bucket) { buckets.add(bucket); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java index 5aec440..e02e353 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java @@ -33,9 +33,9 @@ public class ElasticSearchCountResponse { private Map<String, String> shards; public ElasticSearchCountResponse() { - this.shards = new HashMap<String,String>(); + this.shards = new HashMap<String, String>(); } - + public int getCount() { return count; } @@ -51,7 +51,7 @@ public class ElasticSearchCountResponse { public void setShards(Map<String, String> shards) { this.shards = shards; } - + public void addShard(String key, String value) { this.shards.put(key, value); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java index 5f5e333..da84dd7 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java @@ -26,7 +26,6 @@ package org.onap.aai.sparky.dal.elasticsearch.entity; public class PayloadEntity { - public PayloadEntity() { - } - + public PayloadEntity() {} + } diff --git a/src/test/java/org/onap/aai/sparky/dal/rest/RestOperationalStatisticsTest.java b/src/test/java/org/onap/aai/sparky/dal/rest/RestOperationalStatisticsTest.java index 415cbe7..2e0c90e 100644 --- a/src/test/java/org/onap/aai/sparky/dal/rest/RestOperationalStatisticsTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/rest/RestOperationalStatisticsTest.java @@ -28,183 +28,183 @@ import org.onap.aai.sparky.dal.NetworkTransaction; public class RestOperationalStatisticsTest {
- @Test
- public void testUpdateCounters_Get() {
- RestOperationalStatistics ros = new RestOperationalStatistics();
-
- OperationResult result = new OperationResult();
- result.setResultCode(101);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ros.updateCounters(ntwTxn1);
-
- result.setResultCode(201);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ros.updateCounters(ntwTxn2);
-
- result.setResultCode(301);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ros.updateCounters(ntwTxn3);
-
- result.setResultCode(401);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ros.updateCounters(ntwTxn4);
-
- result.setResultCode(501);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ros.updateCounters(ntwTxn5);
-
- result.setResultCode(601);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ros.updateCounters(ntwTxn6);
-
- String statistics = ros.getStatisticsReport();
- Assert.assertNotNull(statistics);
- }
-
- @Test
- public void testUpdateCounters_Put() {
- RestOperationalStatistics ros = new RestOperationalStatistics();
-
- OperationResult result = new OperationResult();
- result.setResultCode(101);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- ros.updateCounters(ntwTxn1);
-
- result.setResultCode(201);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- ros.updateCounters(ntwTxn2);
-
- result.setResultCode(301);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- ros.updateCounters(ntwTxn3);
-
- result.setResultCode(401);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- ros.updateCounters(ntwTxn4);
-
- result.setResultCode(501);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- ros.updateCounters(ntwTxn5);
-
- result.setResultCode(601);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
- ros.updateCounters(ntwTxn6);
-
- String statistics = ros.getStatisticsReport();
- Assert.assertNotNull(statistics);
- }
-
- @Test
- public void testUpdateCounters_Post() {
- RestOperationalStatistics ros = new RestOperationalStatistics();
-
- OperationResult result = new OperationResult();
- result.setResultCode(101);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
- ros.updateCounters(ntwTxn1);
-
- result.setResultCode(201);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
- ros.updateCounters(ntwTxn2);
-
- result.setResultCode(301);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
- ros.updateCounters(ntwTxn3);
-
- result.setResultCode(401);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
- ros.updateCounters(ntwTxn4);
-
- result.setResultCode(501);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
- ros.updateCounters(ntwTxn5);
-
- result.setResultCode(601);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
- ros.updateCounters(ntwTxn6);
-
- String statistics = ros.getStatisticsReport();
- Assert.assertNotNull(statistics);
- }
-
- @Test
- public void testUpdateCounters_Delete() {
- RestOperationalStatistics ros = new RestOperationalStatistics();
-
- OperationResult result = new OperationResult();
- result.setResultCode(101);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- ros.updateCounters(ntwTxn1);
-
- result.setResultCode(201);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- ros.updateCounters(ntwTxn2);
-
- result.setResultCode(301);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- ros.updateCounters(ntwTxn3);
-
- result.setResultCode(401);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- ros.updateCounters(ntwTxn4);
-
- result.setResultCode(501);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- ros.updateCounters(ntwTxn5);
-
- result.setResultCode(601);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
- ros.updateCounters(ntwTxn6);
-
- String statistics = ros.getStatisticsReport();
- Assert.assertNotNull(statistics);
- }
+ @Test
+ public void testUpdateCounters_Get() {
+ RestOperationalStatistics ros = new RestOperationalStatistics();
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(101);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ros.updateCounters(ntwTxn1);
+
+ result.setResultCode(201);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ros.updateCounters(ntwTxn2);
+
+ result.setResultCode(301);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ros.updateCounters(ntwTxn3);
+
+ result.setResultCode(401);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ros.updateCounters(ntwTxn4);
+
+ result.setResultCode(501);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ros.updateCounters(ntwTxn5);
+
+ result.setResultCode(601);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ros.updateCounters(ntwTxn6);
+
+ String statistics = ros.getStatisticsReport();
+ Assert.assertNotNull(statistics);
+ }
+
+ @Test
+ public void testUpdateCounters_Put() {
+ RestOperationalStatistics ros = new RestOperationalStatistics();
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(101);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ ros.updateCounters(ntwTxn1);
+
+ result.setResultCode(201);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ ros.updateCounters(ntwTxn2);
+
+ result.setResultCode(301);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ ros.updateCounters(ntwTxn3);
+
+ result.setResultCode(401);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ ros.updateCounters(ntwTxn4);
+
+ result.setResultCode(501);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ ros.updateCounters(ntwTxn5);
+
+ result.setResultCode(601);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.PUT, "entity-1", result);
+ ros.updateCounters(ntwTxn6);
+
+ String statistics = ros.getStatisticsReport();
+ Assert.assertNotNull(statistics);
+ }
+
+ @Test
+ public void testUpdateCounters_Post() {
+ RestOperationalStatistics ros = new RestOperationalStatistics();
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(101);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
+ ros.updateCounters(ntwTxn1);
+
+ result.setResultCode(201);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
+ ros.updateCounters(ntwTxn2);
+
+ result.setResultCode(301);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
+ ros.updateCounters(ntwTxn3);
+
+ result.setResultCode(401);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
+ ros.updateCounters(ntwTxn4);
+
+ result.setResultCode(501);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
+ ros.updateCounters(ntwTxn5);
+
+ result.setResultCode(601);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.POST, "entity-1", result);
+ ros.updateCounters(ntwTxn6);
+
+ String statistics = ros.getStatisticsReport();
+ Assert.assertNotNull(statistics);
+ }
+
+ @Test
+ public void testUpdateCounters_Delete() {
+ RestOperationalStatistics ros = new RestOperationalStatistics();
+
+ OperationResult result = new OperationResult();
+ result.setResultCode(101);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn1 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ ros.updateCounters(ntwTxn1);
+
+ result.setResultCode(201);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn2 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ ros.updateCounters(ntwTxn2);
+
+ result.setResultCode(301);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn3 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ ros.updateCounters(ntwTxn3);
+
+ result.setResultCode(401);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn4 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ ros.updateCounters(ntwTxn4);
+
+ result.setResultCode(501);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn5 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ ros.updateCounters(ntwTxn5);
+
+ result.setResultCode(601);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn6 = new NetworkTransaction(HttpMethod.DELETE, "entity-1", result);
+ ros.updateCounters(ntwTxn6);
+
+ String statistics = ros.getStatisticsReport();
+ Assert.assertNotNull(statistics);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java b/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java index fe6fa56..fabc32b 100644 --- a/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java @@ -46,7 +46,7 @@ import com.sun.jersey.api.client.WebResource.Builder; /** * The Class RestfulDataAccessorTest. */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class RestfulDataAccessorTest { private RestClientBuilder clientBuilderMock; @@ -54,7 +54,7 @@ public class RestfulDataAccessorTest { private ClientResponse mockClientResponse; private WebResource mockWebResource; private Builder mockBuilder; - + /** * Inits the. @@ -63,7 +63,7 @@ public class RestfulDataAccessorTest { */ @Before public void init() throws Exception { - + /* * common collaborator mocking setup */ diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java index 4d85bd6..3aaef43 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java @@ -30,14 +30,14 @@ import java.util.Map; public class DocumentEntity { private String etag; private String url; - private Map<String,String> content; + private Map<String, String> content; public DocumentEntity() { - content = new HashMap<String,String>(); + content = new HashMap<String, String>(); } - - - public String getEtag() { + + + public String getEtag() { return etag; } @@ -60,7 +60,7 @@ public class DocumentEntity { public void setContent(Map<String, String> content) { this.content = content; } - + public void addContent(String key, String value) { content.put(key, value); } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java index d6e9971..fe69f81 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java @@ -28,12 +28,12 @@ import java.util.HashMap; import java.util.Map; public class EntityCountResponse { - - private Map<String,String> shards; + + private Map<String, String> shards; private int count; - + public EntityCountResponse() { - this.shards = new HashMap<String,String>(); + this.shards = new HashMap<String, String>(); } public Map<String, String> getShards() { @@ -51,5 +51,5 @@ public class EntityCountResponse { public void setCount(int count) { this.count = count; } - + } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java index 0f1609b..9418cf5 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java @@ -32,7 +32,7 @@ import org.onap.aai.sparky.dal.elasticsearch.entity.BucketEntity; public class GroupByAggregationEntity { private int totalChartHits; List<BucketEntity> buckets; - + public GroupByAggregationEntity() { this.buckets = new ArrayList<BucketEntity>(); } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java index 0af4600..3f8cb69 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java @@ -30,9 +30,9 @@ public class GroupByAggregationResponseEntity { @JsonProperty("groupby_aggregation") private GroupByAggregationEntity aggEntity; - + public GroupByAggregationResponseEntity() { - + } public GroupByAggregationEntity getAggEntity() { @@ -42,7 +42,7 @@ public class GroupByAggregationResponseEntity { public void setAggEntity(GroupByAggregationEntity aggEntity) { this.aggEntity = aggEntity; } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java index 755e903..2340c0d 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java @@ -30,7 +30,7 @@ public class HitEntity { private DocumentEntity document; public String getScore() { - return score; + return score; } public void setScore(String score) { diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java index e815e0b..08bf76c 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java @@ -30,9 +30,9 @@ import java.util.Map; public class SearchAbstractionEntityBuilder { - + public static HitEntity getHitSample1() { - + HitEntity hitEntity = new HitEntity(); DocumentEntity doc = new DocumentEntity(); @@ -40,20 +40,23 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.073963"); doc.addContent("entityPrimaryKeyValue", "example-vnf-id-val-4394"); - doc.addContent("entityType", "vpe"); - doc.addContent("searchTags", "example-vnf-id-val-4394;example-vnf-name-val-4394;example-vnf-name2-val-4394"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/vpes/vpe/example-vnf-id-val-4394"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.072-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/e317a35256717f10e88d1b2c995efcdddfc911bf350c73e37e8afca6dfb11553"); + doc.addContent("entityType", "vpe"); + doc.addContent("searchTags", + "example-vnf-id-val-4394;example-vnf-name-val-4394;example-vnf-name2-val-4394"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/vpes/vpe/example-vnf-id-val-4394"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.072-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/e317a35256717f10e88d1b2c995efcdddfc911bf350c73e37e8afca6dfb11553"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample2() { HitEntity hitEntity = new HitEntity(); @@ -63,20 +66,22 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.073963"); doc.addContent("entityPrimaryKeyValue", "vpe-vnf-id-team4-11"); - doc.addContent("entityType", "vpe"); - doc.addContent("searchTags", "vpe-vnf-id-team4-11;example-vnf-name-val-9512;example-vnf-name2-val-9512"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/vpes/vpe/vpe-vnf-id-team4-11"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.175-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/80f6d1a252e047e50e0adbeb90ad30876bb5b63cf70c9dd53f3fe46aeb50c74b"); + doc.addContent("entityType", "vpe"); + doc.addContent("searchTags", + "vpe-vnf-id-team4-11;example-vnf-name-val-9512;example-vnf-name2-val-9512"); + doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/vpes/vpe/vpe-vnf-id-team4-11"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.175-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/80f6d1a252e047e50e0adbeb90ad30876bb5b63cf70c9dd53f3fe46aeb50c74b"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample3() { HitEntity hitEntity = new HitEntity(); @@ -86,20 +91,23 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.030035"); doc.addContent("entityPrimaryKeyValue", "example-vnf-id-val-6176"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "example-vnf-id-val-6176;example-vnf-name-val-6176;example-vnf-name2-val-6176"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/example-vnf-id-val-6176"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.889-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/8dfd1136f943296508fee11efcda35a0719aa490aa60e9abffecce0b220d8c94"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", + "example-vnf-id-val-6176;example-vnf-name-val-6176;example-vnf-name2-val-6176"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/example-vnf-id-val-6176"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.889-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/8dfd1136f943296508fee11efcda35a0719aa490aa60e9abffecce0b220d8c94"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample4() { HitEntity hitEntity = new HitEntity(); @@ -109,20 +117,23 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.01174"); doc.addContent("entityPrimaryKeyValue", "vnf-id-team4-11"); - doc.addContent("entityType", "newvce"); - doc.addContent("searchTags", "vnf-id-team4-11;example-vnf-name-val-5313;example-vnf-name2-val-5313"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/newvces/newvce/vnf-id-team4-11"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:21:08.142-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/83dcab92d75b20eb94578039c8cec5e7b6b4717791e3c367d8af5069ce76dc90"); + doc.addContent("entityType", "newvce"); + doc.addContent("searchTags", + "vnf-id-team4-11;example-vnf-name-val-5313;example-vnf-name2-val-5313"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/newvces/newvce/vnf-id-team4-11"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:21:08.142-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/83dcab92d75b20eb94578039c8cec5e7b6b4717791e3c367d8af5069ce76dc90"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample5() { HitEntity hitEntity = new HitEntity(); @@ -132,20 +143,23 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.01174"); doc.addContent("entityPrimaryKeyValue", "example-vnf-id2-val-9501"); - doc.addContent("entityType", "newvce"); - doc.addContent("searchTags", "example-vnf-id2-val-9501;example-vnf-name-val-9501;example-vnf-name2-val-9501"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/newvces/newvce/example-vnf-id2-val-9501"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:21:23.323-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/461816ba8aa94d01f2c978999b843dbaf10e0509db58d1945d6f5999d6db8f5e"); + doc.addContent("entityType", "newvce"); + doc.addContent("searchTags", + "example-vnf-id2-val-9501;example-vnf-name-val-9501;example-vnf-name2-val-9501"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/newvces/newvce/example-vnf-id2-val-9501"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:21:23.323-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/461816ba8aa94d01f2c978999b843dbaf10e0509db58d1945d6f5999d6db8f5e"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample6() { HitEntity hitEntity = new HitEntity(); @@ -155,20 +169,22 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.01174"); doc.addContent("entityPrimaryKeyValue", "vnf-id-dm-auto-10"); - doc.addContent("entityType", "vce"); - doc.addContent("searchTags", "vpe-id-dm-auto-10;vnf-id-dm-auto-10;vnf-name-dm-auto-10;vnf-name2-dm-auto-10"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/vces/vce/vnf-id-dm-auto-10"); - doc.addContent("searchTagIDs", "0;1;2;3"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:24:57.209-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1ead4512e65ee0eafb24e0156cc1abdf97368f08dfe065f02580aa09661bbcd8"); + doc.addContent("entityType", "vce"); + doc.addContent("searchTags", + "vpe-id-dm-auto-10;vnf-id-dm-auto-10;vnf-name-dm-auto-10;vnf-name2-dm-auto-10"); + doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/vces/vce/vnf-id-dm-auto-10"); + doc.addContent("searchTagIDs", "0;1;2;3"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:24:57.209-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1ead4512e65ee0eafb24e0156cc1abdf97368f08dfe065f02580aa09661bbcd8"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample7() { HitEntity hitEntity = new HitEntity(); @@ -178,20 +194,22 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.940832"); doc.addContent("entityPrimaryKeyValue", "e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7;VNF_Test_vNF_modules_01"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:26:34.603-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1462582e8fd7786f72f26548e4247b72ab6cd101cca0bbb68a60dd3ad16500d0"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7;VNF_Test_vNF_modules_01"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:26:34.603-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1462582e8fd7786f72f26548e4247b72ab6cd101cca0bbb68a60dd3ad16500d0"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample8() { HitEntity hitEntity = new HitEntity(); @@ -201,20 +219,22 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.940832"); doc.addContent("entityPrimaryKeyValue", "fusion-jitsi-vnf-001"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "fusion-jitsi-vnf-001;fusion-jitsi-vnf"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/fusion-jitsi-vnf-001"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:28:14.293-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/b79ddfec9a00184445174c91e7490a0d407f351983bba4ae53bfec0584f73ee3"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "fusion-jitsi-vnf-001;fusion-jitsi-vnf"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/fusion-jitsi-vnf-001"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:28:14.293-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/b79ddfec9a00184445174c91e7490a0d407f351983bba4ae53bfec0584f73ee3"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample9() { HitEntity hitEntity = new HitEntity(); @@ -224,20 +244,22 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.940832"); doc.addContent("entityPrimaryKeyValue", "vnfm0003v"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "vnfm0003v;vnfm0003v"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/vnfm0003v"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.594-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/52ae232ea5506d6de8ef35c4f46a1ceafe35f3717ff578b83531bc7615870b12"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "vnfm0003v;vnfm0003v"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/vnfm0003v"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.594-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/52ae232ea5506d6de8ef35c4f46a1ceafe35f3717ff578b83531bc7615870b12"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample10() { HitEntity hitEntity = new HitEntity(); @@ -247,33 +269,35 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.928098"); doc.addContent("entityPrimaryKeyValue", "amist456vnf"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "amist456vnf;amist456vnf"); - doc.addContent("link", "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/amist456vnf"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:28:28.163-0400"); - - doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/3424afea5963696380a0fdc78ee5320cf5fa9bc0459f1f9376db208d31196434"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "amist456vnf;amist456vnf"); + doc.addContent("link", + "https://aai-hostname:8443/aai/v9/network/generic-vnfs/generic-vnf/amist456vnf"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:28:28.163-0400"); + + doc.setUrl( + "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/3424afea5963696380a0fdc78ee5320cf5fa9bc0459f1f9376db208d31196434"); doc.setEtag("1"); return hitEntity; } - - - + + + public static SearchAbstractionResponse getSuccessfulEntitySearchResponse() { - + SearchAbstractionResponse sasResponse = new SearchAbstractionResponse(); - + SearchResult searchResult = new SearchResult(); sasResponse.setSearchResult(searchResult); - + searchResult.setTotalHits(3257); - + List<HitEntity> hits = new ArrayList<HitEntity>(); - + hits.add(getHitSample1()); hits.add(getHitSample2()); hits.add(getHitSample3()); @@ -284,12 +308,12 @@ public class SearchAbstractionEntityBuilder { hits.add(getHitSample8()); hits.add(getHitSample9()); hits.add(getHitSample10()); - + searchResult.setHits(hits); - + return sasResponse; - + } - + } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java index d3d4a4c..547b61e 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java @@ -25,13 +25,13 @@ package org.onap.aai.sparky.dal.sas.entity; public class SearchAbstractionResponse { - + private SearchResult searchResult; public SearchResult getSearchResult() { return searchResult; } - + public void setSearchResult(SearchResult searchResult) { this.searchResult = searchResult; } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java index e484fa6..255413d 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java @@ -30,20 +30,23 @@ public class SearchResult { private int totalHits; private List<HitEntity> hits; - - public int getTotalHits() { + + public int getTotalHits() { return totalHits; } + public void setTotalHits(int totalHits) { this.totalHits = totalHits; } + public List<HitEntity> getHits() { return hits; } + public void setHits(List<HitEntity> hits) { this.hits = hits; } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/search/VnfSearchQueryBuilderTest.java b/src/test/java/org/onap/aai/sparky/search/VnfSearchQueryBuilderTest.java index 19a0a3a..99b20c1 100644 --- a/src/test/java/org/onap/aai/sparky/search/VnfSearchQueryBuilderTest.java +++ b/src/test/java/org/onap/aai/sparky/search/VnfSearchQueryBuilderTest.java @@ -34,42 +34,44 @@ import org.onap.aai.sparky.search.VnfSearchQueryBuilder; public class VnfSearchQueryBuilderTest {
- @Test
- public void testCreateSuggestionsQuery() {
- String maxResults = "maxResults-1";
- String queryStr = "queryStr-1";
- JsonObject object = VnfSearchQueryBuilder.createSuggestionsQuery(maxResults, queryStr);
- Assert.assertNotNull(object);
- }
-
- @Test
- public void testSortCriteria() {
- JsonArray array = VnfSearchQueryBuilder.getSortCriteria("field-1", "sortOrder-1");
- Assert.assertNotNull(array);
- }
-
- @Test
- public void testCreateEntityCountsQuery_SingleAttribute() {
- Map<String, String> attributes = new HashMap<>();
- attributes.put("key-1", "value-1");
- JsonObject object = VnfSearchQueryBuilder.createEntityCountsQuery(attributes);
- Assert.assertNotNull(object);
- }
-
- @Test
- public void testCreateSummaryByEntityTypeQuery_Single() {
- Map<String, String> attributes = new HashMap<>();
- attributes.put("key-1", "value-1");
- JsonObject object = VnfSearchQueryBuilder.createSummaryByEntityTypeQuery(attributes, "groupkey-1");
- Assert.assertNotNull(object);
- }
-
- @Test
- public void testCreateSummaryByEntityTypeQuery_Multiple() {
- Map<String, String> attributes = new HashMap<>();
- attributes.put("key-1", "value-1");
- attributes.put("key-2", "value-2");
- JsonObject object = VnfSearchQueryBuilder.createSummaryByEntityTypeQuery(attributes, "groupkey-1");
- Assert.assertNotNull(object);
- }
+ @Test
+ public void testCreateSuggestionsQuery() {
+ String maxResults = "maxResults-1";
+ String queryStr = "queryStr-1";
+ JsonObject object = VnfSearchQueryBuilder.createSuggestionsQuery(maxResults, queryStr);
+ Assert.assertNotNull(object);
+ }
+
+ @Test
+ public void testSortCriteria() {
+ JsonArray array = VnfSearchQueryBuilder.getSortCriteria("field-1", "sortOrder-1");
+ Assert.assertNotNull(array);
+ }
+
+ @Test
+ public void testCreateEntityCountsQuery_SingleAttribute() {
+ Map<String, String> attributes = new HashMap<>();
+ attributes.put("key-1", "value-1");
+ JsonObject object = VnfSearchQueryBuilder.createEntityCountsQuery(attributes);
+ Assert.assertNotNull(object);
+ }
+
+ @Test
+ public void testCreateSummaryByEntityTypeQuery_Single() {
+ Map<String, String> attributes = new HashMap<>();
+ attributes.put("key-1", "value-1");
+ JsonObject object =
+ VnfSearchQueryBuilder.createSummaryByEntityTypeQuery(attributes, "groupkey-1");
+ Assert.assertNotNull(object);
+ }
+
+ @Test
+ public void testCreateSummaryByEntityTypeQuery_Multiple() {
+ Map<String, String> attributes = new HashMap<>();
+ attributes.put("key-1", "value-1");
+ attributes.put("key-2", "value-2");
+ JsonObject object =
+ VnfSearchQueryBuilder.createSummaryByEntityTypeQuery(attributes, "groupkey-1");
+ Assert.assertNotNull(object);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/search/VnfSearchServiceTest.java b/src/test/java/org/onap/aai/sparky/search/VnfSearchServiceTest.java index 8c4d59d..ed77e25 100644 --- a/src/test/java/org/onap/aai/sparky/search/VnfSearchServiceTest.java +++ b/src/test/java/org/onap/aai/sparky/search/VnfSearchServiceTest.java @@ -41,49 +41,54 @@ import org.onap.aai.sparky.viewandinspect.entity.QuerySearchEntity; public class VnfSearchServiceTest {
- VnfSearchService searchService;
-
- @Before
- public void init() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException {
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/";
- ElasticSearchConfig.setConfig(null);
- setFinalStatic();
- searchService = new VnfSearchService();
- }
- @Test
- public void testSetZeroCountResponse() throws IOException {
- HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
- Mockito.doNothing().when(response).setStatus(1);
- Mockito.doNothing().when(response).setContentType(Mockito.anyString());
- PrintWriter writer = Mockito.mock(PrintWriter.class);
- Mockito.doNothing().when(writer).println(Mockito.anyString());
- Mockito.doNothing().when(writer).close();
- Mockito.when(response.getWriter()).thenReturn(writer);
- searchService.setZeroCountResponse(response);
- }
-
- @Test
- public void testSetEmptyAggResponse() throws IOException {
- HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
- Mockito.doNothing().when(response).setStatus(1);
- Mockito.doNothing().when(response).setContentType(Mockito.anyString());
- PrintWriter writer = Mockito.mock(PrintWriter.class);
- Mockito.doNothing().when(writer).println(Mockito.anyString());
- Mockito.doNothing().when(writer).close();
- Mockito.when(response.getWriter()).thenReturn(writer);
- searchService.setEmptyAggResponse(response);
- }
-
-
- static void setFinalStatic() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
- Field configField = ElasticSearchConfig.class.getDeclaredField("CONFIG_FILE");
- configField.setAccessible(true);
+ VnfSearchService searchService;
- Field modifiersField = Field.class.getDeclaredField( "modifiers" );
- modifiersField.setAccessible( true );
- modifiersField.setInt( configField, configField.getModifiers() & ~Modifier.FINAL );
+ @Before
+ public void init() throws NoSuchFieldException, SecurityException, IllegalArgumentException,
+ IllegalAccessException, IOException {
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/";
+ ElasticSearchConfig.setConfig(null);
+ setFinalStatic();
+ searchService = new VnfSearchService();
+ }
- configField.set(null, System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/elasticsearch.properties");
- }
+ @Test
+ public void testSetZeroCountResponse() throws IOException {
+ HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
+ Mockito.doNothing().when(response).setStatus(1);
+ Mockito.doNothing().when(response).setContentType(Mockito.anyString());
+ PrintWriter writer = Mockito.mock(PrintWriter.class);
+ Mockito.doNothing().when(writer).println(Mockito.anyString());
+ Mockito.doNothing().when(writer).close();
+ Mockito.when(response.getWriter()).thenReturn(writer);
+ searchService.setZeroCountResponse(response);
+ }
+
+ @Test
+ public void testSetEmptyAggResponse() throws IOException {
+ HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
+ Mockito.doNothing().when(response).setStatus(1);
+ Mockito.doNothing().when(response).setContentType(Mockito.anyString());
+ PrintWriter writer = Mockito.mock(PrintWriter.class);
+ Mockito.doNothing().when(writer).println(Mockito.anyString());
+ Mockito.doNothing().when(writer).close();
+ Mockito.when(response.getWriter()).thenReturn(writer);
+ searchService.setEmptyAggResponse(response);
+ }
+
+
+ static void setFinalStatic() throws NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException {
+ Field configField = ElasticSearchConfig.class.getDeclaredField("CONFIG_FILE");
+ configField.setAccessible(true);
+
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(configField, configField.getModifiers() & ~Modifier.FINAL);
+
+ configField.set(null,
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/elasticsearch.properties");
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java b/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java index aa37d42..062aa04 100644 --- a/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java +++ b/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java @@ -47,7 +47,7 @@ public class FilteredSearchHelperTest { config.setViewsConfig(config.readUiViewsConfig()); System.out.println("SETTING UIFILTERSCONFIG"); config.setFiltersConfig(config.readUiFiltersConfig()); - + filteredSearchHelper = new FilteredSearchHelper(config); } diff --git a/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java b/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java index 336e3b1..f836821 100644 --- a/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java +++ b/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java @@ -36,5 +36,5 @@ public class DiscoverFiltersRequest { public void setViewName(String viewName) { this.viewName = viewName; } - + } diff --git a/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java b/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java index 815199f..a84748b 100644 --- a/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java +++ b/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java @@ -63,9 +63,9 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; -@PowerMockIgnore({ "javax.crypto.*" }) +@PowerMockIgnore({"javax.crypto.*"}) @RunWith(PowerMockRunner.class) -@PrepareForTest({ PortalAuthenticationConfig.class, RolesConfig.class }) +@PrepareForTest({PortalAuthenticationConfig.class, RolesConfig.class}) public class TestPortalRestAPIServiceImpl { private static File testUsersFile; @@ -75,13 +75,19 @@ public class TestPortalRestAPIServiceImpl { enum TestData { // @formatter:off - TEST_USERS ("src/test/resources/portal/test-users.config"), - PORTAL_AUTHENTICATION_PROPERTIES ("src/test/resources/portal/portal-authentication.properties"), - ROLES_CONFIG_FILE ("src/test/resources/portal/roles.config"); + TEST_USERS("src/test/resources/portal/test-users.config"), PORTAL_AUTHENTICATION_PROPERTIES( + "src/test/resources/portal/portal-authentication.properties"), ROLES_CONFIG_FILE( + "src/test/resources/portal/roles.config"); private String filename; - TestData(String filename) {this.filename = filename;} - public String getFilename() {return this.filename;} + + TestData(String filename) { + this.filename = filename; + } + + public String getFilename() { + return this.filename; + } // @formatter:on } @@ -268,4 +274,4 @@ public class TestPortalRestAPIServiceImpl { assertThat(userWithNoRoles.getRoles(), empty()); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java b/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java index 16669fd..2bc06ef 100644 --- a/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java +++ b/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java @@ -54,7 +54,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import com.google.gson.Gson; @RunWith(PowerMockRunner.class) -//@PrepareForTest(RolesConfig.class) +// @PrepareForTest(RolesConfig.class) public class TestUserManager { private static final String LOGINID_3 = "3"; @@ -68,14 +68,20 @@ public class TestUserManager { enum TestData { // @formatter:off - NO_FILE ("src/test/resources/portal/no-users.config"), - CONCURRENT_USERS ("src/test/resources/portal/concurrent-users.config"), - CONCURRENT_EDIT_USERS ("src/test/resources/portal/concurrent-edit-users.config"); -// ROLES_CONFIG_FILE ("src/test/resources/portal/roles.config"); + NO_FILE("src/test/resources/portal/no-users.config"), CONCURRENT_USERS( + "src/test/resources/portal/concurrent-users.config"), CONCURRENT_EDIT_USERS( + "src/test/resources/portal/concurrent-edit-users.config"); + // ROLES_CONFIG_FILE ("src/test/resources/portal/roles.config"); private String filename; - TestData(String filename) {this.filename = filename;} - public String getFilename() {return this.filename;} + + TestData(String filename) { + this.filename = filename; + } + + public String getFilename() { + return this.filename; + } // @formatter:on } @@ -103,8 +109,8 @@ public class TestUserManager { List<EcompUser> users = Arrays.asList(user1, user2); Files.write(concurrentEditUsers.toPath(), GSON.toJson(users).getBytes()); -// Whitebox.setInternalState(RolesConfig.class, "ROLES_CONFIG_FILE", -// TestData.ROLES_CONFIG_FILE.getFilename()); + // Whitebox.setInternalState(RolesConfig.class, "ROLES_CONFIG_FILE", + // TestData.ROLES_CONFIG_FILE.getFilename()); } @After @@ -127,8 +133,8 @@ public class TestUserManager { return pushTask(concurrentUsers, String.valueOf(NodeUtils.getRandomTxnId())); }; - List<Callable<EcompUser>> callables = Arrays.asList(pushTask, pushTask, pushTask, pushTask, - pushTask); + List<Callable<EcompUser>> callables = + Arrays.asList(pushTask, pushTask, pushTask, pushTask, pushTask); ExecutorService executor = Executors.newWorkStealingPool(); executor.invokeAll(callables).stream().map(future -> { @@ -165,9 +171,9 @@ public class TestUserManager { return editTask(LOGINID_3, "Amy"); }; - List<Callable<EcompUser>> callables = Arrays.asList(pushTaskRandomId, pushTaskRandomId, - pushTaskId3, editTaskId1, pushTaskRandomId, pushTaskRandomId, editTaskId3, editTaskId2, - pushTaskRandomId); + List<Callable<EcompUser>> callables = + Arrays.asList(pushTaskRandomId, pushTaskRandomId, pushTaskId3, editTaskId1, + pushTaskRandomId, pushTaskRandomId, editTaskId3, editTaskId2, pushTaskRandomId); ExecutorService executor = Executors.newWorkStealingPool(); List<EcompUser> userTasks = executor.invokeAll(callables).stream().map(future -> { @@ -203,4 +209,4 @@ public class TestUserManager { userManager.editUser(loginId, user); return user; } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizerTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizerTest.java index e590af6..b903851 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizerTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/AggregationSuggestionSynchronizerTest.java @@ -40,47 +40,52 @@ import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants; public class AggregationSuggestionSynchronizerTest {
- @Before
- public void init() throws IOException {
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/";
- // TierSupportUiConstants.CONFIG_OXM_LOCATION = System.getProperty("AJSC_HOME")+"/bundleconfig-local/oxm/";
- }
-
- @Test
- public void testDoSync() throws Exception {
- ElasticSearchConfig.setConfig(null);
- setFinalStatic();
- AggregationSuggestionSynchronizer ass = new AggregationSuggestionSynchronizer("entity-search-index");
- Assert.assertNotNull(ass);
- OperationState state = ass.doSync();
- Assert.assertEquals(OperationState.OK, state);
+ @Before
+ public void init() throws IOException {
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/";
+ // TierSupportUiConstants.CONFIG_OXM_LOCATION =
+ // System.getProperty("AJSC_HOME")+"/bundleconfig-local/oxm/";
+ }
- OperationResult result = new OperationResult();
- result.setResultCode(200);
- result.setResult("result-1");
- result.setNumRequestRetries(1);
- NetworkTransaction ntwTxn = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
- ass.updateElasticSearchCounters(ntwTxn);
+ @Test
+ public void testDoSync() throws Exception {
+ ElasticSearchConfig.setConfig(null);
+ setFinalStatic();
+ AggregationSuggestionSynchronizer ass =
+ new AggregationSuggestionSynchronizer("entity-search-index");
+ Assert.assertNotNull(ass);
+ OperationState state = ass.doSync();
+ Assert.assertEquals(OperationState.OK, state);
- SynchronizerState syncState = ass.getState();
- Assert.assertEquals(SynchronizerState.IDLE, syncState);
-
- String statReport = ass.getStatReport(true);
- Assert.assertNotNull(statReport);
- Assert.assertTrue(statReport.contains("Aggregation Suggestion Synchronizer"));
-
- ass.shutdown();
- }
+ OperationResult result = new OperationResult();
+ result.setResultCode(200);
+ result.setResult("result-1");
+ result.setNumRequestRetries(1);
+ NetworkTransaction ntwTxn = new NetworkTransaction(HttpMethod.GET, "entity-1", result);
+ ass.updateElasticSearchCounters(ntwTxn);
- static void setFinalStatic() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
- Field configField = ElasticSearchConfig.class.getDeclaredField("CONFIG_FILE");
- configField.setAccessible(true);
+ SynchronizerState syncState = ass.getState();
+ Assert.assertEquals(SynchronizerState.IDLE, syncState);
- Field modifiersField = Field.class.getDeclaredField( "modifiers" );
- modifiersField.setAccessible( true );
- modifiersField.setInt( configField, configField.getModifiers() & ~Modifier.FINAL );
+ String statReport = ass.getStatReport(true);
+ Assert.assertNotNull(statReport);
+ Assert.assertTrue(statReport.contains("Aggregation Suggestion Synchronizer"));
- configField.set(null, System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/elasticsearch.properties");
- }
+ ass.shutdown();
+ }
+
+ static void setFinalStatic() throws NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException {
+ Field configField = ElasticSearchConfig.class.getDeclaredField("CONFIG_FILE");
+ configField.setAccessible(true);
+
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(configField, configField.getModifiers() & ~Modifier.FINAL);
+
+ configField.set(null,
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/elasticsearch.properties");
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java index 822e927..1e14d38 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java @@ -42,7 +42,7 @@ import ch.qos.logback.classic.Level; /** * The Class IndexDocumentTest. */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class IndexDocumentTest { private LogValidator logValidator; diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java index e97da4f..907ff23 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java @@ -130,7 +130,7 @@ public class SyncControllerBuilder { ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); IndexIntegrityValidator entityCounterHistoryValidator = @@ -211,7 +211,7 @@ public class SyncControllerBuilder { RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(nonCachingRestProvider, esConfig.getIndexName(), @@ -266,7 +266,7 @@ public class SyncControllerBuilder { */ public void doSearchableEntitysync() { try { - + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); @@ -286,10 +286,10 @@ public class SyncControllerBuilder { RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); ////// - + SyncController syncController = new SyncController("searchtableEntityTestController"); SearchableEntitySynchronizer ses = @@ -340,7 +340,7 @@ public class SyncControllerBuilder { */ public void doCrossEntityReferenceSync() { try { - + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); @@ -360,12 +360,12 @@ public class SyncControllerBuilder { RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); SyncController syncController = new SyncController("crossEntityRefSyncController"); - CrossEntityReferenceSynchronizer cers = - new CrossEntityReferenceSynchronizer("entitysearchindex-localhost", ActiveInventoryConfig.getConfig()); + CrossEntityReferenceSynchronizer cers = new CrossEntityReferenceSynchronizer( + "entitysearchindex-localhost", ActiveInventoryConfig.getConfig()); cers.setAaiDataProvider(aaiAdapter); cers.setEsDataProvider(esAdapter); syncController.registerEntitySynchronizer(cers); @@ -413,7 +413,7 @@ public class SyncControllerBuilder { */ public void doSuggestionEntitySync() { try { - + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); @@ -433,8 +433,8 @@ public class SyncControllerBuilder { RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); - + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); + SyncController syncController = new SyncController("suggestionEntityTestController"); AutosuggestionSynchronizer ses = @@ -456,7 +456,7 @@ public class SyncControllerBuilder { System.out.println("Error: failed to sync with message = " + exc.getMessage()); } } - + /* * Do no op sync. */ diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerTest.java index c7464d3..bc268df 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerTest.java @@ -29,53 +29,58 @@ import org.onap.aai.sparky.synchronizer.SyncController.SyncActions; public class SyncControllerTest {
- SyncController controller;
+ SyncController controller;
- @Before
- public void init() throws Exception {
- controller = new SyncController("name-1");
- }
- @Test
- public void testPerformAction_PreSync() {
- controller.performAction(SyncActions.SYNCHRONIZE);
- controller.shutdown();
- }
+ @Before
+ public void init() throws Exception {
+ controller = new SyncController("name-1");
+ }
- @Test
- public void testRegisterIndexCleaner_NullIndexName() {
- IndexCleaner cleaner = new ElasticSearchIndexCleaner(null, null, "index_type-1", "host-1", "port-1", 1, 1);
- controller.registerIndexCleaner(cleaner);
- }
+ @Test
+ public void testPerformAction_PreSync() {
+ controller.performAction(SyncActions.SYNCHRONIZE);
+ controller.shutdown();
+ }
- @Test
- public void testRegisterIndexCleaner_NotNullIndexName() {
- IndexCleaner cleaner = new ElasticSearchIndexCleaner(null, "index-1", "index_type-1", "host-1", "port-1", 1, 1);
- controller.registerIndexCleaner(cleaner);
- }
+ @Test
+ public void testRegisterIndexCleaner_NullIndexName() {
+ IndexCleaner cleaner =
+ new ElasticSearchIndexCleaner(null, null, "index_type-1", "host-1", "port-1", 1, 1);
+ controller.registerIndexCleaner(cleaner);
+ }
- @Test
- public void testRegisterIndexValidator_NullIndexValidator() {
- IndexValidator validator = new IndexIntegrityValidator(null, null, "index_type-1", "host-1", "port-1", "json-1");
- controller.registerIndexValidator(validator);
- }
+ @Test
+ public void testRegisterIndexCleaner_NotNullIndexName() {
+ IndexCleaner cleaner =
+ new ElasticSearchIndexCleaner(null, "index-1", "index_type-1", "host-1", "port-1", 1, 1);
+ controller.registerIndexCleaner(cleaner);
+ }
- @Test
- public void testRegisterIndexValidator_NotNullIndexValidator() {
- IndexValidator validator = new IndexIntegrityValidator(null, "index-1", "index_type-1", "host-1", "port-1", "json-1");
- controller.registerIndexValidator(validator);
- }
+ @Test
+ public void testRegisterIndexValidator_NullIndexValidator() {
+ IndexValidator validator =
+ new IndexIntegrityValidator(null, null, "index_type-1", "host-1", "port-1", "json-1");
+ controller.registerIndexValidator(validator);
+ }
- @Test
- public void testRegisterEntitySynchronizer_NullEntitySynchronizer() throws Exception {
- IndexSynchronizer synchroniser = Mockito.mock(SearchableEntitySynchronizer.class);
- Mockito.when(synchroniser.getIndexName()).thenReturn(null);
- controller.registerEntitySynchronizer(synchroniser);
- }
+ @Test
+ public void testRegisterIndexValidator_NotNullIndexValidator() {
+ IndexValidator validator =
+ new IndexIntegrityValidator(null, "index-1", "index_type-1", "host-1", "port-1", "json-1");
+ controller.registerIndexValidator(validator);
+ }
- @Test
- public void testRegisterEntitySynchronizer_NotNullEntitySynchronizer() throws Exception {
- IndexSynchronizer synchroniser = Mockito.mock(SearchableEntitySynchronizer.class);
- Mockito.when(synchroniser.getIndexName()).thenReturn("entity-1");
- controller.registerEntitySynchronizer(synchroniser);
- }
+ @Test
+ public void testRegisterEntitySynchronizer_NullEntitySynchronizer() throws Exception {
+ IndexSynchronizer synchroniser = Mockito.mock(SearchableEntitySynchronizer.class);
+ Mockito.when(synchroniser.getIndexName()).thenReturn(null);
+ controller.registerEntitySynchronizer(synchroniser);
+ }
+
+ @Test
+ public void testRegisterEntitySynchronizer_NotNullEntitySynchronizer() throws Exception {
+ IndexSynchronizer synchroniser = Mockito.mock(SearchableEntitySynchronizer.class);
+ Mockito.when(synchroniser.getIndexName()).thenReturn("entity-1");
+ controller.registerEntitySynchronizer(synchroniser);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/SyncHelperTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/SyncHelperTest.java index 5a2584f..46e6350 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/SyncHelperTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/SyncHelperTest.java @@ -45,74 +45,82 @@ import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants; @RunWith(MockitoJUnitRunner.class)
public class SyncHelperTest {
- private SyncHelper syncHelper;
-
- @BeforeClass
- public static void initBeforeClass() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
- String configHomePath =
- (new File(".").getCanonicalPath() + "/src/test/resources/appconfig/").replace('\\', '/');
- TierSupportUiConstants.AJSC_HOME = configHomePath;
- TierSupportUiConstants.CONFIG_HOME = configHomePath;
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = configHomePath;
- ElasticSearchConfig.setConfig(null);
- SynchronizerConfiguration.setInstance(null);
- setFinalStatic();
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/";
- }
-
-
- @Test
- public void testGetOxmModelLoader() throws Exception {
- syncHelper = new SyncHelper(new OxmModelLoader());
- OxmModelLoader oxmLoader = new OxmModelLoader();
- syncHelper.setOxmModelLoader(oxmLoader);
- assertEquals(oxmLoader, syncHelper.getOxmModelLoader());
- }
-
- @Test
- public void testGetFirstSyncTime(){
- SyncHelper syncHelper = new SyncHelper(new OxmModelLoader());
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
- TimeZone tz = TimeZone.getTimeZone("05:00:00 GMT+00:00");
- Calendar calendar = Calendar.getInstance(tz);
- sdf.setTimeZone(tz);
-
- calendar.set(Calendar.HOUR_OF_DAY, 1);
- calendar.set(Calendar.MINUTE, 1);
- calendar.set(Calendar.SECOND, 1);
-
- long timeCurrent = calendar.getTimeInMillis();
- int taskFrequencyInDay = 2;
-
- assertEquals(calendar.getTimeInMillis(), syncHelper.getFirstSyncTime(calendar, timeCurrent, taskFrequencyInDay));
- taskFrequencyInDay = 0;
- assertEquals(SynchronizerConstants.DELAY_NO_PERIODIC_SYNC_IN_MS, syncHelper.getFirstSyncTime(calendar, timeCurrent, taskFrequencyInDay));
- timeCurrent = timeCurrent + 100;
- taskFrequencyInDay = 2;
- Calendar expCalendar = calendar;
- expCalendar.add(Calendar.DAY_OF_MONTH, taskFrequencyInDay);
- //assertEquals(expCalendar.getTimeInMillis(), syncHelper.getFirstSyncTime(calendar, calendar.getTimeInMillis() + 100, taskFrequencyInDay));
-
- }
-
- static void setFinalStatic() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
- Field configField = ElasticSearchConfig.class.getDeclaredField("CONFIG_FILE");
- configField.setAccessible(true);
-
- Field modifiersField = Field.class.getDeclaredField( "modifiers" );
- modifiersField.setAccessible( true );
- modifiersField.setInt( configField, configField.getModifiers() & ~Modifier.FINAL );
-
- configField.set(null, System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/elasticsearch.properties");
-
- Field syncField = SynchronizerConfiguration.class.getDeclaredField("CONFIG_FILE");
- syncField.setAccessible(true);
-
- Field syncModifiersField = Field.class.getDeclaredField( "modifiers" );
- syncModifiersField.setAccessible( true );
- syncModifiersField.setInt( syncField, syncField.getModifiers() & ~Modifier.FINAL );
-
- syncField.set(null, System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/synchronizer.properties");
- }
+ private SyncHelper syncHelper;
+
+ @BeforeClass
+ public static void initBeforeClass() throws IOException, NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException {
+ String configHomePath =
+ (new File(".").getCanonicalPath() + "/src/test/resources/appconfig/").replace('\\', '/');
+ TierSupportUiConstants.AJSC_HOME = configHomePath;
+ TierSupportUiConstants.CONFIG_HOME = configHomePath;
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = configHomePath;
+ ElasticSearchConfig.setConfig(null);
+ SynchronizerConfiguration.setInstance(null);
+ setFinalStatic();
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/";
+ }
+
+
+ @Test
+ public void testGetOxmModelLoader() throws Exception {
+ syncHelper = new SyncHelper(new OxmModelLoader());
+ OxmModelLoader oxmLoader = new OxmModelLoader();
+ syncHelper.setOxmModelLoader(oxmLoader);
+ assertEquals(oxmLoader, syncHelper.getOxmModelLoader());
+ }
+
+ @Test
+ public void testGetFirstSyncTime() {
+ SyncHelper syncHelper = new SyncHelper(new OxmModelLoader());
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
+ TimeZone tz = TimeZone.getTimeZone("05:00:00 GMT+00:00");
+ Calendar calendar = Calendar.getInstance(tz);
+ sdf.setTimeZone(tz);
+
+ calendar.set(Calendar.HOUR_OF_DAY, 1);
+ calendar.set(Calendar.MINUTE, 1);
+ calendar.set(Calendar.SECOND, 1);
+
+ long timeCurrent = calendar.getTimeInMillis();
+ int taskFrequencyInDay = 2;
+
+ assertEquals(calendar.getTimeInMillis(),
+ syncHelper.getFirstSyncTime(calendar, timeCurrent, taskFrequencyInDay));
+ taskFrequencyInDay = 0;
+ assertEquals(SynchronizerConstants.DELAY_NO_PERIODIC_SYNC_IN_MS,
+ syncHelper.getFirstSyncTime(calendar, timeCurrent, taskFrequencyInDay));
+ timeCurrent = timeCurrent + 100;
+ taskFrequencyInDay = 2;
+ Calendar expCalendar = calendar;
+ expCalendar.add(Calendar.DAY_OF_MONTH, taskFrequencyInDay);
+ // assertEquals(expCalendar.getTimeInMillis(), syncHelper.getFirstSyncTime(calendar,
+ // calendar.getTimeInMillis() + 100, taskFrequencyInDay));
+
+ }
+
+ static void setFinalStatic() throws NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException {
+ Field configField = ElasticSearchConfig.class.getDeclaredField("CONFIG_FILE");
+ configField.setAccessible(true);
+
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(configField, configField.getModifiers() & ~Modifier.FINAL);
+
+ configField.set(null,
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/elasticsearch.properties");
+
+ Field syncField = SynchronizerConfiguration.class.getDeclaredField("CONFIG_FILE");
+ syncField.setAccessible(true);
+
+ Field syncModifiersField = Field.class.getDeclaredField("modifiers");
+ syncModifiersField.setAccessible(true);
+ syncModifiersField.setInt(syncField, syncField.getModifiers() & ~Modifier.FINAL);
+
+ syncField.set(null,
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/synchronizer.properties");
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfigurationTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfigurationTest.java index b61eebd..228b048 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfigurationTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfigurationTest.java @@ -14,11 +14,11 @@ import org.junit.Test; public class SynchronizerConfigurationTest { private SynchronizerConfiguration config; - + private Properties generateTestProperties() { - + Properties props = new Properties(); - + props.put("synchronizer.syncTask.initialDelayInMs", "60000"); props.put("synchronizer.syncTask.taskFrequencyInDay", "2"); props.put("synchronizer.syncTask.startTimestamp", "05:00:00 UTC+00:00"); @@ -35,21 +35,21 @@ public class SynchronizerConfigurationTest { props.put("synchronizer.suppressResourceNotFoundErrors", "true"); props.put("synchronizer.applyNodesOnlyModifier", "false"); props.put("synchronizer.autosuggestSynchronizationEnabled", "true"); - + return props; } - - + + @Before public void init() throws Exception { - + config = new SynchronizerConfiguration(generateTestProperties()); } @Test public void validateAccessors() { - + assertEquals(60000, config.getSyncTaskInitialDelayInMs()); assertEquals(2, config.getSyncTaskFrequencyInDay()); assertEquals("05:00:00 UTC+00:00", config.getSyncTaskStartTime()); @@ -57,7 +57,7 @@ public class SynchronizerConfigurationTest { assertEquals(0, config.getSyncTaskStartTimeMin()); assertEquals(0, config.getSyncTaskStartTimeSec()); assertEquals(true, config.isAutosuggestSynchronizationEnabled()); - assertEquals(false, config.isConfigDisabledForInitialSync() ); + assertEquals(false, config.isConfigDisabledForInitialSync()); assertEquals(true, config.isConfigOkForPeriodicSync()); assertEquals(true, config.isConfigOkForStartupSync()); assertEquals(false, config.isDisplayVerboseQueueManagerStats()); @@ -72,177 +72,176 @@ public class SynchronizerConfigurationTest { assertEquals(1000, config.getResolverQueueMonitorFrequencyInMs()); assertEquals(3600000, config.getIndexIntegrityValidatorFrequencyInMs()); assertTrue(config.toString().startsWith("SynchronizerConfiguration")); - - + + config.setSyncTaskInitialDelayInMs(1234); assertEquals(1234, config.getSyncTaskInitialDelayInMs()); - + config.setSyncTaskFrequencyInDay(5); assertEquals(5, config.getSyncTaskFrequencyInDay()); config.setSyncTaskStartTime("06:10:22 UTC+00:00"); assertEquals("06:10:22 UTC+00:00", config.getSyncTaskStartTime()); - + config.setSyncTaskStartTimeHr(6); assertEquals(6, config.getSyncTaskStartTimeHr()); - + config.setSyncTaskStartTimeMin(10); assertEquals(10, config.getSyncTaskStartTimeMin()); config.setSyncTaskStartTimeSec(22); assertEquals(22, config.getSyncTaskStartTimeSec()); - + config.setAutosuggestSynchronizationEnabled(false); assertEquals(false, config.isAutosuggestSynchronizationEnabled()); - + config.setDisplayVerboseQueueManagerStats(true); assertEquals(true, config.isDisplayVerboseQueueManagerStats()); - - + + config.setIndexIntegrityValidatorEnabled(true); assertEquals(true, config.isIndexIntegrityValidatorEnabled()); - + config.setNodesOnlyModifierEnabled(true); assertEquals(true, config.isNodesOnlyModifierEnabled()); config.setResourceNotFoundErrorsSupressed(false); assertEquals(false, config.isResourceNotFoundErrorsSupressed()); - + config.setNumScrollContextItemsToRetrievePerRequest(1234); assertEquals(1234, config.getNumScrollContextItemsToRetrievePerRequest()); - + config.setScrollContextTimeToLiveInMinutes(11); assertEquals(11, config.getScrollContextTimeToLiveInMinutes()); - - + + config.setSyncTaskStartTimeTimeZone("EST"); assertEquals("EST", config.getSyncTaskStartTimeTimeZone()); - + config.setSyncTaskFrequencyInMs(1221); assertEquals(1221, config.getSyncTaskFrequencyInMs()); - + config.setResolverProgressLogFrequencyInMs(1111); assertEquals(1111, config.getResolverProgressLogFrequencyInMs()); - + config.setResolverQueueMonitorFrequencyInMs(1111); assertEquals(1111, config.getResolverQueueMonitorFrequencyInMs()); - + config.setIndexIntegrityValidatorFrequencyInMs(5555); assertEquals(5555, config.getIndexIntegrityValidatorFrequencyInMs()); - + config.setConfigOkForPeriodicSync(false); assertEquals(false, config.isConfigOkForPeriodicSync()); - + config.setConfigOkForStartupSync(false); assertEquals(false, config.isConfigOkForStartupSync()); - + } - + @Test public void validateFirstSyncTimeCalculation_taskFrequencyZeroDays() { - - Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + + Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // set year, month, day, hour, minute, second - syncThresholdTime.set(2017,2,1,0,0,0); // 00:00 on 1-Feb-2017 - - - Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + syncThresholdTime.set(2017, 2, 1, 0, 0, 0); // 00:00 on 1-Feb-2017 + + + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // set year, month, day, hour, minute, second - timeNow.set(2017,2,1,0,0,0); // 00:00 on 1-Feb-2017 + timeNow.set(2017, 2, 1, 0, 0, 0); // 00:00 on 1-Feb-2017 + + assertEquals(0, config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 0)); - assertEquals( 0, config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 0)); - } - + @Test public void validateFirstSyncTimeCalculation_timeNowLessThanSyncTimeBoundary() { - - Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + + Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // 06:00 on 1-Feb-2017 - syncThresholdTime.set(2017,2,1,6,0,0); - - Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + syncThresholdTime.set(2017, 2, 1, 6, 0, 0); + + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // set year, month, day, hour, minute, second - timeNow.set(2017,2,1,0,0,0); // 00:00 on 1-Feb-2017 - + timeNow.set(2017, 2, 1, 0, 0, 0); // 00:00 on 1-Feb-2017 + // First sync time is the 06:00 am threshold time - assertEquals( syncThresholdTime.getTimeInMillis(), config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 1*86400)); - + assertEquals(syncThresholdTime.getTimeInMillis(), + config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 1 * 86400)); + } - + @Test public void validateFirstSyncTimeCalculation_timeNowEqualsSyncTimeBoundary() { - - Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + + Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // 06:00 on 1-Feb-2017 - syncThresholdTime.set(2017,2,1,6,0,0); - - Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + syncThresholdTime.set(2017, 2, 1, 6, 0, 0); + + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // set year, month, day, hour, minute, second - timeNow.set(2017,2,1,6,0,0); // 00:00 on 1-Feb-2017 - + timeNow.set(2017, 2, 1, 6, 0, 0); // 00:00 on 1-Feb-2017 + // First sync time is the 06:00 am threshold time - //assertEquals( (syncThresholdTime.getTimeInMillis()/1000), (config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 1*86400)/1000)); - + // assertEquals( (syncThresholdTime.getTimeInMillis()/1000), + // (config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 1*86400)/1000)); + } - + @Test public void validateFirstSyncTimeCalculation_timeNowGreaterThanSyncTimeBoundary() { - - Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + + Calendar syncThresholdTime = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // 06:00 on 1-Feb-2017 - syncThresholdTime.set(2017,2,1,6,0,0); - - Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"),Locale.CANADA); + syncThresholdTime.set(2017, 2, 1, 6, 0, 0); + + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.CANADA); // set year, month, day, hour, minute, second - timeNow.set(2017,2,1,8,0,0); // 00:00 on 1-Feb-2017 - + timeNow.set(2017, 2, 1, 8, 0, 0); // 00:00 on 1-Feb-2017 + // First sync time is 1 full sync period past the sync threshold time - assertEquals( 86400000 + syncThresholdTime.getTimeInMillis(), config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 1*86400)); - + assertEquals(86400000 + syncThresholdTime.getTimeInMillis(), + config.getNextSyncTime(syncThresholdTime, timeNow.getTimeInMillis(), 1 * 86400)); + } - -/* @Test - public void validateDefaultPeriodicInitialSyncDelay_dailySync_timeNowAtMidnight() { - - config.setSyncTaskStartTimeTimeZone("EST"); - config.setSyncTaskStartTimeHr(6); - config.setSyncTaskStartTimeMin(0); - config.setSyncTaskStartTimeSec(0); - config.setSyncTaskFrequencyInDay(1); - config.setSyncTaskInitialDelayInMs(60000); - - Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); - // set year, month, day, hour, minute, second - timeNow.set(Calendar.AM_PM, Calendar.AM); - timeNow.set(Calendar.HOUR, 0); - timeNow.set(Calendar.MINUTE, 0); - timeNow.set(Calendar.SECOND, 0); - - // First sync time is 6 hours from midnight - assertEquals( 6*3600*1000, config.getDefaultInitialSyncDelayInMs(timeNow)); - - }*/ - + /* + * @Test public void validateDefaultPeriodicInitialSyncDelay_dailySync_timeNowAtMidnight() { + * + * config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); + * config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); + * config.setSyncTaskFrequencyInDay(1); config.setSyncTaskInitialDelayInMs(60000); + * + * Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); + * + * // set year, month, day, hour, minute, second timeNow.set(Calendar.AM_PM, Calendar.AM); + * timeNow.set(Calendar.HOUR, 0); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, + * 0); + * + * // First sync time is 6 hours from midnight assertEquals( 6*3600*1000, + * config.getDefaultInitialSyncDelayInMs(timeNow)); + * + * } + */ + @Test public void validateDefaultPeriodicInitialSyncDelay_dailySync_timeNowAt4AM() { - + config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); config.setSyncTaskFrequencyInDay(1); config.setSyncTaskInitialDelayInMs(60000); - + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); // set year, month, day, hour, minute, second @@ -250,22 +249,22 @@ public class SynchronizerConfigurationTest { timeNow.set(Calendar.HOUR, 4); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, 0); - + // round time to minutes to avoid millisecond alignment variance assertEquals(2 * 3600, (config.getDefaultInitialSyncDelayInMs(timeNow)) / 1000); } - + @Test public void validateDefaultPeriodicInitialSyncDelay_dailySync_timeNowAt6AM() { - + config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); config.setSyncTaskFrequencyInDay(1); config.setSyncTaskInitialDelayInMs(60000); - + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); // set year, month, day, hour, minute, second @@ -273,22 +272,22 @@ public class SynchronizerConfigurationTest { timeNow.set(Calendar.HOUR, 6); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, 0); - - // First sync time is now with 60 seconds from now - assertEquals( 60000, config.getDefaultInitialSyncDelayInMs(timeNow)); - + + // First sync time is now with 60 seconds from now + assertEquals(60000, config.getDefaultInitialSyncDelayInMs(timeNow)); + } - + @Test public void validateDefaultPeriodicInitialSyncDelay_dailySync_timeNowAt10PM() { - + config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); config.setSyncTaskFrequencyInDay(1); config.setSyncTaskInitialDelayInMs(60000); - + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); // set year, month, day, hour, minute, second @@ -296,46 +295,42 @@ public class SynchronizerConfigurationTest { timeNow.set(Calendar.HOUR, 10); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, 0); - - // First sync time is now 1 sync period delayed. The time delay before + + // First sync time is now 1 sync period delayed. The time delay before // the initial sync should now be 8 hours, assuming 10PM is the current time. - assertEquals( 8*3600, (config.getDefaultInitialSyncDelayInMs(timeNow)/1000)); - + assertEquals(8 * 3600, (config.getDefaultInitialSyncDelayInMs(timeNow) / 1000)); + } - -/* @Test - public void validateDefaultPeriodicInitialSyncDelay_weeklySync_timeNowAtMidnight() { - - config.setSyncTaskStartTimeTimeZone("EST"); - config.setSyncTaskStartTimeHr(6); - config.setSyncTaskStartTimeMin(0); - config.setSyncTaskStartTimeSec(0); - config.setSyncTaskFrequencyInDay(7); - config.setSyncTaskInitialDelayInMs(60000); - - Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); - // set year, month, day, hour, minute, second - timeNow.set(Calendar.AM_PM, Calendar.AM); - timeNow.set(Calendar.HOUR, 0); - timeNow.set(Calendar.MINUTE, 0); - timeNow.set(Calendar.SECOND, 0); - - // First sync time is 6 hours from midnight - assertTrue(6*3600*1000 >= config.getDefaultInitialSyncDelayInMs(timeNow)); - - }*/ - + /* + * @Test public void validateDefaultPeriodicInitialSyncDelay_weeklySync_timeNowAtMidnight() { + * + * config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); + * config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); + * config.setSyncTaskFrequencyInDay(7); config.setSyncTaskInitialDelayInMs(60000); + * + * Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); + * + * // set year, month, day, hour, minute, second timeNow.set(Calendar.AM_PM, Calendar.AM); + * timeNow.set(Calendar.HOUR, 0); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, + * 0); + * + * // First sync time is 6 hours from midnight assertTrue(6*3600*1000 >= + * config.getDefaultInitialSyncDelayInMs(timeNow)); + * + * } + */ + @Test public void validateDefaultPeriodicInitialSyncDelay_weeklySync_timeNowAt4AM() { - + config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); config.setSyncTaskFrequencyInDay(7); config.setSyncTaskInitialDelayInMs(60000); - + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); // set year, month, day, hour, minute, second @@ -343,22 +338,22 @@ public class SynchronizerConfigurationTest { timeNow.set(Calendar.HOUR, 4); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, 0); - + // round time to minutes to avoid millisecond alignment variance assertEquals(2 * 3600, (config.getDefaultInitialSyncDelayInMs(timeNow)) / 1000); } - + @Test public void validateDefaultPeriodicInitialSyncDelay_weeklySync_timeNowAt6AM() { - + config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); config.setSyncTaskFrequencyInDay(7); config.setSyncTaskInitialDelayInMs(60000); - + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); // set year, month, day, hour, minute, second @@ -366,22 +361,22 @@ public class SynchronizerConfigurationTest { timeNow.set(Calendar.HOUR, 6); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, 0); - - // First sync time is now with 60 seconds from now - assertEquals( 60000, config.getDefaultInitialSyncDelayInMs(timeNow)); - + + // First sync time is now with 60 seconds from now + assertEquals(60000, config.getDefaultInitialSyncDelayInMs(timeNow)); + } - + @Test public void validateDefaultPeriodicInitialSyncDelay_weeklySync_timeNowAt10PM() { - + config.setSyncTaskStartTimeTimeZone("EST"); config.setSyncTaskStartTimeHr(6); config.setSyncTaskStartTimeMin(0); config.setSyncTaskStartTimeSec(0); config.setSyncTaskFrequencyInDay(7); config.setSyncTaskInitialDelayInMs(60000); - + Calendar timeNow = Calendar.getInstance(TimeZone.getTimeZone("EST")); // set year, month, day, hour, minute, second @@ -389,12 +384,12 @@ public class SynchronizerConfigurationTest { timeNow.set(Calendar.HOUR, 10); timeNow.set(Calendar.MINUTE, 0); timeNow.set(Calendar.SECOND, 0); - - // First sync time is now 1 sync period delayed. The time delay before + + // First sync time is now 1 sync period delayed. The time delay before // the initial sync should now be 8 hours + 24*6 days, assuming 10PM is the current time. - assertEquals( (8+(6*24))*3600, (config.getDefaultInitialSyncDelayInMs(timeNow)/1000)); - + assertEquals((8 + (6 * 24)) * 3600, (config.getDefaultInitialSyncDelayInMs(timeNow) / 1000)); + } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java index 5b945cf..5aab75d 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java @@ -63,7 +63,7 @@ public class AggregationSuggestionEntityTest { String expectedFilterListPayload = getResourceFileContents( "sync/entity/AggregationSuggestionEntity_getIndexDocumentJson_expected.json"); - assertTrue( - aggregationSuggestionEntity.getIndexDocumentJson().contains(expectedFilterListPayload.trim())); + assertTrue(aggregationSuggestionEntity.getIndexDocumentJson() + .contains(expectedFilterListPayload.trim())); } } diff --git a/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java b/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java index 31b425a..3a36f7d 100644 --- a/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java +++ b/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java @@ -90,13 +90,17 @@ public class CaptureLoggerAppender implements Appender { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.LifeCycle#start() */ @Override public void start() {} - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.LifeCycle#stop() */ @Override @@ -123,7 +127,9 @@ public class CaptureLoggerAppender implements Appender { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addStatus(ch.qos.logback.core.status.Status) */ @Override @@ -132,7 +138,9 @@ public class CaptureLoggerAppender implements Appender { System.out.println("addStatus"); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addInfo(java.lang.String) */ @Override @@ -141,7 +149,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addInfo(java.lang.String, java.lang.Throwable) */ @Override @@ -150,7 +160,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addWarn(java.lang.String) */ @Override @@ -159,7 +171,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addWarn(java.lang.String, java.lang.Throwable) */ @Override @@ -168,7 +182,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addError(java.lang.String) */ @Override @@ -177,7 +193,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.ContextAware#addError(java.lang.String, java.lang.Throwable) */ @Override @@ -186,7 +204,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.FilterAttachable#addFilter(ch.qos.logback.core.filter.Filter) */ @Override @@ -195,7 +215,9 @@ public class CaptureLoggerAppender implements Appender { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.FilterAttachable#clearAllFilters() */ @Override @@ -210,7 +232,9 @@ public class CaptureLoggerAppender implements Appender { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.spi.FilterAttachable#getFilterChainDecision(java.lang.Object) */ @Override @@ -226,7 +250,9 @@ public class CaptureLoggerAppender implements Appender { return "MOCK"; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ch.qos.logback.core.Appender#doAppend(java.lang.Object) */ @Override diff --git a/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java b/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java index 7538c1b..5f98e0b 100644 --- a/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java +++ b/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java @@ -44,6 +44,7 @@ import org.onap.aai.sparky.synchronizer.config.TaskProcessorConfig; public class ElasticEntitySummarizer { private RestDataProvider syncAdapter; + /** * @return the syncAdapter */ @@ -185,10 +186,8 @@ public class ElasticEntitySummarizer { System.out.println(String.format("\n%-30s %-12d", "Total", totalEntities)); } catch (Exception exc) { - System.out.println( - "An error occurred while attempting to collect pre-sync elastic" - + " search document ids with an error cause = " - + exc.getLocalizedMessage()); + System.out.println("An error occurred while attempting to collect pre-sync elastic" + + " search document ids with an error cause = " + exc.getLocalizedMessage()); } diff --git a/src/test/java/org/onap/aai/sparky/util/ElasticGarbageInjector.java b/src/test/java/org/onap/aai/sparky/util/ElasticGarbageInjector.java index 5e47942..92ccd28 100644 --- a/src/test/java/org/onap/aai/sparky/util/ElasticGarbageInjector.java +++ b/src/test/java/org/onap/aai/sparky/util/ElasticGarbageInjector.java @@ -47,8 +47,8 @@ public class ElasticGarbageInjector { private enum ActiveInventoryEntities { COMPLEX("complex"), CUSTOMER("customer"), GENERIC_VNF("generic-vnf"), NEWVCE("newvce"), PSERVER( - "pserver"), SERVICE_INSTANCE("service-instance"), VCE("vce"), VPE("vpe"), VSERVER( - "vserver"); + "pserver"), SERVICE_INSTANCE( + "service-instance"), VCE("vce"), VPE("vpe"), VSERVER("vserver"); private final String entityName; diff --git a/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java b/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java index 6acb1bf..3b56a6e 100644 --- a/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java +++ b/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java @@ -29,7 +29,7 @@ package org.onap.aai.sparky.util; * The Class ExceptionHelper. */ public class ExceptionHelper { - + /** * Extract stack trace elements. * diff --git a/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java b/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java index de90f85..d06a1c1 100644 --- a/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java +++ b/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java @@ -64,8 +64,8 @@ public class HttpServletHelper { try { Mockito.when(request.getContentType()).thenReturn(mimeType); - - + + final ByteArrayInputStream bais = new ByteArrayInputStream(payloadContent.getBytes(StandardCharsets.UTF_8)); @@ -94,8 +94,9 @@ public class HttpServletHelper { }; Mockito.when(request.getInputStream()).thenReturn(servletInputStream); - Mockito.when(request.getReader()).thenReturn(new BufferedReader(new StringReader(payloadContent))); - + Mockito.when(request.getReader()) + .thenReturn(new BufferedReader(new StringReader(payloadContent))); + } catch (IOException ioe) { fail(ExceptionHelper.extractStackTraceElements(5, ioe)); } @@ -150,11 +151,12 @@ public class HttpServletHelper { for (String key : paramNameValueMap.keySet()) { Mockito.when(req.getParameter(key)).thenReturn(paramNameValueMap.get(key)); } - + } } - - public static void assignRequestHeader(HttpServletRequest req, String headerName, String headerValue) { + + public static void assignRequestHeader(HttpServletRequest req, String headerName, + String headerValue) { Mockito.when(req.getHeader(headerName)).thenReturn(headerValue); } diff --git a/src/test/java/org/onap/aai/sparky/util/KeystoreBuilderTest.java b/src/test/java/org/onap/aai/sparky/util/KeystoreBuilderTest.java index aadaff9..b719381 100644 --- a/src/test/java/org/onap/aai/sparky/util/KeystoreBuilderTest.java +++ b/src/test/java/org/onap/aai/sparky/util/KeystoreBuilderTest.java @@ -49,52 +49,57 @@ import org.mockito.Mockito; public class KeystoreBuilderTest {
- @Rule
- public TemporaryFolder folder = new TemporaryFolder();
+ @Rule
+ public TemporaryFolder folder = new TemporaryFolder();
- KeystoreBuilder ksb;
- org.onap.aai.sparky.util.test.KeystoreBuilder ksb1;
+ KeystoreBuilder ksb;
+ org.onap.aai.sparky.util.test.KeystoreBuilder ksb1;
- @Before
- public void setUp() throws IOException, NoSuchAlgorithmException {
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ @Before
+ public void setUp() throws IOException, NoSuchAlgorithmException {
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- folder.newFile("file1.xml");
- folder.newFile("file2.xml");
+ folder.newFile("file1.xml");
+ folder.newFile("file2.xml");
- String endPointList = "https://localhost:9517;https://localhost:8443";
- ksb = new KeystoreBuilder(endPointList);
- ksb1 = new org.onap.aai.sparky.util.test.KeystoreBuilder(endPointList);
- }
+ String endPointList = "https://localhost:9517;https://localhost:8443";
+ ksb = new KeystoreBuilder(endPointList);
+ ksb1 = new org.onap.aai.sparky.util.test.KeystoreBuilder(endPointList);
+ }
- @Test(expected=IOException.class)
- public void testUpdateKeyStore() throws KeyManagementException, KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
- ksb.updateKeystore(folder.getRoot().getAbsolutePath(), "password-1");
- ksb1.updateKeystore(folder.getRoot().getAbsolutePath(), "password-1");
- }
+ @Test(expected = IOException.class)
+ public void testUpdateKeyStore() throws KeyManagementException, KeyStoreException,
+ CertificateException, IOException, NoSuchAlgorithmException {
+ ksb.updateKeystore(folder.getRoot().getAbsolutePath(), "password-1");
+ ksb1.updateKeystore(folder.getRoot().getAbsolutePath(), "password-1");
+ }
- @Test(expected=InvocationTargetException.class)
- public void testCertificateChainMethods() throws NoSuchMethodException, SecurityException,
- IllegalAccessException, IllegalArgumentException, InvocationTargetException, UnknownHostException, IOException {
- SSLSocketFactory factory = Mockito.mock(SSLSocketFactory.class);
- SSLSocket socket = Mockito.mock(SSLSocket.class);
- Mockito.when(factory.createSocket("localhost",9517)).thenReturn(socket);
- Method method = KeystoreBuilder.class.getDeclaredMethod("getCertificateChainForRemoteEndpoint", String.class, int.class);
- method.setAccessible(true);
- X509Certificate[] certChain = (X509Certificate[])method.invoke(ksb, "localhost",9517);
- Assert.assertNotNull(certChain);
- }
+ @Test(expected = InvocationTargetException.class)
+ public void testCertificateChainMethods()
+ throws NoSuchMethodException, SecurityException, IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException, UnknownHostException, IOException {
+ SSLSocketFactory factory = Mockito.mock(SSLSocketFactory.class);
+ SSLSocket socket = Mockito.mock(SSLSocket.class);
+ Mockito.when(factory.createSocket("localhost", 9517)).thenReturn(socket);
+ Method method = KeystoreBuilder.class.getDeclaredMethod("getCertificateChainForRemoteEndpoint",
+ String.class, int.class);
+ method.setAccessible(true);
+ X509Certificate[] certChain = (X509Certificate[]) method.invoke(ksb, "localhost", 9517);
+ Assert.assertNotNull(certChain);
+ }
- @Test(expected=InvocationTargetException.class)
- public void testCertificateChainMethods1() throws NoSuchMethodException, SecurityException,
- IllegalAccessException, IllegalArgumentException, InvocationTargetException, UnknownHostException, IOException {
- SSLSocketFactory factory = Mockito.mock(SSLSocketFactory.class);
- SSLSocket socket = Mockito.mock(SSLSocket.class);
- Mockito.when(factory.createSocket("localhost",9517)).thenReturn(socket);
- Method method = org.onap.aai.sparky.util.test.KeystoreBuilder.class.getDeclaredMethod("getCertificateChainForRemoteEndpoint", String.class, int.class);
- method.setAccessible(true);
- X509Certificate[] certChain = (X509Certificate[])method.invoke(ksb1, "localhost",9517);
- Assert.assertNotNull(certChain);
- }
+ @Test(expected = InvocationTargetException.class)
+ public void testCertificateChainMethods1()
+ throws NoSuchMethodException, SecurityException, IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException, UnknownHostException, IOException {
+ SSLSocketFactory factory = Mockito.mock(SSLSocketFactory.class);
+ SSLSocket socket = Mockito.mock(SSLSocket.class);
+ Mockito.when(factory.createSocket("localhost", 9517)).thenReturn(socket);
+ Method method = org.onap.aai.sparky.util.test.KeystoreBuilder.class
+ .getDeclaredMethod("getCertificateChainForRemoteEndpoint", String.class, int.class);
+ method.setAccessible(true);
+ X509Certificate[] certChain = (X509Certificate[]) method.invoke(ksb1, "localhost", 9517);
+ Assert.assertNotNull(certChain);
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/util/NodeUtilsTest.java b/src/test/java/org/onap/aai/sparky/util/NodeUtilsTest.java index 9329d9a..b2c19df 100644 --- a/src/test/java/org/onap/aai/sparky/util/NodeUtilsTest.java +++ b/src/test/java/org/onap/aai/sparky/util/NodeUtilsTest.java @@ -448,7 +448,7 @@ public class NodeUtilsTest { String result = NodeUtils.concatArray(numberList); assertEquals("1 2 3", result); } - + /** * Test format timestamp expect valid result. */ @@ -470,37 +470,46 @@ public class NodeUtilsTest { assertEquals(validTimeStamp, result); } - + /** * Test isNumeric expect true */ @Test - public void test_isNumeric_expectFalse(){ - String invalidNumber="number"; - assertFalse(NodeUtils.isNumeric(invalidNumber)); + public void test_isNumeric_expectFalse() { + String invalidNumber = "number"; + assertFalse(NodeUtils.isNumeric(invalidNumber)); } - + /** * Test isNumeric expect true */ @Test - public void test_isNumeric_expectTrue(){ - String validNumber="123"; - assertTrue(NodeUtils.isNumeric(validNumber)); + public void test_isNumeric_expectTrue() { + String validNumber = "123"; + assertTrue(NodeUtils.isNumeric(validNumber)); } + /** * test calculate edit attributes urls */ @Test public void validateCalculateEditAttributeLogic() { - - assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v7/pservers/pserver/12345"),"pservers/pserver/12345"); - assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v1/pservers/pserver/12345"),"pservers/pserver/12345"); - assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v21/pservers/pserver/12345"),"pservers/pserver/12345"); - assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v211/pservers/pserver/12345"),"pservers/pserver/12345"); - assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v5252/pservers/pserver/12345"),"pservers/pserver/12345"); + + assertEquals( + NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v7/pservers/pserver/12345"), + "pservers/pserver/12345"); + assertEquals( + NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v1/pservers/pserver/12345"), + "pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri( + "https://localhost:9000/aai/v21/pservers/pserver/12345"), "pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri( + "https://localhost:9000/aai/v211/pservers/pserver/12345"), "pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri( + "https://localhost:9000/aai/v5252/pservers/pserver/12345"), "pservers/pserver/12345"); assertNull(NodeUtils.calculateEditAttributeUri(null)); - assertNull(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/noVersionTag/pservers/pserver/12345")); + assertNull(NodeUtils.calculateEditAttributeUri( + "https://localhost:9000/aai/noVersionTag/pservers/pserver/12345")); } diff --git a/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationsTest.java b/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationsTest.java index 2d277bd..53905d4 100644 --- a/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationsTest.java +++ b/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationsTest.java @@ -14,13 +14,13 @@ public class SuggestionsPermutationsTest { @Test public void isValidSuggestionPermutation_successPath() { - + List<String> x = new ArrayList<>(Arrays.asList("A", "B", "C", "D")); SuggestionsPermutation suggPermutation = new SuggestionsPermutation(); - + ArrayList<ArrayList<String>> uniqueLists = suggPermutation.getSuggestionsPermutation(x); - - assertTrue(uniqueLists.get(0).toString().equals("[A]")); + + assertTrue(uniqueLists.get(0).toString().equals("[A]")); assertTrue(uniqueLists.get(1).toString().equals("[A, B, C, D]")); assertTrue(uniqueLists.get(2).toString().equals("[A, C, D]")); assertTrue(uniqueLists.get(3).toString().equals("[A, D]")); @@ -31,6 +31,6 @@ public class SuggestionsPermutationsTest { assertTrue(uniqueLists.get(8).toString().equals("[C, D]")); assertTrue(uniqueLists.get(9).toString().equals("[D]")); assertTrue(uniqueLists.size() == 10); - + } } diff --git a/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java b/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java index 36b11ed..198a0eb 100644 --- a/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java +++ b/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java @@ -57,8 +57,7 @@ public class TreeWalkerTest { * @throws Exception the exception */ @Before - public void init() throws Exception { - } + public void init() throws Exception {} /** * Validate json node conversion null input. @@ -184,8 +183,7 @@ public class TreeWalkerTest { public void validateWalkTreeOneParentNodeWithObjectArray() { try { - String jsonStr = - "{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"}," + String jsonStr = "{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"}," + "{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"}," + "{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}"; TreeWalker walker = new TreeWalker(); @@ -230,68 +228,68 @@ public class TreeWalkerTest { try { String jsonStr = "{ \"generalNodeClass\": { \"class\": \"aai-entity-node general-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\", " - + " \"svgAttributes\": { \"r\": \"10\" " - + "} }, { \"type\": \"text\", " - + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " - + " \"shapeAttributes\": { \"offset\": { " - + " \"x\": \"0\", \"y\": \"30\" } " - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": { " - + " \"offset\": { \"x\": \"0\", " - + " \"y\": \"40\" } } } ] " - + " }, \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": { " - + " \"r\": \"20\" } }, { " - + " \"type\": \"circle\", \"class\": \"inner\", " - + " \"svgAttributes\": { \"r\": \"10\" }" - + " }, { \"type\": \"text\", " - + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " - + " \"shapeAttributes\": { \"offset\": { " - + " \"x\": \"0\", \"y\": \"30\" }" - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-value-label\", " - + "\"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"40\" } }" - + " } ] }, \"selectedSearchedNodeClass\": { " - + "\"class\": \"aai-entity-node selected-search-node\", \"visualElements\": [" - + " { \"type\": \"circle\", " - + "\"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\" " - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"30\"" - + " } } }, { " - + " \"type\": \"text\", \"class\": \"id-value-label\", " - + " \"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\", " - + " \"y\": \"40\" } } } ]" - + " }, \"selectedNodeClass\": { \"class\":" - + " \"aai-entity-node selected-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\" " - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," - + " \"shapeAttributes\": { \"offset\": " - + "{ " - + " \"x\": \"0\", \"y\": \"30\" } " - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": { " - + "\"offset\": { \"x\": \"0\", " - + "\"y\": \"40\" } } } ] }}"; + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\", " + + " \"svgAttributes\": { \"r\": \"10\" " + + "} }, { \"type\": \"text\", " + + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " + + " \"shapeAttributes\": { \"offset\": { " + + " \"x\": \"0\", \"y\": \"30\" } " + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": { " + + " \"offset\": { \"x\": \"0\", " + + " \"y\": \"40\" } } } ] " + + " }, \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": { " + + " \"r\": \"20\" } }, { " + + " \"type\": \"circle\", \"class\": \"inner\", " + + " \"svgAttributes\": { \"r\": \"10\" }" + + " }, { \"type\": \"text\", " + + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " + + " \"shapeAttributes\": { \"offset\": { " + + " \"x\": \"0\", \"y\": \"30\" }" + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-value-label\", " + + "\"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"40\" } }" + + " } ] }, \"selectedSearchedNodeClass\": { " + + "\"class\": \"aai-entity-node selected-search-node\", \"visualElements\": [" + + " { \"type\": \"circle\", " + + "\"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\" " + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"30\"" + + " } } }, { " + + " \"type\": \"text\", \"class\": \"id-value-label\", " + + " \"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\", " + + " \"y\": \"40\" } } } ]" + + " }, \"selectedNodeClass\": { \"class\":" + + " \"aai-entity-node selected-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\" " + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," + + " \"shapeAttributes\": { \"offset\": " + + "{ " + + " \"x\": \"0\", \"y\": \"30\" } " + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": { " + + "\"offset\": { \"x\": \"0\", " + + "\"y\": \"40\" } } } ] }}"; TreeWalker walker = new TreeWalker(); List<String> paths = new ArrayList<String>(); walker.walkTree(paths, walker.convertJsonToNode(jsonStr)); @@ -400,143 +398,143 @@ public class TreeWalkerTest { try { String n1Str = "{ \"generalNodeClass\": { \"class\": \"aai-entity-node general-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": { \"offset\":" - + " { \"x\": \"0\", \"y\": \"30\"" - + " } } }, {" - + " \"type\": \"text\", \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\":" - + " { \"x\": \"0\", \"y\": \"40\"" - + " } } } ] }," - + " \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"30\"" - + " } } }, {" - + " \"type\": \"text\", \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"40\"" - + " } } } ] }," - + " \"selectedSearchedNodeClass\": { \"class\":" - + " \"aai-entity-node selected-search-node\", \"visualElements\": [" - + " { \"type\": \"circle\", \"class\":" - + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" - + " } }, { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }, {" - + " \"type\": \"text\", \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"30\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"40\"" - + " } } } ] }," - + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"30\" }" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"40\" } }" - + " } ] }}"; + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": { \"offset\":" + + " { \"x\": \"0\", \"y\": \"30\"" + + " } } }, {" + + " \"type\": \"text\", \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\":" + + " { \"x\": \"0\", \"y\": \"40\"" + + " } } } ] }," + + " \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"30\"" + + " } } }, {" + + " \"type\": \"text\", \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"40\"" + + " } } } ] }," + + " \"selectedSearchedNodeClass\": { \"class\":" + + " \"aai-entity-node selected-search-node\", \"visualElements\": [" + + " { \"type\": \"circle\", \"class\":" + + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" + + " } }, { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }, {" + + " \"type\": \"text\", \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"30\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"40\"" + + " } } } ] }," + + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"30\" }" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"40\" } }" + + " } ] }}"; String n2Str = "{ \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }," - + " { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }, {" - + " \"type\": \"text\", \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"y\": \"40\", \"x\": \"0\"" - + " } } } ] }," - + " \"selectedSearchedNodeClass\": { \"class\":" - + " \"aai-entity-node selected-search-node\", \"visualElements\": [" - + " { \"type\": \"circle\", \"class\":" - + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" - + " } }, { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }, {" - + " \"type\": \"text\", \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"y\": \"40\", \"x\": \"0\"" - + " } } } ] }," - + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"y\": \"40\", \"x\": \"0\"" - + " } } } ] }," - + " \"generalNodeClass\": { \"class\":" - + " \"aai-entity-node general-node\", \"visualElements\": [" - + " { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }," - + " { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }," - + " { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" }" - + " } }, {" - + " \"type\": \"text\"," - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"40\"," - + " \"x\": \"0\" }" - + " } } ] }}"; + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }," + + " { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }, {" + + " \"type\": \"text\", \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"y\": \"40\", \"x\": \"0\"" + + " } } } ] }," + + " \"selectedSearchedNodeClass\": { \"class\":" + + " \"aai-entity-node selected-search-node\", \"visualElements\": [" + + " { \"type\": \"circle\", \"class\":" + + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" + + " } }, { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }, {" + + " \"type\": \"text\", \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"y\": \"40\", \"x\": \"0\"" + + " } } } ] }," + + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"y\": \"40\", \"x\": \"0\"" + + " } } } ] }," + + " \"generalNodeClass\": { \"class\":" + + " \"aai-entity-node general-node\", \"visualElements\": [" + + " { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }," + + " { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }," + + " { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" }" + + " } }, {" + + " \"type\": \"text\"," + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"40\"," + + " \"x\": \"0\" }" + + " } } ] }}"; TreeWalker walker = new TreeWalker(); List<String> n1Paths = new ArrayList<String>(); diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/ActiveInventoryNodeTester.java b/src/test/java/org/onap/aai/sparky/viewandinspect/ActiveInventoryNodeTester.java index 9dd23b5..df6bc2c 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/ActiveInventoryNodeTester.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/ActiveInventoryNodeTester.java @@ -87,8 +87,7 @@ public class ActiveInventoryNodeTester { return nodeA; } - private String selfLinkFormat = - "https://aai-hostname:9292/aai/v7/network/generic-vnfs/%s/%s"; + private String selfLinkFormat = "https://aai-hostname:9292/aai/v7/network/generic-vnfs/%s/%s"; /** diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java index bbee87c..1baf2e4 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java @@ -56,7 +56,7 @@ public class SearchAdapterTest { private WebResource mockWebResource; private Builder mockBuilder; - + /** * Inits the. diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java index cae9290..3b2158b 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java @@ -57,19 +57,19 @@ public class SearchResponseTest { SearchResponse response = new SearchResponse(); - //response.setNumReturned(1); + // response.setNumReturned(1); response.setProcessingTimeInMs(512); - //response.setTotalFound(50); + // response.setTotalFound(50); List<EntityEntry> entities = new ArrayList<EntityEntry>(); - //response.setEntities(entities); + // response.setEntities(entities); EntityEntry e1 = new EntityEntry(); e1.setEntityPrimaryKeyValue("e1"); e1.setEntityType("e1"); e1.setSearchTags("e1"); - //response.addEntityEntry(e1); + // response.addEntityEntry(e1); EntityEntry e2 = new EntityEntry(); @@ -77,15 +77,15 @@ public class SearchResponseTest { e2.setEntityType("e2"); e2.setSearchTags("e2"); - //response.addEntityEntry(e2); + // response.addEntityEntry(e2); - //assertEquals(1, response.getNumReturned()); - //assertEquals(512, response.getProcessingTimeInMs()); - //assertEquals(50, response.getTotalFound()); + // assertEquals(1, response.getNumReturned()); + // assertEquals(512, response.getProcessingTimeInMs()); + // assertEquals(50, response.getTotalFound()); - //List<EntityEntry> responseEntities = response.getEntities(); + // List<EntityEntry> responseEntities = response.getEntities(); - //assertEquals(2, responseEntities.size()); + // assertEquals(2, responseEntities.size()); } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java index 198bbb3..6d682f4 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java @@ -97,7 +97,7 @@ public class SearchServletTest { private static final String VNF_ROUTE = "vnf"; private static final String VIEW_INSPECT_ROUTE = "viewInspect"; - + private HttpServletRequest commonRequest = null; private HttpServletResponse commonResponse = null; private PrintWriter printWriter = null; @@ -111,7 +111,7 @@ public class SearchServletTest { private Map<String, OxmEntityDescriptor> descriptors = null; private SuggestionConfig suggestionConfig = null; private SearchServiceConfig esConfig = null; - + /** * Inits the. * @@ -128,21 +128,21 @@ public class SearchServletTest { // permit serialization of objects with no members mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - + rand = new SecureRandom(); - loader = Mockito.mock(OxmModelLoader.class); + loader = Mockito.mock(OxmModelLoader.class); descriptors = new HashMap<String, OxmEntityDescriptor>(); esConfig = new SearchServiceConfig(); suggestionConfig = SuggestionConfig.getConfig(); - + // Use SearchServiceWrapper and VnfSearchService for suggestionConfig Map<String, String> svcs = new HashMap<String, String>(); svcs.put("autosuggestIndexname", "SearchServiceWrapper"); svcs.put("indexName", "VnfSearchService"); suggestionConfig.setSearchIndexToSearchService(svcs); - + esConfig.setIndexName("esi-localhost"); esConfig.setType("default"); @@ -150,7 +150,7 @@ public class SearchServletTest { vnfSearchService = Mockito.mock(VnfSearchService.class); initializeEntityDescriptors(); - + searchWrapper = new SearchServiceWrapper(); searchWrapper.setSasConfig(esConfig); searchWrapper.setSearch(searchAdapter); @@ -161,9 +161,9 @@ public class SearchServletTest { @Test public void validateAccessors() { - assertNotNull("Vnf Search Service should not be null", searchWrapper.getVnfSearch()); + assertNotNull("Vnf Search Service should not be null", searchWrapper.getVnfSearch()); } - + @Test public void validateInitializer() { @@ -173,7 +173,7 @@ public class SearchServletTest { assertNotNull("SearchAdapter should not be null", searchWrapper.getSearch()); assertNotNull("Suggestion Config should not be null", searchWrapper.getSuggestionConfig()); assertNotNull("VnfSearchService should not be null", searchWrapper.getVnfSearch()); - + searchWrapper.setOxmModelLoader(null); searchWrapper.setSasConfig(null); searchWrapper.setSearch(null); @@ -191,34 +191,34 @@ public class SearchServletTest { } } - + /** - * Test doGet() and doPost() for a non-existent end-point. A test objective would be - * to either return a 404 Not Found. + * Test doGet() and doPost() for a non-existent end-point. A test objective would be to either + * return a 404 Not Found. */ @Test public void validateMdcContextLoggingVariablesWhenExplicitlySet() { - + final String transactionId = "1234"; final String serviceName = "AAI_UI"; final String partnerName = "SparkyApp"; - + HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", partnerName); - + HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); - + try { - + /* * Testing the doGet() operation will hit the doPost() operation in the servlet as well */ OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse); - - assertEquals(transactionId,MDC.get(MdcContext.MDC_REQUEST_ID)); - assertEquals(serviceName,MDC.get(MdcContext.MDC_SERVICE_NAME)); - assertEquals(partnerName,MDC.get(MdcContext.MDC_PARTNER_NAME)); + + assertEquals(transactionId, MDC.get(MdcContext.MDC_REQUEST_ID)); + assertEquals(serviceName, MDC.get(MdcContext.MDC_SERVICE_NAME)); + assertEquals(partnerName, MDC.get(MdcContext.MDC_PARTNER_NAME)); } catch (Exception exc) { exc.printStackTrace(); @@ -226,23 +226,24 @@ public class SearchServletTest { } } - + /** - * Test doGet() and doPost() for a non-existent end-point. A test objective would be - * to either return a 404 Not Found. + * Test doGet() and doPost() for a non-existent end-point. A test objective would be to either + * return a 404 Not Found. */ @Test public void validateMdcContextLoggingVariablesWhenNotExplicitlySet() { - - /*final String transactionId = "1234"; - final String serviceName = "AAI-UI"; - final String partnerName = "SparkyApp"; - - HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); - HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName);*/ - + + /* + * final String transactionId = "1234"; final String serviceName = "AAI-UI"; final String + * partnerName = "SparkyApp"; + * + * HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); + * HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName); + */ + HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); - + try { /* @@ -250,7 +251,7 @@ public class SearchServletTest { */ OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse); - + assertNotNull(MDC.get(MdcContext.MDC_REQUEST_ID)); assertNotNull(MDC.get(MdcContext.MDC_SERVICE_NAME)); assertNotNull(MDC.get(MdcContext.MDC_PARTNER_NAME)); @@ -261,17 +262,17 @@ public class SearchServletTest { } } - - - + + + /** - * Test doGet() and doPost() for a non-existent end-point. + * Test doGet() and doPost() for a non-existent end-point. */ @Test public void validateViewAndInspectSearchError_invalidRequestUri() { - + HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); - + try { /* @@ -288,10 +289,10 @@ public class SearchServletTest { } } - - + + /** - * Test doGet() and doPost() for Unified Query Search success path + * Test doGet() and doPost() for Unified Query Search success path */ @Test public void validateQuerySearch_successPath() { @@ -302,12 +303,13 @@ public class SearchServletTest { searchEntity.setMaxResults("10"); searchEntity.setQueryStr("the quick brown fox"); - HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch"); + HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch"); HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(searchEntity, false)); - - // set search-abstraction-response that we expect to get back from real system, but stubbed through a mock + + // set search-abstraction-response that we expect to get back from real system, but stubbed + // through a mock // to fulfill collaborator behavior OperationResult mockedEntitySearchResponse = new OperationResult(); @@ -315,22 +317,23 @@ public class SearchServletTest { mockedEntitySearchResponse.setResult(NodeUtils.convertObjectToJson( SearchAbstractionEntityBuilder.getSuccessfulEntitySearchResponse(), false)); - // TODO: make parameters expect certain values to lock in invocation attempt against a specific input sequence + // TODO: make parameters expect certain values to lock in invocation attempt against a + // specific input sequence Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) .thenReturn(mockedEntitySearchResponse); - + List<SuggestionEntity> autoSuggestions = new ArrayList<SuggestionEntity>(); - autoSuggestions.add(new SuggestionEntity("vnf","1234", "VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","1111", "Created VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","1122", "ACTIVE VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","2233", "ACTIVE and Error VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","3344", "ACTIVE and NOT ORCHESTRATED VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","4455", "ACTIVE and Running VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","5566", "Activated VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","6677", "CAPPED VNFs")); - autoSuggestions.add(new SuggestionEntity("vnf","7788", "CAPPED and Created VNFs")); - + autoSuggestions.add(new SuggestionEntity("vnf", "1234", "VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "1111", "Created VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "1122", "ACTIVE VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "2233", "ACTIVE and Error VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "3344", "ACTIVE and NOT ORCHESTRATED VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "4455", "ACTIVE and Running VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "5566", "Activated VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "6677", "CAPPED VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf", "7788", "CAPPED and Created VNFs")); + Mockito.when(vnfSearchService.getSuggestionsResults(Mockito.anyObject(), Mockito.anyInt())) .thenReturn(autoSuggestions); @@ -339,39 +342,39 @@ public class SearchServletTest { */ OperationResult result = doEvaluation(true, commonRequest, commonResponse); - - + + assertEquals(200, result.getResultCode()); - + SearchResponse searchResponse = mapper.readValue(result.getResult(), SearchResponse.class); - + assertEquals(10, searchResponse.getTotalFound()); - + int numVnf = 0; int numViewInspect = 0; - - for ( SuggestionEntity suggestion : searchResponse.getSuggestions()) { - - if ( VNF_ROUTE.equals(suggestion.getRoute())) { + + for (SuggestionEntity suggestion : searchResponse.getSuggestions()) { + + if (VNF_ROUTE.equals(suggestion.getRoute())) { numVnf++; - } else if ( VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) { + } else if (VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) { numViewInspect++; } } - + assertEquals(5, numVnf); assertEquals(5, numViewInspect); - - //assertTrue(result.getResult().contains("Ignored request-uri")); + + // assertTrue(result.getResult().contains("Ignored request-uri")); } catch (Exception exc) { fail("Unexpected exception = " + exc.getLocalizedMessage()); } } - + /** - * Test doGet() and doPost() for Unified Query Search success path + * Test doGet() and doPost() for Unified Query Search success path */ @Test public void validateSummaryByEntityTypeCount_successPath() { @@ -379,15 +382,17 @@ public class SearchServletTest { try { HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype/count"); - - Map<String,String> payloadFields = new HashMap<String,String>(); - payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); + + Map<String, String> payloadFields = new HashMap<String, String>(); + payloadFields.put("hashId", + "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); payloadFields.put("groupby", "orchestration-status"); - - - HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false)); - - + + + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), + NodeUtils.convertObjectToJson(payloadFields, false)); + + /* * In this test we don't want to mock the vnf search service, only it's collaborator * interactions with a REST endpoint. @@ -397,55 +402,57 @@ public class SearchServletTest { searchWrapper.setVnfSearch(vnfSearchService); /* - * The first network response to mock is the one to elastic search to get the suggestion entity by hash id + * The first network response to mock is the one to elastic search to get the suggestion + * entity by hash id * - * http://localhost:9200/entityautosuggestindex-localhost/_search - * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}} + * http://localhost:9200/entityautosuggestindex-localhost/_search + * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"} + * }} */ - + AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse(); - + elasticResponse.setTook(1); - + elasticResponse.setTimedOut(false); elasticResponse.addShard("total", "5"); elasticResponse.addShard("successful", "5"); elasticResponse.addShard("failed", "0"); - + AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity(); elasticHit.setIndex("entityautosuggestindex-localhost"); elasticHit.setType("default"); elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"); elasticHit.setScore("1"); - + AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields(); suggestDocFields.addInput("VNFs"); suggestDocFields.addInput("generic-vnfs"); suggestDocFields.setOutput("VNFs"); suggestDocFields.setPayload(new PayloadEntity()); suggestDocFields.setWeight(100); - + AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity(); autoSuggestDoc.setFields(suggestDocFields); - + elasticHit.setSource(autoSuggestDoc); - + AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity(); hits.addHit(elasticHit); - + elasticResponse.setHits(hits); - - + + OperationResult mockedSearchResponse = new OperationResult(); mockedSearchResponse.setResultCode(200); - + mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false)); - + /* * The second response is the count API dip to elastic search */ - + ElasticSearchCountResponse countResponse = new ElasticSearchCountResponse(); countResponse.setCount(3170); countResponse.addShard("total", "5"); @@ -454,39 +461,41 @@ public class SearchServletTest { OperationResult searchResponseForCount = new OperationResult(); searchResponseForCount.setResultCode(200); - + searchResponseForCount.setResult(NodeUtils.convertObjectToJson(countResponse, false)); - // TODO: make parameters expect certain values to lock in invocation attempt against a specific input sequence + // TODO: make parameters expect certain values to lock in invocation attempt against a + // specific input sequence Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) .thenReturn(mockedSearchResponse).thenReturn(searchResponseForCount); - - + + /* * Testing the doGet() operation will hit the doPost() operation in the servlet as well */ OperationResult result = doEvaluation(true, commonRequest, commonResponse); - - + + assertEquals(200, result.getResultCode()); - + // - //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} - - EntityCountResponse entityCountResponse = mapper.readValue(result.getResult(), EntityCountResponse.class); - - assertEquals(3170, entityCountResponse.getCount()); + // {"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} + + EntityCountResponse entityCountResponse = + mapper.readValue(result.getResult(), EntityCountResponse.class); + + assertEquals(3170, entityCountResponse.getCount()); } catch (Exception exc) { fail("Unexpected exception = " + exc.getLocalizedMessage()); } } - - + + /** - * Test doGet() and doPost() for Unified Query Search success path + * Test doGet() and doPost() for Unified Query Search success path */ @Test public void validateSummaryByEntityType_successPath() { @@ -494,13 +503,15 @@ public class SearchServletTest { try { HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype"); - - Map<String,String> payloadFields = new HashMap<String,String>(); - payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); + + Map<String, String> payloadFields = new HashMap<String, String>(); + payloadFields.put("hashId", + "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); payloadFields.put("groupby", "orchestration-status"); - - HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false)); - + + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), + NodeUtils.convertObjectToJson(payloadFields, false)); + /* * In this test we don't want to mock the vnf search service, only it's collaborator * interactions with a REST endpoint. @@ -510,128 +521,132 @@ public class SearchServletTest { searchWrapper.setVnfSearch(vnfSearchService); /* - * The first network response to mock is the one to elastic search to get the suggestion entity by hash id + * The first network response to mock is the one to elastic search to get the suggestion + * entity by hash id * - * http://localhost:9200/entityautosuggestindex-localhost/_search - * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}} + * http://localhost:9200/entityautosuggestindex-localhost/_search + * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"} + * }} */ - + AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse(); - + elasticResponse.setTook(1); - + elasticResponse.setTimedOut(false); elasticResponse.addShard("total", "5"); elasticResponse.addShard("successful", "5"); elasticResponse.addShard("failed", "0"); - + AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity(); elasticHit.setIndex("entityautosuggestindex-localhost"); elasticHit.setType("default"); elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"); elasticHit.setScore("1"); - + AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields(); suggestDocFields.addInput("VNFs"); suggestDocFields.addInput("generic-vnfs"); suggestDocFields.setOutput("VNFs"); suggestDocFields.setPayload(new PayloadEntity()); suggestDocFields.setWeight(100); - + AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity(); autoSuggestDoc.setFields(suggestDocFields); - + elasticHit.setSource(autoSuggestDoc); - + AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity(); hits.addHit(elasticHit); - + elasticResponse.setHits(hits); - - + + OperationResult mockedSearchResponse = new OperationResult(); mockedSearchResponse.setResultCode(200); - + mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false)); - + /* * The second response is the aggregation API dip to elastic search */ - + ElasticSearchAggegrationResponse aggResponse = new ElasticSearchAggegrationResponse(); - + aggResponse.setTook(20); aggResponse.setTimedOut(false); - - aggResponse.addShard("total","5"); - aggResponse.addShard("successful","5"); - aggResponse.addShard("failed","0"); - + + aggResponse.addShard("total", "5"); + aggResponse.addShard("successful", "5"); + aggResponse.addShard("failed", "0"); + ElasticHitsEntity hitsEntity = new ElasticHitsEntity(); - + hitsEntity.setTotal(3170); hitsEntity.setMaxScore(0); aggResponse.setHits(hitsEntity); - + ElasticSearchAggregation defaultAggregation = new ElasticSearchAggregation(); - + defaultAggregation.setDocCountErrorUpperBound(0); defaultAggregation.setSumOtherDocCount(0); - defaultAggregation.addBucket(new BucketEntity("created",1876)); - defaultAggregation.addBucket(new BucketEntity("Created",649)); - defaultAggregation.addBucket(new BucketEntity("Activated",158)); - defaultAggregation.addBucket(new BucketEntity("active",59)); - defaultAggregation.addBucket(new BucketEntity("NOT ORCHESTRATED",42)); - defaultAggregation.addBucket(new BucketEntity("Pending-Create",10)); - defaultAggregation.addBucket(new BucketEntity("Running",9)); - defaultAggregation.addBucket(new BucketEntity("Configured",7)); - defaultAggregation.addBucket(new BucketEntity("pending-create",7)); - defaultAggregation.addBucket(new BucketEntity("Error",3)); - defaultAggregation.addBucket(new BucketEntity("planned",3)); - defaultAggregation.addBucket(new BucketEntity("PLANNED",2)); - defaultAggregation.addBucket(new BucketEntity("ERROR",1)); - defaultAggregation.addBucket(new BucketEntity("RUNNING",1)); - defaultAggregation.addBucket(new BucketEntity("example-orchestration-status-val-6176",1)); - + defaultAggregation.addBucket(new BucketEntity("created", 1876)); + defaultAggregation.addBucket(new BucketEntity("Created", 649)); + defaultAggregation.addBucket(new BucketEntity("Activated", 158)); + defaultAggregation.addBucket(new BucketEntity("active", 59)); + defaultAggregation.addBucket(new BucketEntity("NOT ORCHESTRATED", 42)); + defaultAggregation.addBucket(new BucketEntity("Pending-Create", 10)); + defaultAggregation.addBucket(new BucketEntity("Running", 9)); + defaultAggregation.addBucket(new BucketEntity("Configured", 7)); + defaultAggregation.addBucket(new BucketEntity("pending-create", 7)); + defaultAggregation.addBucket(new BucketEntity("Error", 3)); + defaultAggregation.addBucket(new BucketEntity("planned", 3)); + defaultAggregation.addBucket(new BucketEntity("PLANNED", 2)); + defaultAggregation.addBucket(new BucketEntity("ERROR", 1)); + defaultAggregation.addBucket(new BucketEntity("RUNNING", 1)); + defaultAggregation.addBucket(new BucketEntity("example-orchestration-status-val-6176", 1)); + aggResponse.addAggregation("default", defaultAggregation); - + OperationResult searchResponseForAggregation = new OperationResult(); searchResponseForAggregation.setResultCode(200); - + searchResponseForAggregation.setResult(NodeUtils.convertObjectToJson(aggResponse, false)); - // TODO: make parameters expect certain values to lock in invocation attempt against a specific input sequence + // TODO: make parameters expect certain values to lock in invocation attempt against a + // specific input sequence Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) .thenReturn(mockedSearchResponse).thenReturn(searchResponseForAggregation); - - + + /* * Testing the doGet() operation will hit the doPost() operation in the servlet as well */ OperationResult result = doEvaluation(true, commonRequest, commonResponse); - - + + assertEquals(200, result.getResultCode()); - + // - //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} - - GroupByAggregationResponseEntity groupByResponse = mapper.readValue(result.getResult(), GroupByAggregationResponseEntity.class); - - assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits()); - assertEquals(15, groupByResponse.getAggEntity().getBuckets().size()); + // {"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} + + GroupByAggregationResponseEntity groupByResponse = + mapper.readValue(result.getResult(), GroupByAggregationResponseEntity.class); + + assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits()); + assertEquals(15, groupByResponse.getAggEntity().getBuckets().size()); } catch (Exception exc) { fail("Unexpected exception = " + exc.getLocalizedMessage()); } } - - - + + + /** * Builds the resource entity descriptor. * @@ -664,7 +679,7 @@ public class SearchServletTest { descriptors.put("customer", buildResourceEntityDescriptor("customer", "service-instance-id", "f1,f2,f3")); } - + /** * Builds the view and inspect search request. * @@ -703,7 +718,8 @@ public class SearchServletTest { * @param res the res * @return the string */ - private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req, HttpServletResponse res) { + private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req, + HttpServletResponse res) { /* * Test method invocation @@ -717,7 +733,7 @@ public class SearchServletTest { e.printStackTrace(); } ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class); - + try { if (doGet) { searchServlet.doGet(req, res); @@ -732,16 +748,16 @@ public class SearchServletTest { responseStringWriter.flush(); Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - + OperationResult result = new OperationResult(); - + result.setResultCode(responseCodeCaptor.getValue()); result.setResult(responseStringWriter.toString()); return result; } - + /** * Do evaluation. * @@ -750,13 +766,14 @@ public class SearchServletTest { * @param res the res * @return the string */ - private OperationResult doEvaluation(boolean doGet, HttpServletRequest req, HttpServletResponse res) { + private OperationResult doEvaluation(boolean doGet, HttpServletRequest req, + HttpServletResponse res) { /* * Test method invocation */ ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class); - + try { if (doGet) { searchWrapper.doGet(req, res); @@ -771,9 +788,9 @@ public class SearchServletTest { responseStringWriter.flush(); Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - + OperationResult result = new OperationResult(); - + result.setResultCode(responseCodeCaptor.getValue()); result.setResult(responseStringWriter.toString()); @@ -781,6 +798,6 @@ public class SearchServletTest { } - + } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java index d378c3a..5d9fa3a 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java @@ -36,38 +36,36 @@ public class SearchableGroupsTest { + "\"search-paths\" : [\"cloud-infrastructure\", \"business\", \"network\"]" + "}," + "{" + "\"group-name\" : \"cloud-infrastructure\"," + "\"search-paths\" : [\"complexes\", \"cloud-regions\", \"pservers\"]" + "}" + "]" + "}"; - /* - * @Before public void init() throws NoSuchFieldException, SecurityException, - * IllegalArgumentException, IllegalAccessException { Field instance = - * SearchableGroups.class.getDeclaredField("instance"); instance.setAccessible(true); - * instance.set(null, null); } - * - * @Test public void test_FileNotFound() throws ElasticSearchOperationException { - * System.setProperty("AJSC_HOME", ""); SearchableGroups testGroups = - * SearchableGroups.getTestInstance(); assertTrue(testGroups.getGroups().isEmpty()); } - * - * @Test public void test_FileFoundWithProperlyFormatedConfig() throws - * ElasticSearchOperationException { ResolverUtils testUtils = - * Mockito.mock(ResolverUtils.class); - * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); - * SearchableGroups testGroups = SearchableGroups.getTestInstance(); - * - * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); - * - * assertFalse(testGroups.getGroups().isEmpty()); - * - * assertFalse(testGroups.getSearchableGroups("inventory").isEmpty()); } - * - * @Test public void test_FileFoundGroupDoesNotExist() throws - * ElasticSearchOperationException { - * ResolverUtils testUtils = Mockito.mock(ResolverUtils.class); - * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); - * SearchableGroups testGroups = SearchableGroups.getTestInstance(); - * - * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); - * - * assertFalse(testGroups.getGroups().isEmpty()); - * - * assertEquals(null, testGroups.getSearchableGroups("Test")); } - */ + /* + * @Before public void init() throws NoSuchFieldException, SecurityException, + * IllegalArgumentException, IllegalAccessException { Field instance = + * SearchableGroups.class.getDeclaredField("instance"); instance.setAccessible(true); + * instance.set(null, null); } + * + * @Test public void test_FileNotFound() throws ElasticSearchOperationException { + * System.setProperty("AJSC_HOME", ""); SearchableGroups testGroups = + * SearchableGroups.getTestInstance(); assertTrue(testGroups.getGroups().isEmpty()); } + * + * @Test public void test_FileFoundWithProperlyFormatedConfig() throws + * ElasticSearchOperationException { ResolverUtils testUtils = Mockito.mock(ResolverUtils.class); + * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); + * SearchableGroups testGroups = SearchableGroups.getTestInstance(); + * + * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); + * + * assertFalse(testGroups.getGroups().isEmpty()); + * + * assertFalse(testGroups.getSearchableGroups("inventory").isEmpty()); } + * + * @Test public void test_FileFoundGroupDoesNotExist() throws ElasticSearchOperationException { + * ResolverUtils testUtils = Mockito.mock(ResolverUtils.class); + * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); + * SearchableGroups testGroups = SearchableGroups.getTestInstance(); + * + * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); + * + * assertFalse(testGroups.getGroups().isEmpty()); + * + * assertEquals(null, testGroups.getSearchableGroups("Test")); } + */ } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java index 15d46dd..70dd762 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java @@ -38,7 +38,7 @@ import org.onap.aai.sparky.viewandinspect.entity.QuerySearchEntity; /** * The Class ViewAndInspectSearchRequestTest. */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class ViewAndInspectSearchRequestTest { /** diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java index 023855b..d5fe2ae 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java @@ -39,7 +39,7 @@ import org.mockito.runners.MockitoJUnitRunner; /** * The Class EntityEntryTest. */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class EntityEntryTest { /** diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContextTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContextTest.java index 08ce29d..00c6267 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContextTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationContextTest.java @@ -56,84 +56,86 @@ import com.fasterxml.jackson.databind.node.ObjectNode; public class VisualizationContextTest {
- VisualizationContext context;
- ActiveInventoryDataProvider dataProvider;
- long contextId;
- OxmModelLoader oxmModelLoader;
- ExecutorService service;
+ VisualizationContext context;
+ ActiveInventoryDataProvider dataProvider;
+ long contextId;
+ OxmModelLoader oxmModelLoader;
+ ExecutorService service;
- @Before
- public void init() throws Exception {
- MockitoAnnotations.initMocks(this);
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/";
- TierSupportUiConstants.CONFIG_OXM_LOCATION = System.getProperty("AJSC_HOME")+"/bundleconfig-local/oxm/";
- oxmModelLoader = Mockito.spy(OxmModelLoader.getInstance());
- ActiveInventoryDataProvider dataProvider = new ActiveInventoryAdapter(new RestClientBuilder());
- SecureRandom random = new SecureRandom();
- long contextId = random.nextLong();
- ExecutorService service = NodeUtils.createNamedExecutor("SLNC-WORKER",
- 2, LoggerFactory.getInstance().getLogger(VisualizationContextTest.class));
- context = new VisualizationContext(contextId, dataProvider, service, oxmModelLoader);
- }
+ @Before
+ public void init() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/";
+ TierSupportUiConstants.CONFIG_OXM_LOCATION =
+ System.getProperty("AJSC_HOME") + "/bundleconfig-local/oxm/";
+ oxmModelLoader = Mockito.spy(OxmModelLoader.getInstance());
+ ActiveInventoryDataProvider dataProvider = new ActiveInventoryAdapter(new RestClientBuilder());
+ SecureRandom random = new SecureRandom();
+ long contextId = random.nextLong();
+ ExecutorService service = NodeUtils.createNamedExecutor("SLNC-WORKER", 2,
+ LoggerFactory.getInstance().getLogger(VisualizationContextTest.class));
+ context = new VisualizationContext(contextId, dataProvider, service, oxmModelLoader);
+ }
- @Test
- public void testExtractQueryParamsFromSelfLink_NullLink() {
- List<String> queryParams = context.extractQueryParamsFromSelfLink(null);
- Assert.assertEquals(queryParams.size(), 0);
- }
+ @Test
+ public void testExtractQueryParamsFromSelfLink_NullLink() {
+ List<String> queryParams = context.extractQueryParamsFromSelfLink(null);
+ Assert.assertEquals(queryParams.size(), 0);
+ }
- @Test
- public void testExtractQueryParamsFromSelfLink_NotNullLink() {
- context.extractQueryParamsFromSelfLink("https://localhost:9517/model/aai/webapp/index.html");
- }
+ @Test
+ public void testExtractQueryParamsFromSelfLink_NotNullLink() {
+ context.extractQueryParamsFromSelfLink("https://localhost:9517/model/aai/webapp/index.html");
+ }
- @Test
- public void testDecodeComplexAttributeGroup_NullAttributeGroup() {
- ActiveInventoryNode ain = new ActiveInventoryNode();
- ObjectNode node = JsonNodeFactory.instance.objectNode();
- boolean retValue = context.decodeComplexAttributeGroup(ain, node);
- Assert.assertFalse(retValue);
- }
+ @Test
+ public void testDecodeComplexAttributeGroup_NullAttributeGroup() {
+ ActiveInventoryNode ain = new ActiveInventoryNode();
+ ObjectNode node = JsonNodeFactory.instance.objectNode();
+ boolean retValue = context.decodeComplexAttributeGroup(ain, node);
+ Assert.assertFalse(retValue);
+ }
- @Test
- public void testDecodeComplexAttributeGroup_NotNullAttributeGroup() {
- ActiveInventoryNode ain = new ActiveInventoryNode();
- ObjectNode node1 = JsonNodeFactory.instance.objectNode();
- ObjectNode node2 = JsonNodeFactory.instance.objectNode();
- node1.set("model", node2);
- ObjectNode modelNode = JsonNodeFactory.instance.objectNode();
- node2.set("model-1", modelNode);
- modelNode.set("firstValue", JsonNodeFactory.instance.objectNode());
- modelNode.set("secondValue", JsonNodeFactory.instance.objectNode());
- modelNode.set("thirdValue", JsonNodeFactory.instance.objectNode());
- boolean retValue = context.decodeComplexAttributeGroup(ain, node1);
- Assert.assertFalse(retValue);
- }
+ @Test
+ public void testDecodeComplexAttributeGroup_NotNullAttributeGroup() {
+ ActiveInventoryNode ain = new ActiveInventoryNode();
+ ObjectNode node1 = JsonNodeFactory.instance.objectNode();
+ ObjectNode node2 = JsonNodeFactory.instance.objectNode();
+ node1.set("model", node2);
+ ObjectNode modelNode = JsonNodeFactory.instance.objectNode();
+ node2.set("model-1", modelNode);
+ modelNode.set("firstValue", JsonNodeFactory.instance.objectNode());
+ modelNode.set("secondValue", JsonNodeFactory.instance.objectNode());
+ modelNode.set("thirdValue", JsonNodeFactory.instance.objectNode());
+ boolean retValue = context.decodeComplexAttributeGroup(ain, node1);
+ Assert.assertFalse(retValue);
+ }
- @Test
- public void testProcessSelfLinks() {
- SearchableEntity entity = new SearchableEntity();
- entity.setId("id-1");
- entity.setEntityType("cloud-region");
- entity.setEntityPrimaryKeyValue("cloud-region-1");
- entity.setLink("https://localhost:9517/model/aai/webapp/index.html");
- QueryParams params = new QueryParams();
- params.setSearchTargetNodeId("id-1");
- Map<String, ActiveInventoryNode> nodeMap = context.getNodeCache();
- ActiveInventoryNode node = new ActiveInventoryNode();
- node.setEntityType("cloud-region");
- node.setNodeId("id-1");
- node.setPrimaryKeyName("cloud-region-1");
- node.setPrimaryKeyValue("cloud-region-1");
- node.addQueryParam(
+ @Test
+ public void testProcessSelfLinks() {
+ SearchableEntity entity = new SearchableEntity();
+ entity.setId("id-1");
+ entity.setEntityType("cloud-region");
+ entity.setEntityPrimaryKeyValue("cloud-region-1");
+ entity.setLink("https://localhost:9517/model/aai/webapp/index.html");
+ QueryParams params = new QueryParams();
+ params.setSearchTargetNodeId("id-1");
+ Map<String, ActiveInventoryNode> nodeMap = context.getNodeCache();
+ ActiveInventoryNode node = new ActiveInventoryNode();
+ node.setEntityType("cloud-region");
+ node.setNodeId("id-1");
+ node.setPrimaryKeyName("cloud-region-1");
+ node.setPrimaryKeyValue("cloud-region-1");
+ node.addQueryParam(
node.getEntityType() + "." + node.getPrimaryKeyName() + ":" + node.getPrimaryKeyValue());
- node.setNodeDepth(0);
- node.setRootNode(true);
- node.setSelfLink(entity.getLink());
- nodeMap.put("id-1", node);
- node.setResolvedSelfLink(true);
- context.processSelfLinks(entity, params);
+ node.setNodeDepth(0);
+ node.setRootNode(true);
+ node.setSelfLink(entity.getLink());
+ nodeMap.put("id-1", node);
+ node.setResolvedSelfLink(true);
+ context.processSelfLinks(entity, params);
- }
+ }
}
diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationServiceTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationServiceTest.java index 72ea1ed..fef0410 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationServiceTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/services/VisualizationServiceTest.java @@ -33,79 +33,64 @@ import org.onap.aai.sparky.viewandinspect.entity.QueryRequest; public class VisualizationServiceTest {
- VisualizationService service;
-
- @Before
- public void init() throws Exception {
- System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
- TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/src/test/resources/appconfig/";
- //TierSupportUiConstants.CONFIG_OXM_LOCATION = System.getProperty("AJSC_HOME")+"/bundleconfig-local/oxm/";
- TierSupportUiConstants.STATIC_CONFIG_APP_LOCATION = System.getProperty("AJSC_HOME")+"/bundleconfig-local/etc/appprops";
- OxmModelLoader loader = OxmModelLoader.getInstance();
- service = new VisualizationService(loader);
- }
-
- @Test
- public void testAnalyzeQueryRequestBody_InvalidQuery() {
- QueryRequest request = service.analyzeQueryRequestBody("query-json-1");
- Assert.assertNull(request);
- }
-
- @Test
- public void testAnalyzeQueryRequestBody_ValidQuery() {
- QueryRequest request = service.analyzeQueryRequestBody("{\"hashId\":\"hashid-1\"}");
- Assert.assertNotNull(request);
- }
- @Test
- public void testBuildVisualizationUsingGenericQuery_UnsuccessfulOperationResult() {
- QueryRequest queryRequest = new QueryRequest();
- queryRequest.setHashId("hash-id-1");
- service.buildVisualizationUsingGenericQuery(queryRequest);
- }
+ VisualizationService service;
- String queryRequest = "{\r\n" +
- " \"variables\": [],\r\n" +
- " \"info\": {\r\n" +
- " \"name\": \"NamedQuery\",\r\n" +
- " \"_postman_id\": \"8006823d-35ce-16ef-88e9-cd5b873c9e7b\",\r\n" +
- " \"schema\": \"https://schema.getpostman.com/json/collection/v2.0.0/collection.json\"\r\n" +
- " },\r\n" +
- " \"item\": [\r\n" +
- " {\r\n" +
- " \"name\": \"https://127.0.0.1:8443/aai/v11/service-design-and-creation/named-queries/named-query/0367193e-c785-4d5f-9cb8-7bc89dc9ddb7\",\r\n" +
- " \"request\": {\r\n" +
- " \"url\": \"https://127.0.0.1:8443/aai/v11/service-design-and-creation/named-queries/named-query/0367193e-c785-4d5f-9cb8-7bc89dc9ddb7\",\r\n" +
- " \"method\": \"POST\",\r\n" +
- " \"header\": [\r\n" +
- " {\r\n" +
- " \"key\": \"Content-Type\",\r\n" +
- " \"value\": \"application/json\",\r\n" +
- " \"description\": \"\"\r\n" +
- " },\r\n" +
- " {\r\n" +
- " \"key\": \"X-TransactionId\",\r\n" +
- " \"value\": \"9999\",\r\n" +
- " \"description\": \"\"\r\n" +
- " },\r\n" +
- " {\r\n" +
- " \"key\": \"X-FromAppId\",\r\n" +
- " \"value\": \"jimmy-postman\",\r\n" +
- " \"description\": \"\"\r\n" +
- " },\r\n" +
- " {\r\n" +
- " \"key\": \"Authorization\",\r\n" +
- " \"value\": \"Basic QUFJOkFBSQ==\",\r\n" +
- " \"description\": \"\"\r\n" +
- " }\r\n" +
- " ],\r\n" +
- " \"body\": {\r\n" +
- " \"mode\": \"raw\",\r\n" +
- " \"raw\": \"{\\n \\\"named-query-uuid\\\" : \\\"0367193e-c785-4d5f-9cb8-7bc89dc9ddb7\\\",\\n \\\"named-query-name\\\" : \\\"get-component-list\\\",\\n \\\"named-query-version\\\" : \\\"1.1\\\",\\n \\\"description\\\" : \\\"Named Query - Get Component List\\\",\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"property-collect-list\\\" : [ \\\"service-instance-id\\\", \\\"service-instance-name\\\" ],\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"1b2c9ba7-e449-4831-ba15-3073672f5ef2\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"3d560d81-57d0-438b-a2a1-5334dba0651a\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"fcec1b02-b2d0-4834-aef8-d71be04717dd\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"ff69d4e0-a8e8-4108-bdb0-dd63217e63c7\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"fcec1b02-b2d0-4834-aef8-d71be04717dd\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"1b2c9ba7-e449-4831-ba15-3073672f5ef2\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"3d560d81-57d0-438b-a2a1-5334dba0651a\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"ef86f9c5-2165-44f3-8fc3-96018b609ea5\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"acc6edd8-a8d4-4b93-afaa-0994068be14c\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"82194af1-3c2c-485a-8f44-420e22a9eaa4\\\"\\n } ]\\n } ]\\n }\\n } ]\\n }\\n}\\n\"\r\n" +
- " },\r\n" +
- " \"description\": \"\"\r\n" +
- " },\r\n" +
- " \"response\": []\r\n" +
- " }\r\n" +
- " ]\r\n" +
- "}";
+ @Before
+ public void init() throws Exception {
+ System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/'));
+ TierSupportUiConstants.DYNAMIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/src/test/resources/appconfig/";
+ // TierSupportUiConstants.CONFIG_OXM_LOCATION =
+ // System.getProperty("AJSC_HOME")+"/bundleconfig-local/oxm/";
+ TierSupportUiConstants.STATIC_CONFIG_APP_LOCATION =
+ System.getProperty("AJSC_HOME") + "/bundleconfig-local/etc/appprops";
+ OxmModelLoader loader = OxmModelLoader.getInstance();
+ service = new VisualizationService(loader);
+ }
+
+ @Test
+ public void testAnalyzeQueryRequestBody_InvalidQuery() {
+ QueryRequest request = service.analyzeQueryRequestBody("query-json-1");
+ Assert.assertNull(request);
+ }
+
+ @Test
+ public void testAnalyzeQueryRequestBody_ValidQuery() {
+ QueryRequest request = service.analyzeQueryRequestBody("{\"hashId\":\"hashid-1\"}");
+ Assert.assertNotNull(request);
+ }
+
+ @Test
+ public void testBuildVisualizationUsingGenericQuery_UnsuccessfulOperationResult() {
+ QueryRequest queryRequest = new QueryRequest();
+ queryRequest.setHashId("hash-id-1");
+ service.buildVisualizationUsingGenericQuery(queryRequest);
+ }
+
+ String queryRequest = "{\r\n" + " \"variables\": [],\r\n" + " \"info\": {\r\n"
+ + " \"name\": \"NamedQuery\",\r\n"
+ + " \"_postman_id\": \"8006823d-35ce-16ef-88e9-cd5b873c9e7b\",\r\n"
+ + " \"schema\": \"https://schema.getpostman.com/json/collection/v2.0.0/collection.json\"\r\n"
+ + " },\r\n" + " \"item\": [\r\n" + " {\r\n"
+ + " \"name\": \"https://127.0.0.1:8443/aai/v11/service-design-and-creation/named-queries/named-query/0367193e-c785-4d5f-9cb8-7bc89dc9ddb7\",\r\n"
+ + " \"request\": {\r\n"
+ + " \"url\": \"https://127.0.0.1:8443/aai/v11/service-design-and-creation/named-queries/named-query/0367193e-c785-4d5f-9cb8-7bc89dc9ddb7\",\r\n"
+ + " \"method\": \"POST\",\r\n" + " \"header\": [\r\n"
+ + " {\r\n" + " \"key\": \"Content-Type\",\r\n"
+ + " \"value\": \"application/json\",\r\n"
+ + " \"description\": \"\"\r\n" + " },\r\n"
+ + " {\r\n" + " \"key\": \"X-TransactionId\",\r\n"
+ + " \"value\": \"9999\",\r\n"
+ + " \"description\": \"\"\r\n" + " },\r\n"
+ + " {\r\n" + " \"key\": \"X-FromAppId\",\r\n"
+ + " \"value\": \"jimmy-postman\",\r\n"
+ + " \"description\": \"\"\r\n" + " },\r\n"
+ + " {\r\n" + " \"key\": \"Authorization\",\r\n"
+ + " \"value\": \"Basic QUFJOkFBSQ==\",\r\n"
+ + " \"description\": \"\"\r\n" + " }\r\n"
+ + " ],\r\n" + " \"body\": {\r\n"
+ + " \"mode\": \"raw\",\r\n"
+ + " \"raw\": \"{\\n \\\"named-query-uuid\\\" : \\\"0367193e-c785-4d5f-9cb8-7bc89dc9ddb7\\\",\\n \\\"named-query-name\\\" : \\\"get-component-list\\\",\\n \\\"named-query-version\\\" : \\\"1.1\\\",\\n \\\"description\\\" : \\\"Named Query - Get Component List\\\",\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"property-collect-list\\\" : [ \\\"service-instance-id\\\", \\\"service-instance-name\\\" ],\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"1b2c9ba7-e449-4831-ba15-3073672f5ef2\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"3d560d81-57d0-438b-a2a1-5334dba0651a\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"fcec1b02-b2d0-4834-aef8-d71be04717dd\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"ff69d4e0-a8e8-4108-bdb0-dd63217e63c7\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"fcec1b02-b2d0-4834-aef8-d71be04717dd\\\"\\n } ]\\n } ]\\n }\\n }, {\\n \\\"named-query-elements\\\" : {\\n \\\"named-query-element\\\" : [ {\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"1b2c9ba7-e449-4831-ba15-3073672f5ef2\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"3d560d81-57d0-438b-a2a1-5334dba0651a\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"ef86f9c5-2165-44f3-8fc3-96018b609ea5\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"acc6edd8-a8d4-4b93-afaa-0994068be14c\\\"\\n } ]\\n } ]\\n }\\n } ]\\n },\\n \\\"relationship-list\\\" : {\\n \\\"relationship\\\" : [ {\\n \\\"related-to\\\" : \\\"model\\\",\\n \\\"relationship-data\\\" : [ {\\n \\\"relationship-key\\\" : \\\"model.model-invariant-id\\\",\\n \\\"relationship-value\\\" : \\\"82194af1-3c2c-485a-8f44-420e22a9eaa4\\\"\\n } ]\\n } ]\\n }\\n } ]\\n }\\n}\\n\"\r\n"
+ + " },\r\n" + " \"description\": \"\"\r\n" + " },\r\n"
+ + " \"response\": []\r\n" + " }\r\n" + " ]\r\n" + "}";
}
|