diff options
author | mark.j.leonard <mark.j.leonard@gmail.com> | 2019-01-14 15:48:40 +0000 |
---|---|---|
committer | mark.j.leonard <mark.j.leonard@gmail.com> | 2019-01-14 15:55:10 +0000 |
commit | c7e9ff11f28009c4fbc13f7ed1a3ffbb765d358b (patch) | |
tree | 7b8382f8eb798a0fe42a4e946b2d3a1efb370a3a /src/main | |
parent | 412d5d84761ca7d32061d4b8c9b8c22bbe4c014b (diff) |
Fix Java code smells (Sonar and Checkstyle)
Change-Id: I04cb9b4dee75560777bb3533f6a58268e10fc217
Issue-ID: AAI-2057
Signed-off-by: mark.j.leonard <mark.j.leonard@gmail.com>
Diffstat (limited to 'src/main')
15 files changed, 773 insertions, 781 deletions
diff --git a/src/main/java/org/onap/aai/auth/AAIMicroServiceAuthCore.java b/src/main/java/org/onap/aai/auth/AAIMicroServiceAuthCore.java index 25273fc..4373711 100644 --- a/src/main/java/org/onap/aai/auth/AAIMicroServiceAuthCore.java +++ b/src/main/java/org/onap/aai/auth/AAIMicroServiceAuthCore.java @@ -1,4 +1,4 @@ -/* +/** * ============LICENSE_START=================================================== * Copyright (c) 2018 Amdocs * ============================================================================ @@ -6,7 +6,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -54,7 +54,7 @@ public class AAIMicroServiceAuthCore { private static boolean timerSet = false; private static String policyAuthFileName; - public enum HTTP_METHODS { + public enum HttpMethods { GET, PUT, DELETE, @@ -73,6 +73,11 @@ public class AAIMicroServiceAuthCore { AAIMicroServiceAuthCore.defaultAuthFileName = Paths.get(defaultAuthFileName); } + /** + * @param authPolicyFile + * @throws AAIAuthException + * if the policy file cannot be loaded + */ public static synchronized void init(String authPolicyFile) throws AAIAuthException { try { @@ -183,7 +188,7 @@ public class AAIMicroServiceAuthCore { JsonNode methodsNode = functionNode.path("methods"); if (methodsNode.size() == 0) { - for (HTTP_METHODS method : HTTP_METHODS.values()) { + for (HttpMethods method : HttpMethods.values()) { String fullFunctionName = method.toString() + ":" + functionName; applicationLogger.debug("Installing (all methods) " + fullFunctionName + " on role " + roleName); role.addAllowedFunction(fullFunctionName); @@ -239,7 +244,7 @@ public class AAIMicroServiceAuthCore { } public boolean hasAllowedFunction(String functionName) { - return allowedFunctions.contains(functionName) ? true : false; + return allowedFunctions.contains(functionName); } } diff --git a/src/main/java/org/onap/aai/validation/ValidationServiceApplication.java b/src/main/java/org/onap/aai/validation/ValidationServiceApplication.java index 8bf7a44..409e375 100644 --- a/src/main/java/org/onap/aai/validation/ValidationServiceApplication.java +++ b/src/main/java/org/onap/aai/validation/ValidationServiceApplication.java @@ -1,4 +1,4 @@ -/* +/* * ============LICENSE_START=================================================== * Copyright (c) 2018 Amdocs * ============================================================================ @@ -17,33 +17,26 @@ */ package org.onap.aai.validation; +import java.util.HashMap; +import java.util.Map; import org.eclipse.jetty.util.security.Password; -import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; -import java.util.HashMap; - - /** * Validation Service Spring Boot Application. */ @SpringBootApplication -@ComponentScan(basePackages = "org.onap.aai.validation") +@ComponentScan(basePackages = "org.onap.aai.validation.config") @ImportResource("classpath:validation-service-beans.xml") public class ValidationServiceApplication extends SpringBootServletInitializer { - // public static void main(String[] args) { - // SpringApplication.run(ValidationServiceApplication.class, args); - // } - - public static void main(String[] args) { - HashMap<String, Object> props = new HashMap<>(); + Map<String, Object> props = new HashMap<>(); String keyStorePassword = System.getProperty("KEY_STORE_PASSWORD"); if (keyStorePassword != null && !keyStorePassword.isEmpty()) { props.put("server.ssl.key-store-password", Password.deobfuscate(keyStorePassword)); @@ -53,5 +46,4 @@ public class ValidationServiceApplication extends SpringBootServletInitializer { .run(args); } - } diff --git a/src/main/java/org/onap/aai/validation/config/EventReaderConfig.java b/src/main/java/org/onap/aai/validation/config/EventReaderConfig.java index c819351..377cffa 100644 --- a/src/main/java/org/onap/aai/validation/config/EventReaderConfig.java +++ b/src/main/java/org/onap/aai/validation/config/EventReaderConfig.java @@ -24,140 +24,140 @@ import org.springframework.beans.factory.annotation.Value; */ public class EventReaderConfig extends PropertiesConfig { - @Value("${event.domain.path}") - private String eventDomainPath; + @Value("${event.domain.path}") + private String eventDomainPath; @Value("${event.action.path}") - private String eventActionPath; + private String eventActionPath; - @Value("${event.type.path}") - private String eventTypePath; + @Value("${event.type.path}") + private String eventTypePath; - @Value("${event.entity.type.path}") - private String entityTypePath; + @Value("${event.entity.type.path}") + private String entityTypePath; - @Value("${event.entity.type.top.path}") - private String topEntityTypePath; + @Value("${event.entity.type.top.path}") + private String topEntityTypePath; - @Value("${event.entity.link.path}") - private String entityLinkPath; + @Value("${event.entity.link.path}") + private String entityLinkPath; - @Value("${event.entity.link.delimiter}") - private String entityLinkDelimiter; - - @Value("${event.entity.path}") - private String entityPath; - - @Value("${event.entity.nested.path}") - private String nestedEntityPath; - - /** Entity relative path. Use when the entity has been extracted from the event. */ - @Value("${entity.id.path}") - private String entityIdPath; - - /** Entity relative path. Use when the entity has been extracted from the event. */ - @Value("${entity.resource.version.path}") - private String entityResourceVersionPath; - - public String getEventDomainPath() { - return eventDomainPath; - } - - public void setEventDomainPath(String eventDomainPath) { - this.eventDomainPath = eventDomainPath; - } - - public String getEventActionPath() { - return eventActionPath; - } - - public void setEventActionPath(String eventActionPath) { - this.eventActionPath = eventActionPath; - } - - public String getEventTypePath() { - return eventTypePath; - } - - public void setEventTypePath(String eventTypePath) { - this.eventTypePath = eventTypePath; - } - - public String getTopEntityTypePath() { - return topEntityTypePath; - } - - public void setTopEntityTypePath(String topEntityTypePath) { - this.topEntityTypePath = topEntityTypePath; - } - - public String getEntityLinkPath() { - return entityLinkPath; - } - - public void setEntityLinkPath(String entityLinkPath) { - this.entityLinkPath = entityLinkPath; - } - - public String getEntityLinkDelimiter() { - return entityLinkDelimiter; - } - - public void setEntityLinkDelimiter(String entityLinkDelimiter) { - this.entityLinkDelimiter = entityLinkDelimiter; - } - - public String getEntityTypePath() { - return entityTypePath; - } - - public void setEntityTypePath(String entityTypePath) { - this.entityTypePath = entityTypePath; - } - - public String getEntityPath() { - return entityPath; - } - - public void setEntityPath(String entityPath) { - this.entityPath = entityPath; - } - - /** - * Formats the nested entity path using the entity type provided. - * - * @param entityType - * an entity type - * @return the formatted nested entity path - */ - public String getNestedEntityPath(String entityType) { - return formatter(nestedEntityPath, entityType); - } - - public void setNestedEntityPath(String nestedEntityPath) { - this.nestedEntityPath = nestedEntityPath; - } - - /** - * Formats the entity ID path using the entity type provided. - * - * @param entityType - * an entity type - * @return the formatted entity ID path - */ - public String getEntityIdPath(String entityType) { - return formatter(entityIdPath, entityType); - } - - public void setEntityIdPath(String entityIdPath) { - this.entityIdPath = entityIdPath; - } - - public String getEntityResourceVersionPath() { - return entityResourceVersionPath; - } - - public void setEntityResourceVersionPath(String entityResourceVersionPath) { - this.entityResourceVersionPath = entityResourceVersionPath; - } -}
\ No newline at end of file + @Value("${event.entity.link.delimiter}") + private String entityLinkDelimiter; + + @Value("${event.entity.path}") + private String entityPath; + + @Value("${event.entity.nested.path}") + private String nestedEntityPath; + + /** Entity relative path. Use when the entity has been extracted from the event. */ + @Value("${entity.id.path}") + private String entityIdPath; + + /** Entity relative path. Use when the entity has been extracted from the event. */ + @Value("${entity.resource.version.path}") + private String entityResourceVersionPath; + + public String getEventDomainPath() { + return eventDomainPath; + } + + public void setEventDomainPath(String eventDomainPath) { + this.eventDomainPath = eventDomainPath; + } + + public String getEventActionPath() { + return eventActionPath; + } + + public void setEventActionPath(String eventActionPath) { + this.eventActionPath = eventActionPath; + } + + public String getEventTypePath() { + return eventTypePath; + } + + public void setEventTypePath(String eventTypePath) { + this.eventTypePath = eventTypePath; + } + + public String getTopEntityTypePath() { + return topEntityTypePath; + } + + public void setTopEntityTypePath(String topEntityTypePath) { + this.topEntityTypePath = topEntityTypePath; + } + + public String getEntityLinkPath() { + return entityLinkPath; + } + + public void setEntityLinkPath(String entityLinkPath) { + this.entityLinkPath = entityLinkPath; + } + + public String getEntityLinkDelimiter() { + return entityLinkDelimiter; + } + + public void setEntityLinkDelimiter(String entityLinkDelimiter) { + this.entityLinkDelimiter = entityLinkDelimiter; + } + + public String getEntityTypePath() { + return entityTypePath; + } + + public void setEntityTypePath(String entityTypePath) { + this.entityTypePath = entityTypePath; + } + + public String getEntityPath() { + return entityPath; + } + + public void setEntityPath(String entityPath) { + this.entityPath = entityPath; + } + + /** + * Formats the nested entity path using the entity type provided. + * + * @param entityType + * an entity type + * @return the formatted nested entity path + */ + public String getNestedEntityPath(String entityType) { + return formatter(nestedEntityPath, entityType); + } + + public void setNestedEntityPath(String nestedEntityPath) { + this.nestedEntityPath = nestedEntityPath; + } + + /** + * Formats the entity ID path using the entity type provided. + * + * @param entityType + * an entity type + * @return the formatted entity ID path + */ + public String getEntityIdPath(String entityType) { + return formatter(entityIdPath, entityType); + } + + public void setEntityIdPath(String entityIdPath) { + this.entityIdPath = entityIdPath; + } + + public String getEntityResourceVersionPath() { + return entityResourceVersionPath; + } + + public void setEntityResourceVersionPath(String entityResourceVersionPath) { + this.entityResourceVersionPath = entityResourceVersionPath; + } +} diff --git a/src/main/java/org/onap/aai/validation/config/ModelConfig.java b/src/main/java/org/onap/aai/validation/config/ModelConfig.java index 02e14bc..d4b01b1 100644 --- a/src/main/java/org/onap/aai/validation/config/ModelConfig.java +++ b/src/main/java/org/onap/aai/validation/config/ModelConfig.java @@ -25,15 +25,15 @@ import org.springframework.beans.factory.annotation.Value; */ public class ModelConfig { - @Value("${model.cache.expirySeconds}") - private Long modelCacheExpirySeconds; + @Value("${model.cache.expirySeconds}") + private Long modelCacheExpirySeconds; - public Long getModelCacheExpirySeconds() { - return modelCacheExpirySeconds; - } + public Long getModelCacheExpirySeconds() { + return modelCacheExpirySeconds; + } - public void setModelCacheExpirySeconds(Long modelCacheExpirySeconds) { - this.modelCacheExpirySeconds = modelCacheExpirySeconds; - } + public void setModelCacheExpirySeconds(Long modelCacheExpirySeconds) { + this.modelCacheExpirySeconds = modelCacheExpirySeconds; + } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/validation/config/PropertiesConfig.java b/src/main/java/org/onap/aai/validation/config/PropertiesConfig.java index cf4bcb2..9232c4c 100644 --- a/src/main/java/org/onap/aai/validation/config/PropertiesConfig.java +++ b/src/main/java/org/onap/aai/validation/config/PropertiesConfig.java @@ -24,18 +24,18 @@ import java.text.MessageFormat; */ public class PropertiesConfig { - /** - * Replaces place-holders in property values. - * - * @param s - * a string with place-holders in the form {n} - * @param args - * values for place-holders - * @return a formated String with replaced place-holders. - */ - public String formatter(String s, Object... args) { - MessageFormat formatter = new MessageFormat(""); - formatter.applyPattern(s); - return formatter.format(args); - } + /** + * Replaces place-holders in property values. + * + * @param s + * a string with place-holders in the form {n} + * @param args + * values for place-holders + * @return a formated String with replaced place-holders. + */ + public String formatter(String s, Object... args) { + MessageFormat formatter = new MessageFormat(""); + formatter.applyPattern(s); + return formatter.format(args); + } } diff --git a/src/main/java/org/onap/aai/validation/config/RestConfig.java b/src/main/java/org/onap/aai/validation/config/RestConfig.java index e99d6c2..344c203 100644 --- a/src/main/java/org/onap/aai/validation/config/RestConfig.java +++ b/src/main/java/org/onap/aai/validation/config/RestConfig.java @@ -111,7 +111,7 @@ public class RestConfig { * @return the decrypted password */ public String getTrustStorePassword() { - return trustStorePassword; + return trustStorePassword; } public void setTrustStorePassword(String trustStorePassword) { @@ -132,7 +132,7 @@ public class RestConfig { * @return the decrypted password */ public String getKeyStorePassword() { - return keyStorePassword; + return keyStorePassword; } public void setKeyStorePassword(String keyStorePassword) { diff --git a/src/main/java/org/onap/aai/validation/config/RuleIndexingConfig.java b/src/main/java/org/onap/aai/validation/config/RuleIndexingConfig.java index 1d27705..67b0b8a 100644 --- a/src/main/java/org/onap/aai/validation/config/RuleIndexingConfig.java +++ b/src/main/java/org/onap/aai/validation/config/RuleIndexingConfig.java @@ -65,7 +65,7 @@ public class RuleIndexingConfig extends PropertiesConfig { } public boolean skipOxmValidation(String event) { - if(excludedOxmValidationEvents == null) { + if (excludedOxmValidationEvents == null) { return false; } return excludedOxmValidationEvents.contains(event); diff --git a/src/main/java/org/onap/aai/validation/config/TopicConfig.java b/src/main/java/org/onap/aai/validation/config/TopicConfig.java index ccf5d51..327db5e 100644 --- a/src/main/java/org/onap/aai/validation/config/TopicConfig.java +++ b/src/main/java/org/onap/aai/validation/config/TopicConfig.java @@ -46,7 +46,7 @@ public class TopicConfig { List<Topic> publisherTopics = new ArrayList<>(); @Autowired - public TopicConfig (@Value("${consumer.topic.names}") final String consumerNames, + public TopicConfig(@Value("${consumer.topic.names}") final String consumerNames, @Value("${publisher.topic.names}") final String publisherNames) { consumerTopicNames = Arrays.asList(consumerNames.split(",")); publisherTopicNames = Arrays.asList(publisherNames.split(",")); @@ -57,8 +57,7 @@ public class TopicConfig { * * @return a list of topic configurations. */ - public List<Topic> getConsumerTopics() - { + public List<Topic> getConsumerTopics() { return populateTopics(consumerTopics, consumerTopicNames); } @@ -73,31 +72,31 @@ public class TopicConfig { } /** - * Populates the topics list with topic objects created from each item in the topicNames list. - * - * @param topics - * The topic list to populate. - * @param topicNames - * The list of topic names to populate the topic list with. - * @return The populated topic list. - */ - private List<Topic> populateTopics(List<Topic> topics, List<String> topicNames) { - if (topics.isEmpty()) { - for (String topicName : topicNames) { - Topic topicConfig = new Topic(); - topicConfig.setName(getTopicProperties().getProperty(topicName + ".name")); - topicConfig.setHost(getTopicProperties().getProperty(topicName + ".host")); - topicConfig.setUsername(getTopicProperties().getProperty(topicName + ".username")); - topicConfig.setPassword(getTopicProperties().getProperty(topicName + ".password")); - topicConfig.setPartition(getTopicProperties().getProperty(topicName + ".publisher.partition")); - topicConfig.setConsumerGroup(getTopicProperties().getProperty(topicName + ".consumer.group")); - topicConfig.setConsumerId(getTopicProperties().getProperty(topicName + ".consumer.id")); - topicConfig.setTransportType(getTopicProperties().getProperty(topicName + ".transport.type")); - topics.add(topicConfig); - } - } - return topics; - } + * Populates the topics list with topic objects created from each item in the topicNames list. + * + * @param topics + * The topic list to populate. + * @param topicNames + * The list of topic names to populate the topic list with. + * @return The populated topic list. + */ + private List<Topic> populateTopics(List<Topic> topics, List<String> topicNames) { + if (topics.isEmpty()) { + for (String topicName : topicNames) { + Topic topicConfig = new Topic(); + topicConfig.setName(getTopicProperties().getProperty(topicName + ".name")); + topicConfig.setHost(getTopicProperties().getProperty(topicName + ".host")); + topicConfig.setUsername(getTopicProperties().getProperty(topicName + ".username")); + topicConfig.setPassword(getTopicProperties().getProperty(topicName + ".password")); + topicConfig.setPartition(getTopicProperties().getProperty(topicName + ".publisher.partition")); + topicConfig.setConsumerGroup(getTopicProperties().getProperty(topicName + ".consumer.group")); + topicConfig.setConsumerId(getTopicProperties().getProperty(topicName + ".consumer.id")); + topicConfig.setTransportType(getTopicProperties().getProperty(topicName + ".transport.type")); + topics.add(topicConfig); + } + } + return topics; + } public List<String> getConsumerTopicNames() { return consumerTopicNames; @@ -161,7 +160,7 @@ public class TopicConfig { } public String getPassword() { - return password; + return password; } public void setPassword(String password) { @@ -206,8 +205,8 @@ public class TopicConfig { @Override public int hashCode() { - return Objects.hash(this.consumerGroup, this.consumerId, this.host, this.username, this.name, this.partition, - this.password, this.transportType); + return Objects.hash(this.consumerGroup, this.consumerId, this.host, this.username, this.name, + this.partition, this.password, this.transportType); } @Override @@ -234,8 +233,8 @@ public class TopicConfig { @Override public String toString() { - return "Topic [name=" + name + ", host=" + host + ", username=" + username + ", password=" + password + ", partition=" - + partition + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + return "Topic [name=" + name + ", host=" + host + ", username=" + username + ", password=" + password + + ", partition=" + partition + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + ", transportType =" + transportType + "]"; } } diff --git a/src/main/java/org/onap/aai/validation/config/TopicPropertiesConfig.java b/src/main/java/org/onap/aai/validation/config/TopicPropertiesConfig.java index 4742cef..4a2dc16 100644 --- a/src/main/java/org/onap/aai/validation/config/TopicPropertiesConfig.java +++ b/src/main/java/org/onap/aai/validation/config/TopicPropertiesConfig.java @@ -1,4 +1,4 @@ -/* +/** * ============LICENSE_START=================================================== * Copyright (c) 2018 Amdocs * ============================================================================ @@ -6,7 +6,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,19 +17,21 @@ */ package org.onap.aai.validation.config; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import org.onap.aai.validation.logging.ApplicationMsgs; import org.onap.aai.validation.logging.LogHelper; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.PropertiesFactoryBean; -import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - @Configuration public class TopicPropertiesConfig { @@ -38,38 +40,28 @@ public class TopicPropertiesConfig { @Value("${topics.properties.location}") private String topicsPropertiesLocation; - private static final String[] TOPICS_PROPERTIES_LOCATION_TPL = { "file:./%s/*.properties", "classpath:/%s/*.properties" }; + private static final String[] propertyFilePatterns = { "file:./%s/*.properties", "classpath:/%s/*.properties" }; - @Bean(name="topicProperties") + @Bean(name = "topicProperties") public Properties topicProperties() throws IOException { - PropertiesFactoryBean config = new PropertiesFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - List<Resource> resouceList = new ArrayList<Resource>(); - try { - for (String p : bldrsPropLoc2Path(topicsPropertiesLocation)) { - Resource[] resources = resolver.getResources(p); - if (resources != null && resources.length > 0) { - for (Resource resource : resources) { - resouceList.add(resource); - } - break; - } + List<Resource> resourceList = new ArrayList<>(); + for (String patternTemplate : propertyFilePatterns) { + String pattern = String.format(patternTemplate, topicsPropertiesLocation).replace("//", "/"); + applicationLogger.info(ApplicationMsgs.LOAD_PROPERTIES, "using pattern " + pattern); + try { + resourceList.addAll(Arrays.asList(resolver.getResources(pattern))); + } catch (FileNotFoundException e) { + applicationLogger.info(ApplicationMsgs.LOAD_PROPERTIES, e.getMessage()); } - } catch (Exception e) { - applicationLogger.logAuditError(e); } - config.setLocations(resouceList.toArray(new Resource[]{})); + + applicationLogger.info(ApplicationMsgs.LOAD_PROPERTIES, resourceList.toString()); + + PropertiesFactoryBean config = new PropertiesFactoryBean(); + config.setLocations(resourceList.toArray(new Resource[resourceList.size()])); config.afterPropertiesSet(); return config.getObject(); } - private static String[] bldrsPropLoc2Path(String topicsPropertiesLocation) { - String[] res = new String[TOPICS_PROPERTIES_LOCATION_TPL.length]; - int indx = 0; - for (String tmpl : TOPICS_PROPERTIES_LOCATION_TPL) { - res[indx++] = String.format(tmpl, topicsPropertiesLocation).replace("//", "/"); - } - return res; - } - } diff --git a/src/main/java/org/onap/aai/validation/config/ValidationControllerConfig.java b/src/main/java/org/onap/aai/validation/config/ValidationControllerConfig.java index 4110175..af01be3 100644 --- a/src/main/java/org/onap/aai/validation/config/ValidationControllerConfig.java +++ b/src/main/java/org/onap/aai/validation/config/ValidationControllerConfig.java @@ -25,52 +25,52 @@ import org.springframework.beans.factory.annotation.Value; */ public class ValidationControllerConfig extends PropertiesConfig { - @Value("${event.domain}") - private String eventDomain; + @Value("${event.domain}") + private String eventDomain; - @Value("#{'${event.action.exclude}'.split(',')}") - private List<String> excludedEventActions; + @Value("#{'${event.action.exclude}'.split(',')}") + private List<String> excludedEventActions; - @Value("#{'${event.type.rule}'.split(',')}") - private List<String> eventTypeRule; + @Value("#{'${event.type.rule}'.split(',')}") + private List<String> eventTypeRule; - @Value("#{'${event.type.model}'.split(',')}") - private List<String> eventTypeModel; + @Value("#{'${event.type.model}'.split(',')}") + private List<String> eventTypeModel; - @Value("${event.type.end:END-EVENT}") + @Value("${event.type.end:END-EVENT}") private String eventTypeEnd; - public String getEventDomain() { - return eventDomain; - } + public String getEventDomain() { + return eventDomain; + } - public void setEventDomain(String eventDomain) { - this.eventDomain = eventDomain; - } + public void setEventDomain(String eventDomain) { + this.eventDomain = eventDomain; + } - public List<String> getExcludedEventActions() { - return excludedEventActions; - } + public List<String> getExcludedEventActions() { + return excludedEventActions; + } - public void setExcludedEventActions(List<String> excludedEventActions) { - this.excludedEventActions = excludedEventActions; - } + public void setExcludedEventActions(List<String> excludedEventActions) { + this.excludedEventActions = excludedEventActions; + } - public List<String> getEventTypeRule() { - return eventTypeRule; - } + public List<String> getEventTypeRule() { + return eventTypeRule; + } - public void setEventTypeRule(List<String> eventTypeRule) { - this.eventTypeRule = eventTypeRule; - } + public void setEventTypeRule(List<String> eventTypeRule) { + this.eventTypeRule = eventTypeRule; + } - public List<String> getEventTypeModel() { - return eventTypeModel; - } + public List<String> getEventTypeModel() { + return eventTypeModel; + } - public void setEventTypeModel(List<String> eventTypeModel) { - this.eventTypeModel = eventTypeModel; - } + public void setEventTypeModel(List<String> eventTypeModel) { + this.eventTypeModel = eventTypeModel; + } public String getEventTypeEnd() { return eventTypeEnd; diff --git a/src/main/java/org/onap/aai/validation/config/ValidationServiceAuthConfig.java b/src/main/java/org/onap/aai/validation/config/ValidationServiceAuthConfig.java index 62280fa..cd42e02 100644 --- a/src/main/java/org/onap/aai/validation/config/ValidationServiceAuthConfig.java +++ b/src/main/java/org/onap/aai/validation/config/ValidationServiceAuthConfig.java @@ -21,26 +21,26 @@ import org.springframework.beans.factory.annotation.Value; public class ValidationServiceAuthConfig { - @Value("${auth.authentication.disable}") - private boolean authenticationDisable; + @Value("${auth.authentication.disable}") + private boolean authenticationDisable; - @Value("${auth.policy.file}") - private String authPolicyFile; + @Value("${auth.policy.file}") + private String authPolicyFile; - public boolean isAuthenticationDisable() { - return authenticationDisable; - } + public boolean isAuthenticationDisable() { + return authenticationDisable; + } - public void setAuthenticationDisable(boolean authenticationDisable) { - this.authenticationDisable = authenticationDisable; - } + public void setAuthenticationDisable(boolean authenticationDisable) { + this.authenticationDisable = authenticationDisable; + } - public String getAuthPolicyFile() { - return authPolicyFile; - } + public String getAuthPolicyFile() { + return authPolicyFile; + } - public void setAuthPolicyFile(String authPolicyFile) { - this.authPolicyFile = authPolicyFile; - } + public void setAuthPolicyFile(String authPolicyFile) { + this.authPolicyFile = authPolicyFile; + } } diff --git a/src/main/java/org/onap/aai/validation/modeldriven/parser/XMLModelParser.java b/src/main/java/org/onap/aai/validation/modeldriven/parser/XMLModelParser.java index cf7aa38..5d4ab9d 100644 --- a/src/main/java/org/onap/aai/validation/modeldriven/parser/XMLModelParser.java +++ b/src/main/java/org/onap/aai/validation/modeldriven/parser/XMLModelParser.java @@ -98,7 +98,6 @@ public class XMLModelParser { * The XPath expression to run on the Node. * @return A List of Nodes representing the result of the XPath expression. */ - @SuppressWarnings("unchecked") public static List<Node> getObjectsFromXPath(Node currentNode, String xPath) { return currentNode.selectNodes(xPath); } diff --git a/src/main/java/org/onap/aai/validation/modeldriven/validator/InstanceReader.java b/src/main/java/org/onap/aai/validation/modeldriven/validator/InstanceReader.java index 7832e51..2d8544b 100644 --- a/src/main/java/org/onap/aai/validation/modeldriven/validator/InstanceReader.java +++ b/src/main/java/org/onap/aai/validation/modeldriven/validator/InstanceReader.java @@ -41,276 +41,279 @@ import org.onap.aai.validation.reader.OxmReader; */ public class InstanceReader { - private static final String MODEL_NAME = "model-name"; - private static final String[] INVALID_ENTRIES = { "inventory-response-items", "extra-properties", MODEL_NAME }; - private static final String RESOURCE_VERSION = "resource-version"; - private static final String JSON_PATH_MODEL_ID = "$.*.persona-model-id"; - - private JsonReader jsonReader; - private OxmReader oxmReader; - private JsonParser jsonParser = new JsonParser(); - - /** - * @param jsonReader - * @param oxmReader - */ - @Inject - public InstanceReader(JsonReader jsonReader, OxmReader oxmReader) { - this.jsonReader = jsonReader; - this.oxmReader = oxmReader; - } - - public OxmReader getOxmReader() { - return oxmReader; - } - - /** - * Gets object instance values. - * - * @param json - * a Named Query JSON payload - * @param mapping - * defines the paths that allow the extraction of values from the object instance. This includes: - * <ul> - * <li>origin: path that serves as the starting point for the instance search</li> - * <li>root: path to underlying instance objects that can be examined by recursively calling the - * getValues method</li> - * </ul> - * - * @return a {@link Multimap} of instances keyed by their model id. - * @throws ValidationServiceException - */ - public Multimap<String, String> getValues(String json, ModelInstanceMapper mapping) throws ValidationServiceException { - Multimap<String, String> values = HashMultimap.create(); - - DocumentContext document = jsonReader.parse(json); - - if (MappingType.RELATIONSHIP.equals(mapping.getMappingType())) { - String rootPath = mapping.getInstance().getRoot(); - if (rootPath == null || rootPath.isEmpty()) { - throw new ValidationServiceException(ValidationServiceError.INSTANCE_MAPPING_ROOT_ERROR); - } - - JsonElement jsonElement = jsonReader.getJsonElement(document, rootPath); - - if (jsonElement instanceof JsonArray) { - JsonArray jsonArray = jsonElement.getAsJsonArray(); - - processRelatedObjects(values, jsonArray); - } - } else { - // We are dealing with attributes. - String valuePath = mapping.getInstance().getValue(); - if (valuePath != null && !valuePath.isEmpty()) { - List<String> attributes = jsonReader.get(json, valuePath); - for (String attribute : attributes) { - values.put(attribute, null); - } - } - } - - return values; - } - - /** - * Gets the instance type, e.g. connector, pserver, etc. - * - * @param json - * a Named Query JSON payload - * @return the type of the entity - */ - public String getInstanceType(String json) { - return getNamedQueryEntity(json).getEntityType(); - } - - /** - * Gets the id of the instance. Uses the {@link OxmReader} to identify the property holding the primary key.<br> - * - * WARNING: Some types of object appear to have more than one primary key. This method uses the first primary key. - * - * @param json - * a Named Query JSON payload - * @return the identifier of the object instance - * @throws ValidationServiceException - */ - public String getInstanceId(String json) throws ValidationServiceException { - String instanceId = null; - - InstanceEntity entity = getNamedQueryEntity(json); - - List<String> primaryKeys = oxmReader.getPrimaryKeys(entity.getEntityType()); - - if (primaryKeys != null && !primaryKeys.isEmpty()) { - JsonObject instance = entity.getObject().getAsJsonObject(); - JsonElement primaryKey = instance.get(primaryKeys.get(0)); - instanceId = primaryKey == null ? null : primaryKey.getAsString(); - } - - return instanceId; - } - - /** - * Strips the instance out of its payload wrapping. - * - * @param json - * a Named Query JSON payload - * @param mappings - * the definition of the paths that allow the extraction of the instance from the JSON payload - * @return - * @throws ValidationServiceException - */ - public String getInstance(String json, List<ModelInstanceMapper> mappings) throws ValidationServiceException { - String origin = mappings.iterator().next().getInstance().getOrigin(); - List<String> jsonList = jsonReader.get(json, origin); - - if (!jsonList.isEmpty()) { - return jsonList.get(0); - } else { - throw new ValidationServiceException(ValidationServiceError.INSTANCE_READER_NO_INSTANCE, origin, json); - } - } - - /** - * Extracts the entity from a Named Query JSON payload. - * - * @param json - * a Named Query JSON payload - * @return an {@link InstanceEntity} object - */ - public InstanceEntity getNamedQueryEntity(String json) { - return getNamedQueryEntity(jsonParser.parse(json).getAsJsonObject()); - } - - /** - * Gets the model identifier of a given entity. - * - * @param entity - * a JSON entity - * @return a model identifier attribute value if the attribute exists else a null is returned. - * @throws ValidationServiceException - */ - public String getModelId(String entity) throws ValidationServiceException { - String modelId = null; - List<String> readResult = jsonReader.get(entity, JSON_PATH_MODEL_ID); - if (!readResult.isEmpty()) { - modelId = readResult.get(0); - } - return modelId; - } - - /** - * Gets the resource version of the instance. - * - * @param json - * a Named Query JSON payload - * @return the resource version of the object instance - */ - public String getResourceVersion(String json) { - String resourceVersion = null; - - InstanceEntity entity = getNamedQueryEntity(json); - - if (entity != null && entity.getObject() != null && entity.getObject().getAsJsonObject().has(RESOURCE_VERSION)) { - resourceVersion = entity.getObject().getAsJsonObject().get(RESOURCE_VERSION).getAsString(); - } - return resourceVersion; - } - - /** - * Gets the model name of the instance. - * - * @param jsonString - * a Named Query JSON payload - * @return the model name of the object instance - * @throws ValidationServiceException - */ - public String getModelName(String jsonString) { - JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject(); - return getModelName(jsonObject); - } - - /** - * @param jsonObject - * @return - */ - private String getModelName(JsonObject jsonObject) { - for (Entry<String, JsonElement> entry : jsonObject.entrySet()) { - if (MODEL_NAME.equals(entry.getKey())) { - return entry.getValue().getAsString(); - } - } - return null; - } - - private void processRelatedObjects(Multimap<String, String> values, JsonArray jsonArray) { - for (JsonElement relatedObject : jsonArray) { - JsonObject jsonObject = relatedObject.getAsJsonObject(); - - InstanceEntity entity = getNamedQueryEntity(jsonObject); - if (entity != null) { - values.put(entity.getModelName() == null ? entity.getEntityType() : entity.getModelName(), jsonObject.toString()); - } - } - } - - private InstanceEntity getNamedQueryEntity(JsonObject jsonObject) { - Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet(); - - String modelName = getModelName(jsonObject); - - for (Entry<String, JsonElement> entry : entrySet) { - if (!Arrays.asList(INVALID_ENTRIES).contains(entry.getKey())) { - return new InstanceEntity(entry.getKey(), modelName, entry.getValue().getAsJsonObject(), jsonObject); - } - } - - return null; - } - - /** - * An Entity bean for the InstanceReader - * - */ - public class InstanceEntity { - - private String entityType; - private String modelName; - private JsonObject object; - private JsonObject objectAndGraph; - - /** - * @param entityType - * @param modelName - * @param object - * @param objectAndGraph - */ - public InstanceEntity(String entityType, String modelName, JsonObject object, JsonObject objectAndGraph) { - this.entityType = entityType; - this.modelName = modelName; - this.object = object; - this.objectAndGraph = objectAndGraph; - } - - public String getEntityType() { - return entityType; - } - - public String getModelName() { - return modelName; - } - - public JsonObject getObject() { - return object; - } - - public JsonObject getObjectAndGraph() { - return objectAndGraph; - } - - @Override - public String toString() { - return "Entity [entityType=" + entityType + ", modelName=" + modelName + ", object=" + object.toString() + ", fullObject=" - + objectAndGraph.toString() + "]"; - } - } -}
\ No newline at end of file + private static final String MODEL_NAME = "model-name"; + private static final String[] INVALID_ENTRIES = { "inventory-response-items", "extra-properties", MODEL_NAME }; + private static final String RESOURCE_VERSION = "resource-version"; + private static final String JSON_PATH_MODEL_ID = "$.*.persona-model-id"; + + private JsonReader jsonReader; + private OxmReader oxmReader; + private JsonParser jsonParser = new JsonParser(); + + /** + * @param jsonReader + * @param oxmReader + */ + @Inject + public InstanceReader(JsonReader jsonReader, OxmReader oxmReader) { + this.jsonReader = jsonReader; + this.oxmReader = oxmReader; + } + + public OxmReader getOxmReader() { + return oxmReader; + } + + /** + * Gets object instance values. + * + * @param json + * a Named Query JSON payload + * @param mapping + * defines the paths that allow the extraction of values from the object instance. This includes: + * <ul> + * <li>origin: path that serves as the starting point for the instance search</li> + * <li>root: path to underlying instance objects that can be examined by recursively calling the getValues + * method</li> + * </ul> + * + * @return a {@link Multimap} of instances keyed by their model id. + * @throws ValidationServiceException + */ + public Multimap<String, String> getValues(String json, ModelInstanceMapper mapping) + throws ValidationServiceException { + Multimap<String, String> values = HashMultimap.create(); + + DocumentContext document = jsonReader.parse(json); + + if (MappingType.RELATIONSHIP.equals(mapping.getMappingType())) { + String rootPath = mapping.getInstance().getRoot(); + if (rootPath == null || rootPath.isEmpty()) { + throw new ValidationServiceException(ValidationServiceError.INSTANCE_MAPPING_ROOT_ERROR); + } + + JsonElement jsonElement = jsonReader.getJsonElement(document, rootPath); + + if (jsonElement instanceof JsonArray) { + JsonArray jsonArray = jsonElement.getAsJsonArray(); + + processRelatedObjects(values, jsonArray); + } + } else { + // We are dealing with attributes. + String valuePath = mapping.getInstance().getValue(); + if (valuePath != null && !valuePath.isEmpty()) { + List<String> attributes = jsonReader.get(json, valuePath); + for (String attribute : attributes) { + values.put(attribute, null); // NOSONAR + } + } + } + + return values; + } + + /** + * Gets the instance type, e.g. connector, pserver, etc. + * + * @param json + * a Named Query JSON payload + * @return the type of the entity + */ + public String getInstanceType(String json) { + return getNamedQueryEntity(json).getEntityType(); + } + + /** + * Gets the id of the instance. Uses the {@link OxmReader} to identify the property holding the primary key.<br> + * + * WARNING: Some types of object appear to have more than one primary key. This method uses the first primary key. + * + * @param json + * a Named Query JSON payload + * @return the identifier of the object instance + * @throws ValidationServiceException + */ + public String getInstanceId(String json) throws ValidationServiceException { + String instanceId = null; + + InstanceEntity entity = getNamedQueryEntity(json); + + List<String> primaryKeys = oxmReader.getPrimaryKeys(entity.getEntityType()); + + if (primaryKeys != null && !primaryKeys.isEmpty()) { + JsonObject instance = entity.getObject().getAsJsonObject(); + JsonElement primaryKey = instance.get(primaryKeys.get(0)); + instanceId = primaryKey == null ? null : primaryKey.getAsString(); + } + + return instanceId; + } + + /** + * Strips the instance out of its payload wrapping. + * + * @param json + * a Named Query JSON payload + * @param mappings + * the definition of the paths that allow the extraction of the instance from the JSON payload + * @return + * @throws ValidationServiceException + */ + public String getInstance(String json, List<ModelInstanceMapper> mappings) throws ValidationServiceException { + String origin = mappings.iterator().next().getInstance().getOrigin(); + List<String> jsonList = jsonReader.get(json, origin); + + if (!jsonList.isEmpty()) { + return jsonList.get(0); + } else { + throw new ValidationServiceException(ValidationServiceError.INSTANCE_READER_NO_INSTANCE, origin, json); + } + } + + /** + * Extracts the entity from a Named Query JSON payload. + * + * @param json + * a Named Query JSON payload + * @return an {@link InstanceEntity} object + */ + public InstanceEntity getNamedQueryEntity(String json) { + return getNamedQueryEntity(jsonParser.parse(json).getAsJsonObject()); + } + + /** + * Gets the model identifier of a given entity. + * + * @param entity + * a JSON entity + * @return a model identifier attribute value if the attribute exists else a null is returned. + * @throws ValidationServiceException + */ + public String getModelId(String entity) throws ValidationServiceException { + String modelId = null; + List<String> readResult = jsonReader.get(entity, JSON_PATH_MODEL_ID); + if (!readResult.isEmpty()) { + modelId = readResult.get(0); + } + return modelId; + } + + /** + * Gets the resource version of the instance. + * + * @param json + * a Named Query JSON payload + * @return the resource version of the object instance + */ + public String getResourceVersion(String json) { + String resourceVersion = null; + + InstanceEntity entity = getNamedQueryEntity(json); + + if (entity != null && entity.getObject() != null + && entity.getObject().getAsJsonObject().has(RESOURCE_VERSION)) { + resourceVersion = entity.getObject().getAsJsonObject().get(RESOURCE_VERSION).getAsString(); + } + return resourceVersion; + } + + /** + * Gets the model name of the instance. + * + * @param jsonString + * a Named Query JSON payload + * @return the model name of the object instance + * @throws ValidationServiceException + */ + public String getModelName(String jsonString) { + JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject(); + return getModelName(jsonObject); + } + + /** + * @param jsonObject + * @return + */ + private String getModelName(JsonObject jsonObject) { + for (Entry<String, JsonElement> entry : jsonObject.entrySet()) { + if (MODEL_NAME.equals(entry.getKey())) { + return entry.getValue().getAsString(); + } + } + return null; + } + + private void processRelatedObjects(Multimap<String, String> values, JsonArray jsonArray) { + for (JsonElement relatedObject : jsonArray) { + JsonObject jsonObject = relatedObject.getAsJsonObject(); + + InstanceEntity entity = getNamedQueryEntity(jsonObject); + if (entity != null) { + values.put(entity.getModelName() == null ? entity.getEntityType() : entity.getModelName(), + jsonObject.toString()); + } + } + } + + private InstanceEntity getNamedQueryEntity(JsonObject jsonObject) { + Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet(); + + String modelName = getModelName(jsonObject); + + for (Entry<String, JsonElement> entry : entrySet) { + if (!Arrays.asList(INVALID_ENTRIES).contains(entry.getKey())) { + return new InstanceEntity(entry.getKey(), modelName, entry.getValue().getAsJsonObject(), jsonObject); + } + } + + return null; + } + + /** + * An Entity bean for the InstanceReader + * + */ + public class InstanceEntity { + + private String entityType; + private String modelName; + private JsonObject object; + private JsonObject objectAndGraph; + + /** + * @param entityType + * @param modelName + * @param object + * @param objectAndGraph + */ + public InstanceEntity(String entityType, String modelName, JsonObject object, JsonObject objectAndGraph) { + this.entityType = entityType; + this.modelName = modelName; + this.object = object; + this.objectAndGraph = objectAndGraph; + } + + public String getEntityType() { + return entityType; + } + + public String getModelName() { + return modelName; + } + + public JsonObject getObject() { + return object; + } + + public JsonObject getObjectAndGraph() { + return objectAndGraph; + } + + @Override + public String toString() { + return "Entity [entityType=" + entityType + ", modelName=" + modelName + ", object=" + object.toString() + + ", fullObject=" + objectAndGraph.toString() + "]"; + } + } +} diff --git a/src/main/java/org/onap/aai/validation/modeldriven/validator/ModelReader.java b/src/main/java/org/onap/aai/validation/modeldriven/validator/ModelReader.java index 04728a3..75dcefa 100644 --- a/src/main/java/org/onap/aai/validation/modeldriven/validator/ModelReader.java +++ b/src/main/java/org/onap/aai/validation/modeldriven/validator/ModelReader.java @@ -1,4 +1,4 @@ -/* +/** * ============LICENSE_START=================================================== * Copyright (c) 2018 Amdocs * ============================================================================ @@ -6,7 +6,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,200 +37,195 @@ import org.onap.aai.validation.modeldriven.parser.XMLModelParser; */ public class ModelReader { - private static final String ATTRIBUTE_MODELTYPE = "model-type"; - - /** - * Do not instantiate an object of this class - */ - private ModelReader() { - // Deliberately empty - } - - /** - * Gets the values of a model element as defined by the model-instance mapping configuration. When the mapping - * type is "attribute", the multimap will be returned with a null value. - * - * @param modelElement - * the model element from which the values will be extracted - * @param mapping - * the model-instance mapping object defining the path to the model values - * @param modelCacheManager - * the model cache manager used to retrieve further models - * @return a {@link Multimap} of model values. - * @throws ValidationServiceException - */ - public static Multimap<String, Node> getValues(Node modelElement, ModelInstanceMapper mapping, ModelCacheManager modelCacheManager) - throws ValidationServiceException { - Multimap<String, Node> values = HashMultimap.create(); - - if (MappingType.ATTRIBUTE.equals(mapping.getMappingType())) { - // Get attributes on current model element. - Multimap<String, Node> modelValues = getModelValues(modelElement, mapping, false); - if (modelValues.isEmpty()) { - throw new ValidationServiceException(ValidationServiceError.MODEL_VALUE_ERROR, - mapping.getModel().getValue(), modelElement.asXML()); - } - values.putAll(modelValues); - } else { - // Get related objects. - getValuesAndModels(modelElement, mapping, modelCacheManager, values); - } - - - return values; - } - - /** - * Returns the model type property of the current model element. - * - * @param model - * The current model element. - * @return the model type of the current element or null if not found. - */ - public static String getModelType(Node model) { - String modelType = null; - List<Node> modelTypeElements = XMLModelParser.getObjectsFromXPath(model, ATTRIBUTE_MODELTYPE); - if (!modelTypeElements.isEmpty()) { - modelType = modelTypeElements.iterator().next().getText(); - } - return modelType; - } - - /** - * @param model - * @param mapping - * @return True if supplied model is of type widget. - */ - public static boolean isValidModelType(Node model, ModelInstanceMapper mapping) { - Collection<String> validTypes = mapping.getModel().getFilter().getValid(); - return validTypes.isEmpty() ? false :validTypes.contains(getModelType(model)); - } - - /** - * Populates a Multimap of models. If a root and filter are defined in the mapping it will navigate the model to find a - * valid models according to the filter. If the root property is not defined a model is not returned. - * - * @param model - * the model to be inspected - * @param mapping - * the model-instance mapping object defining the root model - * @param modelCacheManager - * the model cache manager used to retrieve further models - * @param models - * a Multimap of models that will be populated with further models - * @throws ValidationServiceException - */ - public static void getValuesAndModels(Node model, ModelInstanceMapper mapping, ModelCacheManager modelCacheManager, Multimap<String, Node> models) throws ValidationServiceException { - String root = mapping.getModel().getRoot(); - - if (root == null) { - return; - } - - List<Node> childModelElements = XMLModelParser.getObjectsFromXPath(model, root); - for (Node childModel : childModelElements) { - // If the child element is a leaf, this could either mean the end of the hierarchy, or that we have - // encountered a resource and need to retrieve a separate model to continue the model traversal. - List<String> modelNames = getModelValuesList(childModel, mapping); - if (!hasChildren(childModel, root) && !isValidModel(childModel, mapping) && mapping.getModel().getId() != null) { - childModel = getChildModelNode(modelCacheManager, childModel, mapping); - } - - if (isValidModel(childModel, mapping)) { - for (String modelName : modelNames) { - models.put(modelName, childModel); - } - } else { - getValuesAndModels(childModel, mapping, modelCacheManager, models); - } - } - } - - /** - * Find the next child model given a specific node. - * - * @param modelCacheManager - * the model cache manager used to retrieve further models - * @param node - * the top-level node under which child model nodes are searched - * @param rootXPath - * the path expression to apply to the node to find child elements - * @param modelIdPath - * the path expression to apply to the node to find the child model IDs - * @return either or the {@code node} if there were no matches for {@code id} - * @throws ValidationServiceException - */ - private static Node getChildModelNode(ModelCacheManager modelCacheManager, Node node, ModelInstanceMapper mapping) throws ValidationServiceException { - Node childModel = node; - - // Get the model for the specified node to check its type. - // Only one model ID is expected, although the API returns a list. - List<Node> childModelIds = XMLModelParser.getObjectsFromXPath(node, mapping.getModel().getId()); - - if (!childModelIds.isEmpty()) { - // Found the child model ID, so retrieve the child model from cache. - ModelId modelId = new ModelId(ModelId.ATTR_MODEL_NAME_VERSION_ID, childModelIds.iterator().next().getText()); - Node fullChildModel = modelCacheManager.get(modelId); - - if (fullChildModel != null && !isValidModelType(fullChildModel, mapping)) { - // Child model is not a widget so replace current child model with the full child model - // retrieved from the cache. - List<Node> fullChildModelElements = XMLModelParser.getObjectsFromXPath(fullChildModel, mapping.getModel().getRoot()); - // Only one crown widget is expected, although the API returns a list. - childModel = fullChildModelElements.isEmpty() ? node : fullChildModelElements.iterator().next(); - } - } - - return childModel; - } - - private static Multimap<String, Node> getModelValues(Node model, ModelInstanceMapper mapping, boolean addModel) { - Multimap<String, Node> values = HashMultimap.create(); - List<String> valueStrings = getModelValuesList(model, mapping); - for (String value : valueStrings) { - values.put(value, addModel ? model : null); - } - return values; - } - - private static List<String> getModelValuesList(Node model, ModelInstanceMapper mapping) { - List<String> values = new ArrayList<>(); - List<Node> valueElements = XMLModelParser.getObjectsFromXPath(model, mapping.getModel().getValue()); - for (Node node : valueElements) { - values.add(node.getText()); - } - return values; - } - - private static boolean isValidModel(Node node, ModelInstanceMapper mapping) { - Filter filter = mapping.getModel().getFilter(); - if (filter == null) { - return true; - } - - List<String> valid = filter.getValid(); - // If there are no valid values, return false. - if (valid.isEmpty()) { - return false; - } - - String filterXPath = filter.getPath(); - if (filterXPath == null) { - return false; - } - - List<Node> filterNodes = XMLModelParser.getObjectsFromXPath(node, filterXPath); - for (Node filterNode : filterNodes) { - String text = filterNode.getText(); - if (valid.contains(text)) { - return true; - } - } - - return false; - } - - private static boolean hasChildren(Node parent, String rootXPath) { - return !XMLModelParser.getObjectsFromXPath(parent, rootXPath).isEmpty(); - } -}
\ No newline at end of file + private static final String ATTRIBUTE_MODELTYPE = "model-type"; + + /** + * Do not instantiate an object of this class + */ + private ModelReader() { + // Deliberately empty + } + + /** + * Gets the values of a model element as defined by the model-instance mapping configuration. When the mapping type + * is "attribute", the multimap will be returned with a null value. + * + * @param modelElement + * the model element from which the values will be extracted + * @param mapping + * the model-instance mapping object defining the path to the model values + * @param modelCacheManager + * the model cache manager used to retrieve further models + * @return a {@link Multimap} of model values. + * @throws ValidationServiceException + */ + public static Multimap<String, Node> getValues(Node modelElement, ModelInstanceMapper mapping, + ModelCacheManager modelCacheManager) throws ValidationServiceException { + Multimap<String, Node> values = HashMultimap.create(); + + if (MappingType.ATTRIBUTE.equals(mapping.getMappingType())) { + // Get attributes on current model element. + Multimap<String, Node> modelValues = getModelValues(modelElement, mapping, false); + if (modelValues.isEmpty()) { + throw new ValidationServiceException(ValidationServiceError.MODEL_VALUE_ERROR, + mapping.getModel().getValue(), modelElement.asXML()); + } + values.putAll(modelValues); + } else { + // Get related objects. + getValuesAndModels(modelElement, mapping, modelCacheManager, values); + } + + + return values; + } + + /** + * Returns the model type property of the current model element. + * + * @param model + * The current model element. + * @return the model type of the current element or null if not found. + */ + public static String getModelType(Node model) { + String modelType = null; + List<Node> modelTypeElements = XMLModelParser.getObjectsFromXPath(model, ATTRIBUTE_MODELTYPE); + if (!modelTypeElements.isEmpty()) { + modelType = modelTypeElements.iterator().next().getText(); + } + return modelType; + } + + /** + * @param model + * @param mapping + * @return True if supplied model is of type widget. + */ + public static boolean isValidModelType(Node model, ModelInstanceMapper mapping) { + Collection<String> validTypes = mapping.getModel().getFilter().getValid(); + return !validTypes.isEmpty() && validTypes.contains(getModelType(model)); + } + + /** + * Populates a Multimap of models. If a root and filter are defined in the mapping it will navigate the model to + * find a valid models according to the filter. If the root property is not defined a model is not returned. + * + * @param model + * the model to be inspected + * @param mapping + * the model-instance mapping object defining the root model + * @param modelCacheManager + * the model cache manager used to retrieve further models + * @param models + * a Multimap of models that will be populated with further models + * @throws ValidationServiceException + */ + public static void getValuesAndModels(Node model, ModelInstanceMapper mapping, ModelCacheManager modelCacheManager, + Multimap<String, Node> models) throws ValidationServiceException { + String root = mapping.getModel().getRoot(); + + if (root == null) { + return; + } + + List<Node> childModelElements = XMLModelParser.getObjectsFromXPath(model, root); + for (Node childModel : childModelElements) { + // If the child element is a leaf, this could either mean the end of the hierarchy, or that we have + // encountered a resource and need to retrieve a separate model to continue the model traversal. + List<String> modelNames = getModelValuesList(childModel, mapping); + if (!hasChildren(childModel, root) && !isValidModel(childModel, mapping.getModel().getFilter()) + && mapping.getModel().getId() != null) { + childModel = getChildModelNode(modelCacheManager, childModel, mapping); + } + + if (isValidModel(childModel, mapping.getModel().getFilter())) { + for (String modelName : modelNames) { + models.put(modelName, childModel); + } + } else { + getValuesAndModels(childModel, mapping, modelCacheManager, models); + } + } + } + + /** + * Find the next child model given a specific node. + * + * @param modelCacheManager + * the model cache manager used to retrieve further models + * @param node + * the top-level node under which child model nodes are searched + * @param rootXPath + * the path expression to apply to the node to find child elements + * @param modelIdPath + * the path expression to apply to the node to find the child model IDs + * @return either or the {@code node} if there were no matches for {@code id} + * @throws ValidationServiceException + */ + private static Node getChildModelNode(ModelCacheManager modelCacheManager, Node node, ModelInstanceMapper mapping) + throws ValidationServiceException { + Node childModel = node; + + // Get the model for the specified node to check its type. + // Only one model ID is expected, although the API returns a list. + List<Node> childModelIds = XMLModelParser.getObjectsFromXPath(node, mapping.getModel().getId()); + + if (!childModelIds.isEmpty()) { + // Found the child model ID, so retrieve the child model from cache. + ModelId modelId = + new ModelId(ModelId.ATTR_MODEL_NAME_VERSION_ID, childModelIds.iterator().next().getText()); + Node fullChildModel = modelCacheManager.get(modelId); + + if (fullChildModel != null && !isValidModelType(fullChildModel, mapping)) { + // Child model is not a widget so replace current child model with the full child model + // retrieved from the cache. + List<Node> fullChildModelElements = + XMLModelParser.getObjectsFromXPath(fullChildModel, mapping.getModel().getRoot()); + // Only one crown widget is expected, although the API returns a list. + childModel = fullChildModelElements.isEmpty() ? node : fullChildModelElements.iterator().next(); + } + } + + return childModel; + } + + private static Multimap<String, Node> getModelValues(Node model, ModelInstanceMapper mapping, boolean addModel) { + Multimap<String, Node> values = HashMultimap.create(); + List<String> valueStrings = getModelValuesList(model, mapping); + for (String value : valueStrings) { + values.put(value, addModel ? model : null); // NOSONAR + } + return values; + } + + private static List<String> getModelValuesList(Node model, ModelInstanceMapper mapping) { + List<String> values = new ArrayList<>(); + List<Node> valueElements = XMLModelParser.getObjectsFromXPath(model, mapping.getModel().getValue()); + for (Node node : valueElements) { + values.add(node.getText()); + } + return values; + } + + private static boolean isValidModel(Node node, Filter filter) { + if (filter == null) { + return true; + } + + final List<String> validValues = filter.getValid(); + + if (!validValues.isEmpty() && filter.getPath() != null) { + for (Node filterNode : XMLModelParser.getObjectsFromXPath(node, filter.getPath())) { + if (validValues.contains(filterNode.getText())) { + return true; + } + } + } + + return false; + } + + private static boolean hasChildren(Node parent, String rootXPath) { + return !XMLModelParser.getObjectsFromXPath(parent, rootXPath).isEmpty(); + } +} diff --git a/src/main/java/org/onap/aai/validation/ruledriven/RuleDrivenValidator.java b/src/main/java/org/onap/aai/validation/ruledriven/RuleDrivenValidator.java index 2bc2d90..49b251e 100644 --- a/src/main/java/org/onap/aai/validation/ruledriven/RuleDrivenValidator.java +++ b/src/main/java/org/onap/aai/validation/ruledriven/RuleDrivenValidator.java @@ -73,12 +73,15 @@ public class RuleDrivenValidator implements Validator { /** * Construct a Validator that is configured using rule files * - * @param configurationPath path to the Groovy rules files - * @param oxmReader required for validating entity types - * @param eventReader a reader for extracting entities from each event to be validated + * @param configurationPath + * path to the Groovy rules files + * @param oxmReader + * required for validating entity types + * @param eventReader + * a reader for extracting entities from each event to be validated */ - public RuleDrivenValidator(final Path configurationPath, final OxmReader oxmReader, - final EventReader eventReader, final RuleIndexingConfig ruleIndexingConfig) { + public RuleDrivenValidator(final Path configurationPath, final OxmReader oxmReader, final EventReader eventReader, + final RuleIndexingConfig ruleIndexingConfig) { this.configurationPath = configurationPath; this.oxmReader = oxmReader; this.eventReader = eventReader; @@ -116,7 +119,7 @@ public class RuleDrivenValidator implements Validator { private void validateRulesConfiguration() throws ValidationServiceException { for (RuleManager ruleManager : ruleManagers.values()) { for (EntitySection entity : ruleManager.getEntities()) { - if(ruleIndexingConfig.isPresent() && ruleIndexingConfig.get().skipOxmValidation(entity.getName())) { + if (ruleIndexingConfig.isPresent() && ruleIndexingConfig.get().skipOxmValidation(entity.getName())) { continue; } if (oxmReader != null && oxmReader.getPrimaryKeys(entity.getName()).isEmpty()) { @@ -141,7 +144,6 @@ public class RuleDrivenValidator implements Validator { /* * (non-Javadoc) - * * @see org.onap.aai.validation.Validator#validate(java.lang.String) */ @Override @@ -173,7 +175,8 @@ public class RuleDrivenValidator implements Validator { result.getSuccess() ? "pass" : "fail")); if (!result.getSuccess()) { - String errorMessage = MessageFormat.format(rule.getErrorMessage(), result.getErrorArguments().toArray()); + String errorMessage = + MessageFormat.format(rule.getErrorMessage(), result.getErrorArguments().toArray()); //@formatter:off Violation violation = builder @@ -200,8 +203,8 @@ public class RuleDrivenValidator implements Validator { if (eventType.isPresent()) { Optional<RuleManager> ruleManager = getRuleManager(eventType.get().toLowerCase(Locale.getDefault())); if (ruleManager.isPresent()) { - if (ruleIndexingConfig.isPresent() && ruleIndexingConfig.get().getIndexedEvents() != null && - ruleIndexingConfig.get().getIndexedEvents().contains(eventType.get())) { + if (ruleIndexingConfig.isPresent() && ruleIndexingConfig.get().getIndexedEvents() != null + && ruleIndexingConfig.get().getIndexedEvents().contains(eventType.get())) { rules = getRulesByIndex(entity, eventType.get(), ruleManager.get()); } else { rules = Optional.of(ruleManager.get().getRulesForEntity(entity.getType())); @@ -216,32 +219,35 @@ public class RuleDrivenValidator implements Validator { applicationLogger.debug(String.format("Retrieving indexed rules for key '%s'", rulesKey)); Optional<List<Rule>> rules = Optional.of(ruleManager.getRulesForEntity(rulesKey)); if (rules.get().isEmpty() && ruleIndexingConfig.isPresent()) { - if (ruleIndexingConfig.get().getDefaultIndexKey() == null || ruleIndexingConfig.get().getDefaultIndexKey().isEmpty()) { + if (ruleIndexingConfig.get().getDefaultIndexKey() == null + || ruleIndexingConfig.get().getDefaultIndexKey().isEmpty()) { applicationLogger.debug("Default index value not configured, unable to get rules"); applicationLogger.error(ApplicationMsgs.CANNOT_VALIDATE_ERROR, eventType); return rules; } - String defaultKey = RuleManager.generateKey(new String[] {ruleIndexingConfig.get().getDefaultIndexKey()}); + String defaultKey = RuleManager.generateKey(new String[] { ruleIndexingConfig.get().getDefaultIndexKey() }); rules = Optional.of(ruleManager.getRulesForEntity(defaultKey)); } return rules; } private String generateKey(Entity entity, String eventType) { - if (!ruleIndexingConfig.isPresent() || ruleIndexingConfig.get().getIndexAttributes() == null || - ruleIndexingConfig.get().getIndexAttributes().isEmpty()) { + if (!ruleIndexingConfig.isPresent() || ruleIndexingConfig.get().getIndexAttributes() == null + || ruleIndexingConfig.get().getIndexAttributes().isEmpty()) { applicationLogger.debug(String.format( - "Event '%s' is configured to use indexed rules but indexing attributes are not configured", eventType)); + "Event '%s' is configured to use indexed rules but indexing attributes are not configured", + eventType)); return ""; } try { AttributeValues attributeValues = entity.getAttributeValues(ruleIndexingConfig.get().getIndexAttributes()); - applicationLogger.debug("Generating index using attributes: " + attributeValues.generateReport().toString()); + applicationLogger + .debug("Generating index using attributes: " + attributeValues.generateReport().toString()); Collection<Object> values = attributeValues.generateReport().values(); return RuleManager.generateKey(values.stream().toArray(String[]::new)); } catch (ValidationServiceException e) { - applicationLogger.debug("Failed to retrieve index key attributes from event"); - applicationLogger.error(ApplicationMsgs.CANNOT_VALIDATE_ERROR, eventType); + applicationLogger.debug("Failed to retrieve index key attributes from event: " + e.getMessage()); + applicationLogger.error(ApplicationMsgs.CANNOT_VALIDATE_ERROR, e, eventType); return ""; } } @@ -260,7 +266,8 @@ public class RuleDrivenValidator implements Validator { /** * Read the text content of the specified Path and append this to the specified String * - * @param sb StringBuilder for the rule configuration text + * @param sb + * StringBuilder for the rule configuration text * @return a Consumer function that appends file content */ private Consumer<? super Path> appendFileContent(StringBuilder sb) { |