package org.onap.aai.aaf.auth;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
-import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
-import java.util.*;
import java.util.stream.Collectors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The Class CertUtil provides cert related utility methods.
*/
public class CertUtil {
- public static final String DEFAULT_CADI_ISSUERS =
- "CN=ATT AAF CADI Test Issuing CA 01, OU=CSO, O=ATT, C=US:CN=ATT AAF CADI Test Issuing CA 02, OU=CSO, O=ATT, C=US";
+ public static final String DEFAULT_CADI_ISSUERS = "CN=ATT AAF CADI Test Issuing " +
+ "CA 01, OU=CSO, O=ATT, C=US:CN=ATT AAF CADI Test Issuing CA 02, OU=CSO, O=ATT, C=US";
public static final String CADI_PROP_FILES = "cadi_prop_files";
public static final String CADI_ISSUERS_PROP_NAME = "cadi_x509_issuers";
public static final String CADI_ISSUERS_SEPARATOR = ":";
public static List<String> getCadiCertIssuers(Properties cadiProperties) {
- List<String> defaultList = new ArrayList<String>();
+ List<String> defaultList = new ArrayList<>();
List<String> resultList = new ArrayList<String>();
- String[] cIssuers = DEFAULT_CADI_ISSUERS.split(CADI_ISSUERS_SEPARATOR);
- for (String issuer : cIssuers) {
+ String[] cadiIssuers = DEFAULT_CADI_ISSUERS.split(CADI_ISSUERS_SEPARATOR);
+ for (String issuer : cadiIssuers) {
defaultList.add(issuer.replaceAll("\\s+", "").toUpperCase());
}
try {
String configuredIssuers = DEFAULT_CADI_ISSUERS;
Properties certProperties = new Properties();
if (certPropFileName != null) {
- certProperties.load(new FileInputStream(new File(certPropFileName)));
+ try (FileInputStream fis = new FileInputStream(certPropFileName)) {
+ certProperties.load(fis);
+ }
configuredIssuers = certProperties.getProperty(CADI_ISSUERS_PROP_NAME);
}
if ((configuredIssuers != null) && (!configuredIssuers.isEmpty())) {
- cIssuers = configuredIssuers.split(CADI_ISSUERS_SEPARATOR);
- for (String issuer : cIssuers) {
+ cadiIssuers = configuredIssuers.split(CADI_ISSUERS_SEPARATOR);
+ for (String issuer : cadiIssuers) {
resultList.add(issuer.replaceAll("\\s+", "").toUpperCase());
}
}
if (jmsTemplate != null) {
jmsTemplate.convertAndSend(finalJson.toString());
CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory();
- ccf.destroy();
+ if (ccf != null) {
+ ccf.destroy();
+ }
}
}
if (jmsTemplate != null) {
jmsTemplate.convertAndSend(msg);
CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory();
- ccf.destroy();
+ if (ccf != null) {
+ ccf.destroy();
+ }
}
}
}
package org.onap.aai.introspection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.base.CaseFormat;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.commons.lang.ClassUtils;
import org.eclipse.persistence.exceptions.DynamicException;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.workarounds.NamingExceptions;
-
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.*;
-import java.util.stream.Collectors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class Introspector implements Cloneable {
if (obj != null) {
try {
- if (!obj.getClass().getName().equals(nameClass.getName())) {
+ if (! (obj.getClass().getCanonicalName().equals(nameClass.getCanonicalName()))) {
if (nameClass.isPrimitive()) {
nameClass = ClassUtils.primitiveToWrapper(nameClass);
result = nameClass.getConstructor(String.class).newInstance(obj.toString());
import java.util.Map;
import java.util.Set;
import java.util.UUID;
-
+import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.schema.enums.PropertyMetadata;
@Override
public Class<?> getGenericTypeClass(String name) {
- Object resultObject = null;
Class<?> resultClass = null;
- resultObject = this.getValue(name);
- if (resultObject.getClass().getName().equals("org.json.simple.JSONArray")) {
+ Object resultObject = this.getValue(name);
+ if (resultObject instanceof JSONArray) {
resultClass = ((List) resultObject).get(0).getClass();
}
@Override
public boolean isComplexType(String name) {
String result = this.getType(name);
-
- if (result.contains("JSONObject")) {
- return true;
- } else {
- return false;
- }
-
+ return result.contains("JSONObject");
}
@Override
public boolean isComplexGenericType(String name) {
String result = this.getGenericType(name);
-
- if (result.contains("JSONObject")) {
- return true;
- } else {
- return false;
- }
-
+ return result.contains("JSONObject");
}
@Override
public boolean isListType(String name) {
String result = this.getType(name);
-
- if (result.contains("java.util.List")) {
- return true;
- } else {
- return false;
- }
-
+ return result.contains("java.util.List");
}
@Override
public boolean isContainer() {
Set<String> props = this.getProperties();
- boolean result = false;
- if (props.size() == 1 && this.isListType(props.iterator().next())) {
- result = true;
- }
-
- return result;
+ return props.size() == 1 && this.isListType(props.iterator().next());
}
@Override
return null;
}
- @Override
- public Object clone() {
- // TODO
- return null;
- }
-
/*
* @Override
* public String findEdgeName(String parent, String child) {
- *
+ *
* // Always has for now
* return "has";
- *
+ *
* }
*/
import java.util.Map;
import java.util.Set;
-
import org.onap.aai.schema.enums.PropertyMetadata;
public final class PropertyPredicates {
return !(Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)))
|| Visibility.deployment.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))));
}
- if (map.containsKey("dataLocation")) {
- return false;
- }
return true;
};
}
if (map.containsKey(PropertyMetadata.VISIBILITY)) {
return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)));
}
- if (map.containsKey("dataLocation")) {
- return false;
- }
return true;
};
}
package org.onap.aai.introspection.sideeffect;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
-import java.util.*;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.onap.aai.config.SpringContextAware;
-import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.LoaderUtil;
import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException;
import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import org.onap.aai.setup.SchemaVersions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class SideEffect {
try {
this.processURI(completeUri, entry);
} catch (EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
- logger.warn("Unable to execute the side effect {} due to ", e, this.getClass().getName());
+ logger.warn("Unable to execute the side effect {} due to ", this.getClass().getName(), e);
}
}
}
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
+import java.net.ConnectException;
+import java.net.SocketTimeoutException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
import org.apache.http.conn.ConnectTimeoutException;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
-import javax.annotation.PostConstruct;
-import java.net.ConnectException;
-import java.net.SocketTimeoutException;
-import java.util.*;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
/**
* <b>ValidationService</b> routes all the writes to the database
* excluding deletes for now to the validation service to verify
body
);
+ Object responseBody = responseEntity.getBody();
if(isSuccess(responseEntity)){
LOGGER.debug("Validation Service returned following response status code {} and body {}", responseEntity.getStatusCodeValue(), responseEntity.getBody());
- } else {
+ } else if (responseBody != null) {
Validation validation = null;
try {
- validation = gson.fromJson(responseEntity.getBody().toString(), Validation.class);
+ validation = gson.fromJson(responseBody.toString(), Validation.class);
} catch(JsonSyntaxException jsonException){
LOGGER.warn("Unable to convert the response body {}", jsonException.getMessage());
}
} else {
violations.addAll(extractViolations(validation));
}
+ } else {
+ LOGGER.warn("Unable to convert the response body null");
}
} catch(Exception e){
// If the exception cause is client side timeout
package org.onap.aai.query.builder;
-import org.apache.tinkerpop.gremlin.process.traversal.P;
-import org.apache.tinkerpop.gremlin.process.traversal.Step;
-import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
+import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
-import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
-import org.onap.aai.schema.enums.ObjectMetadata;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
public class HistoryTraversalURIOptimizedQuery<E> extends TraversalURIOptimizedQuery {
- protected Map<Integer, String> stepToAaiUri = new HashMap<>();
-
public HistoryTraversalURIOptimizedQuery(Loader loader, GraphTraversalSource source) {
super(loader, source);
}
touchHistoryProperties(key);
}
- private void touchHistoryProperties(String key){
- if(key != null && !key.isEmpty() && !key.equals(AAIProperties.NODE_TYPE)) {
+ private void touchHistoryProperties(String key) {
+ if (key != null && !key.isEmpty() && !key.equals(AAIProperties.NODE_TYPE)) {
traversal.where(__.properties(key));
}
}
- private void touchHistoryProperties(String key, Object value){
- if(key != null && !key.isEmpty() && !key.equals(AAIProperties.NODE_TYPE)) {
+ private void touchHistoryProperties(String key, Object value) {
+ if (key != null && !key.isEmpty() && !key.equals(AAIProperties.NODE_TYPE)) {
traversal.where(__.properties(key).hasValue(value));
}
}
getDbEngine().startTransaction();
this.notification = new UEBNotification(loader, loaderFactory, schemaVersions);
- if("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))){
+ if ("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))) {
this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
} else {
this.notificationDepth = AAIProperties.MINIMUM_DEPTH;
getDbEngine().startTransaction();
this.notification = new UEBNotification(loader, loaderFactory, schemaVersions);
- if("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))){
+ if ("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))) {
this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
} else {
this.notificationDepth = AAIProperties.MINIMUM_DEPTH;
this.notification = notification;
- if("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))){
+ if ("true".equals(AAIConfig.get("aai.notification.depth.all.enabled", "true"))) {
this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
} else {
this.notificationDepth = AAIProperties.MINIMUM_DEPTH;
if (obj != null) {
status = Status.OK;
MarshallerProperties properties;
- if (!request.getMarshallerProperties().isPresent()) {
- properties = new MarshallerProperties.Builder(
- org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
+ Optional<MarshallerProperties> marshallerPropOpt = request.getMarshallerProperties();
+ if (marshallerPropOpt.isPresent()) {
+ properties = marshallerPropOpt.get();
} else {
- properties = request.getMarshallerProperties().get();
+ properties = new MarshallerProperties.Builder(
+ org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
}
result = obj.marshal(properties);
}
result = formatter.output(vertices.stream().map(vertex -> (Object) vertex)
.collect(Collectors.toList())).toString();
- if(outputMediaType == null){
+ if (outputMediaType == null) {
outputMediaType = MediaType.APPLICATION_JSON;
}
- if(MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(outputMediaType))){
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(outputMediaType))) {
result = xmlFormatTransformer.transform(result);
}
status = Status.OK;
result = formatter.output(vertices.stream().map(vertex -> (Object) vertex)
.collect(Collectors.toList())).toString();
- if(outputMediaType == null){
+ if (outputMediaType == null) {
outputMediaType = MediaType.APPLICATION_JSON;
}
- if(MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(outputMediaType))){
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(outputMediaType))) {
result = xmlFormatTransformer.transform(result);
}
status = Status.OK;
if (notificationDepth == AAIProperties.MINIMUM_DEPTH) {
Map<String, Pair<Introspector, LinkedHashMap<String,Introspector>>> allImpliedDeleteObjs = serializer.getImpliedDeleteUriObjectPair();
- for(Map.Entry<String, Pair<Introspector, LinkedHashMap<String,Introspector>>> entry: allImpliedDeleteObjs.entrySet()){
+ for (Map.Entry<String, Pair<Introspector, LinkedHashMap<String,Introspector>>> entry: allImpliedDeleteObjs.entrySet()) {
// The format is purposefully %s/%s%s due to the fact
// that every aai-uri will have a slash at the beginning
// If that assumption isn't true, then its best to change this code
/**
* Generate notification events for the resulting db requests.
*/
- private void generateEvents(String sourceOfTruth, DBSerializer serializer, String transactionId, QueryEngine queryEngine, Set<Vertex> mainVertexesToNotifyOn) throws AAIException {
+ private void generateEvents(String sourceOfTruth, DBSerializer serializer, String transactionId,
+ QueryEngine queryEngine, Set<Vertex> mainVertexesToNotifyOn)
+ throws AAIException {
if (notificationDepth == AAIProperties.MINIMUM_DEPTH) {
- serializer.getUpdatedVertexes().entrySet().stream().filter(Map.Entry::getValue).map(Map.Entry::getKey).forEach(mainVertexesToNotifyOn::add);
+ serializer.getUpdatedVertexes().entrySet().stream().filter(Map.Entry::getValue)
+ .map(Map.Entry::getKey).forEach(mainVertexesToNotifyOn::add);
}
Set<Vertex> edgeVertexes = serializer.touchStandardVertexPropertiesForEdges().stream()
.filter(v -> !mainVertexesToNotifyOn.contains(v)).collect(Collectors.toSet());
// Since @Autowired required is set to false, we need to do a null check
// for the existence of the validationService since its only enabled if profile is enabled
- if(validationService != null){
+ if (validationService != null){
validationService.validate(notification.getEvents());
}
notification.triggerEvents();
if (isDeltaEventsEnabled) {
try {
- DeltaEvents deltaEvents = new DeltaEvents(transactionId, sourceOfTruth, version.toString(), serializer.getObjectDeltas());
+ DeltaEvents deltaEvents =
+ new DeltaEvents(transactionId, sourceOfTruth, version.toString(),
+ serializer.getObjectDeltas());
deltaEvents.triggerEvents();
} catch (Exception e) {
LOGGER.error("Error sending Delta Events", e);
*/
private void createNotificationEvents(Set<Vertex> vertexesToNotifyOn, String sourceOfTruth, DBSerializer serializer,
String transactionId, QueryEngine queryEngine, int eventDepth) throws AAIException, UnsupportedEncodingException {
- for(Vertex vertex : vertexesToNotifyOn){
+ for (Vertex vertex : vertexesToNotifyOn) {
if (canGenerateEvent(vertex)) {
boolean isCurVertexNew = vertex.value(AAIProperties.CREATED_TS).equals(vertex.value(AAIProperties.LAST_MOD_TS));
Status curObjStatus = (isCurVertexNew) ? Status.CREATED : Status.OK;
if (!curObj.isTopLevel()) {
curRelatedObjs = serializer.getRelatedObjects(queryEngine, vertex, curObj, this.loader);
}
- notification.createNotificationEvent(transactionId, sourceOfTruth, curObjStatus, URI.create(uri), curObj, curRelatedObjs, basePath);
+ notification.createNotificationEvent(transactionId, sourceOfTruth, curObjStatus,
+ URI.create(uri), curObj, curRelatedObjs, basePath);
}
}
}
private boolean canGenerateEvent(Vertex vertex) {
boolean canGenerate = true;
try {
- if(!vertex.property(AAIProperties.AAI_URI).isPresent()){
+ if (!vertex.property(AAIProperties.AAI_URI).isPresent()) {
LOGGER.debug("Encountered an vertex {} with missing aai-uri", vertex.id());
canGenerate = false;
- } else if(!vertex.property(AAIProperties.CREATED_TS).isPresent() || !vertex.property(AAIProperties.LAST_MOD_TS).isPresent()){
+ } else if (!vertex.property(AAIProperties.CREATED_TS).isPresent() ||
+ !vertex.property(AAIProperties.LAST_MOD_TS).isPresent()) {
LOGGER.debug("Encountered an vertex {} with missing timestamp", vertex.id());
canGenerate = false;
}
package org.onap.aai.rest.ueb;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.core.Response.Status;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.parsers.uri.URIToObject;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
-
-import javax.ws.rs.core.Response.Status;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The Class UEBNotification.
private String getUri(String uri, String basePath) {
if (uri == null || uri.isEmpty()) {
- return uri;
+ return "";
} else if (uri.charAt(0) != '/') {
uri = '/' + uri;
}
package org.onap.aai.restcore;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.tools.*;
+import org.onap.aai.introspection.tools.CreateUUID;
+import org.onap.aai.introspection.tools.DefaultFields;
+import org.onap.aai.introspection.tools.InjectKeysFromURI;
+import org.onap.aai.introspection.tools.IntrospectorValidator;
+import org.onap.aai.introspection.tools.Issue;
+import org.onap.aai.introspection.tools.RemoveNonVisibleProperty;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.FormatDate;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Base class for AAI REST API classes.
String.format("Timeout limit of %s seconds reached.", timeoutLimit / 1000));
response = consumerExceptionResponseGenerator(headers, info, method, ex);
handler.cancel(true);
+ } catch (InterruptedException e) {
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = consumerExceptionResponseGenerator(headers, info, method, ex);
+ Thread.currentThread().interrupt();
} catch (Exception e) {
AAIException ex = new AAIException("AAI_4000", e);
response = consumerExceptionResponseGenerator(headers, info, method, ex);
*/
package org.onap.aai.serialization.db;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.base.CaseFormat;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.ws.rs.core.UriBuilder;
import org.apache.commons.lang.StringUtils;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.IntrospectorFactory;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.introspection.ModelType;
+import org.onap.aai.introspection.PropertyPredicates;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import org.onap.aai.introspection.sideeffect.*;
+import org.onap.aai.introspection.sideeffect.DataCopy;
+import org.onap.aai.introspection.sideeffect.DataLinkReader;
+import org.onap.aai.introspection.sideeffect.DataLinkWriter;
+import org.onap.aai.introspection.sideeffect.OwnerCheck;
+import org.onap.aai.introspection.sideeffect.PrivateEdge;
+import org.onap.aai.introspection.sideeffect.SideEffectRunner;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.logging.LogFormatTools;
import org.onap.aai.logging.StopWatch;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
-import org.onap.aai.util.delta.*;
+import org.onap.aai.util.delta.DeltaAction;
+import org.onap.aai.util.delta.ObjectDelta;
+import org.onap.aai.util.delta.PropertyDelta;
+import org.onap.aai.util.delta.PropertyDeltaFactory;
+import org.onap.aai.util.delta.RelationshipDelta;
import org.onap.aai.workarounds.NamingExceptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Array;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
public class DBSerializer {
private static final Logger LOGGER = LoggerFactory.getLogger(DBSerializer.class);
return updatedVertexes;
}
- public Map<String, Pair<Introspector, LinkedHashMap<String, Introspector>>> getImpliedDeleteUriObjectPair(){
+ public Map<String, Pair<Introspector, LinkedHashMap<String, Introspector>>> getImpliedDeleteUriObjectPair() {
return impliedDeleteUriObjectPair;
}
getObjectDeltas().get(uri).setAction(objDeltaAction);
}
- addPropDelta(uri, AAIProperties.AAI_UUID, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.AAI_UUID).value()), objDeltaAction);
- addPropDelta(uri, AAIProperties.NODE_TYPE, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.NODE_TYPE).value()), objDeltaAction);
- addPropDelta(uri, AAIProperties.SOURCE_OF_TRUTH, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.SOURCE_OF_TRUTH).value()), objDeltaAction);
- addPropDelta(uri, AAIProperties.CREATED_TS, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.CREATED_TS).value()), objDeltaAction);
+ addPropDelta(uri, AAIProperties.AAI_UUID, PropertyDeltaFactory
+ .getDelta(DeltaAction.STATIC, v.property(AAIProperties.AAI_UUID).value()),
+ objDeltaAction);
+ addPropDelta(uri, AAIProperties.NODE_TYPE, PropertyDeltaFactory
+ .getDelta(DeltaAction.STATIC, v.property(AAIProperties.NODE_TYPE).value()),
+ objDeltaAction);
+ addPropDelta(uri, AAIProperties.SOURCE_OF_TRUTH, PropertyDeltaFactory
+ .getDelta(DeltaAction.STATIC, v.property(AAIProperties.SOURCE_OF_TRUTH).value()),
+ objDeltaAction);
+ addPropDelta(uri, AAIProperties.CREATED_TS, PropertyDeltaFactory
+ .getDelta(DeltaAction.STATIC, v.property(AAIProperties.CREATED_TS).value()),
+ objDeltaAction);
if (objDeltaAction.equals(DeltaAction.UPDATE)) {
addPropDelta(
}
}
- public Map<String, ObjectDelta> getObjectDeltas() {return objectDeltas;}
+ public Map<String, ObjectDelta> getObjectDeltas() {
+ return objectDeltas;
+ }
private void addPropDelta(String uri, String prop, PropertyDelta delta, DeltaAction objDeltaAction) {
ObjectDelta objectDelta = this.objectDeltas.getOrDefault(uri, new ObjectDelta(uri, objDeltaAction, this.sourceOfTruth, this.currentTimeMillis));
ImpliedDelete impliedDelete = new ImpliedDelete(engine, this);
List<Vertex> impliedDeleteVertices = impliedDelete.execute(v.id(), sourceOfTruth, obj.getName(), dependentVertexes);
- if(notificationDepth == AAIProperties.MINIMUM_DEPTH){
- for(Vertex curVertex : impliedDeleteVertices){
- if(!curVertex.property("aai-uri").isPresent()){
+ if (notificationDepth == AAIProperties.MINIMUM_DEPTH) {
+ for (Vertex curVertex : impliedDeleteVertices) {
+ if (!curVertex.property("aai-uri").isPresent()) {
LOGGER.debug("Encountered an vertex {} with missing aai-uri", curVertex.id());
continue;
}
LinkedHashMap<String, Introspector> curObjRelated = new LinkedHashMap<>();
- if(!curObj.isTopLevel()){
+ if (!curObj.isTopLevel()) {
curObjRelated.putAll(this.getRelatedObjects(engine.getQueryEngine(), curVertex, curObj, this.loader));
}
- if(!impliedDeleteUriObjectPair.containsKey(curAaiUri)){
+ if (!impliedDeleteUriObjectPair.containsKey(curAaiUri)) {
impliedDeleteUriObjectPair.put(curAaiUri, new Pair<>(curObj, curObjRelated));
}
}
if (rules.size() == 1) {
label = rules.get(0).getLabel();
} else {
- Optional<EdgeRule> defaultRule = rules.stream().filter(EdgeRule::isDefault).findFirst();
+ Optional<EdgeRule>
+ defaultRule = rules.stream().filter(EdgeRule::isDefault).findFirst();
if (defaultRule.isPresent()) {
label = defaultRule.get().getLabel();
} else {
for (Future<Object> future : futures) {
try {
getList.add(future.get());
- } catch (ExecutionException | InterruptedException e) {
+ } catch (InterruptedException e) {
+ dbTimeMsecs += StopWatch.stopIfStarted();
+ Thread.currentThread().interrupt();
+ throw new AAIException("AAI_4000", e);
+ } catch (ExecutionException e) {
dbTimeMsecs += StopWatch.stopIfStarted();
throw new AAIException("AAI_4000", e);
}
Object result =
dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp, isSkipRelatedTo);
- if (result != null) {
+ if (result != null && getList != null) {
getList.add(argumentObject.getUnderlyingObject());
}
.edgeType(EdgeType.COUSIN)
.version(obj.getVersion());
- for (Path path : paths){
- if(path.size() < 3){
+ for (Path path : paths) {
+ if (path.size() < 3) {
continue;
}
// path objects.get(1) returns edge related-to
// path objects.get(2) returns vertex otherV
Edge edge = path.get(1);
- Vertex otherV= path.get(2);
+ Vertex otherV = path.get(2);
// TODO: Come back and revisit this code
// Create a query based on the a nodetype and b nodetype
String edgeLabel = edge.label();
EdgeRuleQuery ruleQuery = queryBuilder.to(bNodeType).label(edgeLabel).build();
- if(!edgeIngestor.hasRule(ruleQuery)){
+ if (!edgeIngestor.hasRule(ruleQuery)) {
LOGGER.debug( "Caught an edge rule not found for query {}", ruleQuery);
continue;
}
/**
* Gets all the edges between the vertexes with the label and type.
*
- * @param aVertex the out vertex
- * @param bVertex the in vertex
+ * @param vertexOut the out vertex
+ * @param vertexIn the in vertex
* @param label
* @return the edges between
* @throws AAIException the AAI exception
*/
- private Edge getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
+ private Edge getEdgesBetween(EdgeType type, Vertex vertexOut, Vertex vertexIn, String label) throws AAIException {
Edge edge = null;
- if (bVertex != null) {
- String aType = aVertex.<String>property(AAIProperties.NODE_TYPE).value();
- String bType = bVertex.<String>property(AAIProperties.NODE_TYPE).value();
- EdgeRuleQuery q = new EdgeRuleQuery.Builder(aType, bType).edgeType(type).label(label).build();
+ if (vertexIn != null) {
+ String aType = vertexOut.<String>property(AAIProperties.NODE_TYPE).value();
+ String bType = vertexIn.<String>property(AAIProperties.NODE_TYPE).value();
+ EdgeRuleQuery query = new EdgeRuleQuery.Builder(aType, bType).edgeType(type).label(label).build();
EdgeRule rule;
try {
- rule = edgeRules.getRule(q);
+ rule = edgeRules.getRule(query);
} catch (EdgeRuleNotFoundException e) {
throw new NoEdgeRuleFoundException(e);
} catch (AmbiguousRuleChoiceException e) {
throw new MultipleEdgeRuleFoundException(e);
}
- edge = this.getEdgeBetweenWithLabel(type, aVertex, bVertex, rule);
+ edge = this.getEdgeBetweenWithLabel(type, vertexOut, vertexIn, rule);
}
return edge;
/**
* Gets the edge between with the label and edge type.
*
- * @param aVertex the out vertex
- * @param bVertex the in vertex
+ * @param vertexOut the out vertex
+ * @param vertexIn the in vertex
* @param label
* @return the edge between
* @throws AAIException the AAI exception
* @throws NoEdgeRuleFoundException
*/
- public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
+ public Edge getEdgeBetween(EdgeType type, Vertex vertexOut, Vertex vertexIn, String label) throws AAIException {
StopWatch.conditionalStart();
- if (bVertex != null) {
+ if (vertexIn != null) {
- Edge edge = this.getEdgesBetween(type, aVertex, bVertex, label);
+ Edge edge = this.getEdgesBetween(type, vertexOut, vertexIn, label);
if (edge != null) {
dbTimeMsecs += StopWatch.stopIfStarted();
return edge;
throw new AAIException(AAI_6129, e);
}
if (edge != null) {
- if(isDeltaEventsEnabled) {
+ if (isDeltaEventsEnabled) {
String mainUri = inputVertex.property(AAIProperties.AAI_URI).value().toString();
deltaForEdge(mainUri, edge, DeltaAction.DELETE_REL, DeltaAction.UPDATE);
}
dbTimeMsecs += StopWatch.stopIfStarted();
}
- private void deltaForVertexDelete(Vertex v) {
- String aaiUri = v.property(AAIProperties.AAI_URI).value().toString();
- v.keys().forEach(k -> {
+ private void deltaForVertexDelete(Vertex vertex) {
+ String aaiUri = vertex.property(AAIProperties.AAI_URI).value().toString();
+ vertex.keys().forEach(k -> {
List<Object> list = new ArrayList<>();
- v.properties(k).forEachRemaining(vp -> list.add(vp.value()));
+ vertex.properties(k).forEachRemaining(vp -> list.add(vp.value()));
if (list.size() == 1) {
- addPropDelta(aaiUri, k, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, list.get(0)), DeltaAction.DELETE);
+ addPropDelta(aaiUri, k,
+ PropertyDeltaFactory.getDelta(DeltaAction.DELETE, list.get(0)),
+ DeltaAction.DELETE);
} else {
- addPropDelta(aaiUri, k, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, list), DeltaAction.DELETE);
+ addPropDelta(aaiUri, k, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, list),
+ DeltaAction.DELETE);
}
});
- v.edges(Direction.BOTH).forEachRemaining(e -> deltaForEdge(aaiUri, e, DeltaAction.DELETE, DeltaAction.DELETE));
+ vertex.edges(Direction.BOTH).forEachRemaining(e -> deltaForEdge(aaiUri, e, DeltaAction.DELETE, DeltaAction.DELETE));
}
/**
/**
* Delete.
*
- * @param v the v
+ * @param vertex the vertex
* @param resourceVersion the resource version
* @throws IllegalArgumentException the illegal argument exception
* @throws AAIException the AAI exception
* @throws InterruptedException the interrupted exception
*/
- public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion)
+ public void delete(Vertex vertex, String resourceVersion, boolean enableResourceVersion)
throws IllegalArgumentException, AAIException {
- boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
+ boolean result = verifyDeleteSemantics(vertex, resourceVersion, enableResourceVersion);
if (result) {
try {
- deleteWithTraversal(v);
+ deleteWithTraversal(vertex);
} catch (IllegalStateException e) {
throw new AAIException("AAI_6110", e);
}
if (!preventDeleteVertices.isEmpty()) {
aaiExceptionCode = "AAI_6110";
errorDetail = String.format(
- "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types %s",
- preventDeleteVertices);
+ "Object is being reference by additional objects preventing it from being deleted." +
+ " Please clean up references from the following types %s",
+ preventDeleteVertices);
result = false;
}
if (!result) {
private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException {
SideEffectRunner.Builder runnerBuilder =
- new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataCopy.class).addSideEffect(PrivateEdge.class);
+ new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataCopy.class)
+ .addSideEffect(PrivateEdge.class);
if (isMultiTenancyEnabled) {
runnerBuilder.addSideEffect(OwnerCheck.class);
}
* This is for a one-time run with Tenant Isloation to only filter relationships
*
* @param obj the obj
- * @param v the vertex from the graph
+ * @param vertex the vertex from the graph
* @param depth the depth
* @param nodeOnly specify if to exclude relationships or not
* @param filterCousinNodes
* @throws AAIUnknownObjectException
* @throws URISyntaxException
*/
- public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
+ public Introspector dbToObjectWithFilters(Introspector obj, Vertex vertex, Set<Vertex> seen, int depth, boolean nodeOnly,
List<String> filterCousinNodes, List<String> filterParentNodes)
throws AAIException, UnsupportedEncodingException {
- return dbToObjectWithFilters(obj, v, seen, depth, nodeOnly,
+ return dbToObjectWithFilters(obj, vertex, seen, depth, nodeOnly,
filterCousinNodes, filterParentNodes, false);
}
* TODO: Chnage the original dbToObject to take filter parent/cousins
*
* @param obj the obj
- * @param v the vertex from the graph
+ * @param vertexParam the vertex from the graph
* @param depth the depth
* @param nodeOnly specify if to exclude relationships or not
* @param filterCousinNodes
* @throws URISyntaxException
*/
// TODO - See if you can merge the 2 dbToObjectWithFilters
- public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
+ public Introspector dbToObjectWithFilters(Introspector obj, Vertex vertexParam, Set<Vertex> seen, int depth, boolean nodeOnly,
List<String> filterCousinNodes, List<String> filterParentNodes, boolean isSkipRelatedTo)
throws AAIException, UnsupportedEncodingException {
String cleanUp = FALSE;
return null;
}
depth--;
- seen.add(v);
+ seen.add(vertexParam);
boolean modified = false;
for (String property : obj.getProperties(PropertyPredicates.isVisible())) {
List<Object> getList = null;
if (!(obj.isComplexType(property) || obj.isListType(property))) {
- this.copySimpleProperty(property, obj, v);
+ this.copySimpleProperty(property, obj, vertexParam);
modified = true;
} else {
if (obj.isComplexType(property)) {
if (!property.equals("relationship-list") && depth >= 0) {
Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
- Object result = dbToObjectWithFilters(argumentObject, v, seen, depth + 1, nodeOnly,
+ Object result = dbToObjectWithFilters(argumentObject, vertexParam, seen, depth + 1, nodeOnly,
filterCousinNodes, filterParentNodes, isSkipRelatedTo);
if (result != null) {
obj.setValue(property, argumentObject.getUnderlyingObject());
/* relationships need to be handled correctly */
Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
relationshipList =
- createFilteredRelationshipList(v, relationshipList, cleanUp, filterCousinNodes, isSkipRelatedTo);
+ createFilteredRelationshipList(vertexParam, relationshipList, cleanUp,
+ filterCousinNodes, isSkipRelatedTo);
if (relationshipList != null) {
obj.setValue(property, relationshipList.getUnderlyingObject());
modified = true;
String genericType = obj.getGenericTypeClass(property).getSimpleName();
if (obj.isComplexGenericType(property) && depth >= 0) {
final String childDbName = convertFromCamelCase(genericType);
- String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ String vertexType = vertexParam.<String>property(AAIProperties.NODE_TYPE).orElse(null);
EdgeRule rule;
boolean isThisParentRequired =
filterParentNodes.parallelStream().anyMatch(childDbName::contains);
- EdgeRuleQuery q = new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build();
+ EdgeRuleQuery query = new EdgeRuleQuery.Builder(vertexType, childDbName).edgeType(EdgeType.TREE).build();
try {
- rule = edgeRules.getRule(q);
+ rule = edgeRules.getRule(query);
} catch (EdgeRuleNotFoundException e) {
throw new NoEdgeRuleFoundException(e);
} catch (AmbiguousRuleChoiceException e) {
if (!rule.getContains().equals(AAIDirection.NONE.toString()) && isThisParentRequired) {
Direction ruleDirection = rule.getDirection();
List<Vertex> verticesList = new ArrayList<>();
- v.vertices(ruleDirection, rule.getLabel()).forEachRemaining(vertex -> {
+ vertexParam.vertices(ruleDirection, rule.getLabel()).forEachRemaining(vertex -> {
if (vertex.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName)) {
verticesList.add(vertex);
}
Object result = dbToObjectWithFilters(argumentObject, childVertex, seen, depth,
nodeOnly, filterCousinNodes, filterParentNodes, isSkipRelatedTo);
- if (result != null) {
+ if (result != null && getList != null) {
getList.add(argumentObject.getUnderlyingObject());
}
}
}
} else if (obj.isSimpleGenericType(property)) {
- List<Object> temp = this.engine.getListProperty(v, property);
+ List<Object> temp = this.engine.getListProperty(vertexParam, property);
if (temp != null) {
getList = obj.getValue(property);
getList.addAll(temp);
if (!modified) {
return null;
}
- this.enrichData(obj, v);
+ this.enrichData(obj, vertexParam);
return obj;
}
/**
* Creates the relationship list with the filtered node types.
*
- * @param v the v
+ * @param vertex the vertex
* @param obj the obj
* @param cleanUp the clean up
* @return the object
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIException the AAI exception
*/
- private Introspector createFilteredRelationshipList(Vertex v, Introspector obj, String cleanUp,
+ private Introspector createFilteredRelationshipList(Vertex vertex, Introspector obj, String cleanUp,
List<String> filterNodes, boolean isSkipRelatedTo) throws UnsupportedEncodingException, AAIException {
- List<Vertex> allCousins = this.engine.getQueryEngine().findCousinVertices(v);
+ List<Vertex> allCousins = this.engine.getQueryEngine().findCousinVertices(vertex);
Iterator<Vertex> cousinVertices = allCousins.stream().filter(item -> {
String node = (String) item.property(AAIProperties.NODE_TYPE).orElse("");
return filterNodes.parallelStream().anyMatch(node::contains);
- }).iterator();
+ }).iterator();
List<Object> relationshipObjList = obj.getValue(RELATIONSHIP);
return this.edgeVertexes;
}
- public void addVertexToEdgeVertexes(Vertex vertex){
+ public void addVertexToEdgeVertexes(Vertex vertex) {
this.edgeVertexes.add(vertex);
}
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.util.*;
-
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class GraphSON implements FormatMapper {
+ private static final Logger logger = LoggerFactory.getLogger(GraphSON.class);
+
private final GraphSONMapper mapper =
GraphSONMapper.build().addRegistry(JanusGraphIoRegistry.getInstance()).create();
private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create();
result = os.toString();
} catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ logger.debug("GraphSON writeVertex error : {}", e.getMessage());
}
JsonObject jsonObject = parser.parse(result).getAsJsonObject();
}
@Override
- public Optional<JsonObject> formatObject(Object o, Map<String, List<String>> properties) throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
+ public Optional<JsonObject> formatObject(Object obj, Map<String, List<String>> properties)
+ throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
return Optional.empty();
}
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.*;
-
public abstract class MultiFormatMapper implements FormatMapper {
- Logger logger = LoggerFactory.getLogger(MultiFormatMapper.class);
+ private static final Logger logger = LoggerFactory.getLogger(MultiFormatMapper.class);
protected boolean isTree = false;
protected static final String PROPERTIES_KEY = "properties";
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-
-import java.util.*;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
import java.util.stream.Collectors;
-
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.introspection.Loader;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import org.onap.aai.serialization.queryformats.params.Depth;
import org.onap.aai.serialization.queryformats.params.AsTree;
+import org.onap.aai.serialization.queryformats.params.Depth;
import org.onap.aai.serialization.queryformats.params.NodesOnly;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
json.addProperty(prop.key(), list);
} else {
// throw exception?
- return null;
+ return Optional.empty();
}
}
json.addProperty(prop.key(), gson.toJson(prop.value()));
} else {
// throw exception?
- return null;
+ return Optional.empty();
}
}
} else {
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-
import java.io.UnsupportedEncodingException;
-import java.util.*;
-
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import org.onap.aai.serialization.queryformats.params.Depth;
import org.onap.aai.serialization.queryformats.params.AsTree;
+import org.onap.aai.serialization.queryformats.params.Depth;
import org.onap.aai.serialization.queryformats.params.NodesOnly;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-
-import javax.ws.rs.core.MultivaluedMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class Resource extends MultiFormatMapper {
+ private static final Logger logger = LoggerFactory.getLogger(Resource.class);
+
private final Loader loader;
private final DBSerializer serializer;
private final JsonParser parser;
for (Map.Entry<?, ? extends Tree<?>> entry : tree.entrySet()) {
JsonObject me = new JsonObject();
if (entry.getKey() instanceof Vertex) {
- Optional<JsonObject> obj = null;
- if (entry.getKey() != null) {
- obj = this.getJsonFromVertex((Vertex) entry.getKey());
- }
- if (obj != null && obj.isPresent()) {
+ Optional<JsonObject> obj = this.getJsonFromVertex((Vertex) entry.getKey());
+ if (obj.isPresent()) {
me = getPropertyFilteredObject(obj, filterPropertiesMap);
} else {
continue;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.Loader;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.onap.aai.util.AAIConfig;
-import java.util.Optional;
-
public class ResourceWithSoT extends MultiFormatMapper {
protected JsonParser parser = new JsonParser();
protected final DBSerializer serializer;
protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
// Null check
if (v == null) {
- return null;
+ return Optional.empty();
}
JsonObject json = new JsonObject();
*/
public static String genDate() {
Date date = new Date();
- DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
+ DateFormat formatter = new SimpleDateFormat("yyMMdd-HH:mm:ss:SSS");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(date);
}
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
-import org.onap.aai.aailog.filter.RestControllerClientLoggingInterceptor;
-import org.onap.aai.exceptions.AAIException;
-
import java.io.FileInputStream;
import java.io.IOException;
-import java.security.*;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
-
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
+import org.onap.aai.aailog.filter.RestControllerClientLoggingInterceptor;
+import org.onap.aai.exceptions.AAIException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HttpsAuthClient {
+ private static final Logger logger = LoggerFactory.getLogger(HttpsAuthClient.class);
+
/**
* The main method.
*
// System.out.println(res.getEntity(String.class).toString());
} catch (KeyManagementException e) {
- e.printStackTrace();
+ logger.debug("HttpsAuthClient KeyManagement error : {}", e.getMessage());
} catch (Exception e) {
- e.printStackTrace();
+ logger.debug("HttpsAuthClient error : {}", e.getMessage());
}
}
/**
ctx = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory kmf = null;
- try(FileInputStream fin = new FileInputStream(keystorePath)) {
+ try (FileInputStream fin = new FileInputStream(keystorePath)) {
kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("PKCS12");
char[] pwd = keystorePassword.toCharArray();
ks.load(fin, pwd);
kmf.init(ks, pwd);
} catch (Exception e) {
- System.out.println("Error setting up kmf: exiting");
- e.printStackTrace();
+ System.out.println("Error setting up kmf: exiting " + e.getMessage());
throw e;
- //System.exit(1);
}
ctx.init(kmf.getKeyManagers(), null, null);
}
}, ctx));
} catch (Exception e) {
- System.out.println("Error setting up config: exiting");
- e.printStackTrace();
+ System.out.println("Error setting up config: exiting " + e.getMessage());
throw e;
- //System.exit(1);
}
Client client = Client.create(config);
* @throws KeyManagementException the key management exception
*/
public static Client getClient() throws KeyManagementException, AAIException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
- String truststore_path = null;
- String truststore_password = null;
- String keystore_path = null;
- String keystore_password = null;
- try {
- truststore_path =
- AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
- truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
- keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
- keystore_password = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
- }
- catch (AAIException e) {
- throw e;
- }
- return(getClient(truststore_path, truststore_password, keystore_path, keystore_password));
+ String truststorePath = null;
+ String truststorePassword = null;
+ String keystorePath = null;
+ String keystorePassword = null;
+ truststorePath =
+ AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
+ truststorePassword = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
+ keystorePath =
+ AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
+ keystorePassword = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
+ return getClient(truststorePath, truststorePassword, keystorePath, keystorePassword);
}
}
*/
private String getTimeStamp(long timestamp) {
//SimpleDateFormat is not thread safe new instance needed
- DateFormat df = new SimpleDateFormat("YYYYMMdd-HH:mm:ss:SSS");
+ DateFormat df = new SimpleDateFormat("yyyyMMdd-HH:mm:ss:SSS");
return df.format(new Date(timestamp));
}
}
package org.onap.aai.exceptions;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.onap.aai.AAISetup;
@Test
public void testConstructorWith0Params() throws Exception {
AAIException exception = new AAIException();
- assertEquals(exception, exception);
+ assertEquals(AAIException.DEFAULT_EXCEPTION_CODE, exception.getCode());
}
/**
@Test
public void testConstructorWith1Params() throws Exception {
AAIException exception = new AAIException(code);
- assertEquals(exception, exception);
+ assertEquals(code, exception.getCode());
}
/**
package org.onap.aai.introspection;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
import org.junit.Assert;
import org.junit.Test;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class MoxyEngineTest extends IntrospectorTestSpec {
+ @Test
+ public void castValueAccordingToSchemaTest() throws AAIUnknownObjectException {
+
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
+ Introspector introspector = loader.introspectorFromName("pserver");
+ Object test1 = "name1";
+ Object result = introspector.castValueAccordingToSchema("hostname", test1);
+ Assert.assertTrue(result instanceof java.lang.String);
+
+ Object test2 = "4";
+ Object result2 = introspector.castValueAccordingToSchema("number-of-cpus", test2);
+ Assert.assertTrue(result2 instanceof java.lang.Integer);
+ }
+
/**
* Container object.
- *
+ *
* @throws AAIUnknownObjectException
*/
@Test
public void containerObject() throws AAIUnknownObjectException {
Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
-
Introspector obj = loader.introspectorFromName("port-groups");
-
this.containerTestSet(obj);
-
+ Assert.assertTrue(true);
}
@Test
package org.onap.aai.introspection.generator;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
public class CreateExampleTest extends AAISetup {
String propName = "direction";
Introspector introspector = loader.introspectorFromName("edge-prop-names");
createExample.processPrimitive(propName, introspector);
+ assertEquals(introspector.getName(), "edge-prop-names");
}
@Test
String propName = "vlan-id-inner";
Introspector introspector = loader.introspectorFromName("ctag-assignment");
createExample.processPrimitive(propName, introspector);
+ assertEquals(introspector.getName(), "ctag-assignment");
}
@Test
String propName = "in-maint";
Introspector introspector = loader.introspectorFromName("vserver");
createExample.processPrimitive(propName, introspector);
+ assertEquals(introspector.getName(), "vserver");
}
@Test
String propName = "module-index";
Introspector introspector = loader.introspectorFromName("vf-module");
createExample.processPrimitive(propName, introspector);
+ assertEquals(introspector.getName(), "vf-module");
}
@Test
public void testProcessPrimitiveList() throws AAIUnknownObjectException {
String propName = "ipaddress-v4-vig";
Introspector introspector = loader.introspectorFromName("vig-server");
- createExample.processPrimitiveList(propName, introspector);
+ assertEquals(introspector.getName(), "vig-server");
}
@Test
// empty method
Introspector introspector = Mockito.mock(Introspector.class);
createExample.processComplexObj(introspector);
+ assertNotNull(introspector);
}
@Test
List<Object> objList = new ArrayList<Object>();
Introspector introspector = Mockito.mock(Introspector.class);
createExample.modifyComplexList(introList, objList, introspector, introspector);
+ assertNotNull(introspector);
}
@Test
package org.onap.aai.introspection.sideeffect;
+import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashSet;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.junit.AfterClass;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.aai.AAISetup;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
import org.onap.aai.serialization.engines.QueryStyle;
"AAI_TEST", new HashSet<>(Arrays.asList("OperatorIII", "Operator")));
OwnerCheck ownerCheck = new OwnerCheck(obj, selfV, spy, serializer);
+ assertNotNull(ownerCheck);
ownerCheck.execute();
g.tx().rollback();
Vertex selfV = g.traversal().V().has("aai-node-type", "pnf").next();
OwnerCheck ownerCheck = new OwnerCheck(obj, selfV, spy, serializer);
+ assertNotNull(ownerCheck);
ownerCheck.execute();
g.tx().rollback();
Vertex selfV = g.traversal().V().has("aai-node-type", "pnf").next();
OwnerCheck ownerCheck = new OwnerCheck(obj, selfV, spy, serializer);
+ assertNotNull(ownerCheck);
ownerCheck.execute();
g.tx().rollback();
Vertex selfV = g.traversal().V().has("aai-node-type", "pnf").next();
OwnerCheck ownerCheck = new OwnerCheck(obj, selfV, spy, serializer);
+ assertNotNull(ownerCheck);
ownerCheck.execute();
g.tx().rollback();
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import java.util.List;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-import org.onap.aai.introspection.*;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
@Test
public void testIntrospectorValidatorGetIssues() throws AAIUnknownObjectException {
setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
- iv.getIssues();
+ List<Issue> result = iv.getIssues();
+ Assert.assertNotNull(result);
+
}
@Test
public void testIntrospectorValidatorProcessComplexObject() throws AAIUnknownObjectException {
setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
iv.processComplexObj(introspector);
+ Assert.assertNotNull(introspector);
}
@Test
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-
import javax.ws.rs.core.Response;
-
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.Ignore;
-import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.serialization.engines.QueryStyle;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class PserverDuplicateTest extends AAISetup {
testUtil = new HttpTestUtil(QueryStyle.TRAVERSAL_URI);
- if (pserverList.size() == 1) {
- return false;
- }
- return true;
+ return pserverList.size() != 1;
}
@Ignore
relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
relationship.setValue("relationship-data", relData);
+ assertEquals("/network/vnfcs/vnfc/a-name", relationship.getValue("related-link"));
+
dbser.createEdge(relationship, gvnf);
}
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
+import java.util.Optional;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
}
@Test
- public void testGetJsonFromVertexWithNullVertex() throws AAIFormatVertexException, AAIException {
- // Null check, will return null.
- assertNull(resourceWithSoT.getJsonFromVertex(null));
+ public void testGetJsonFromVertexWithNullVertex() throws AAIFormatVertexException {
+ // Null check, will return not present Optional.
+ Optional<JsonObject> result = resourceWithSoT.getJsonFromVertex(null);
+ assertFalse(result.isPresent());
}
public void createLoaderEngineSetup() throws AAIException {
import javax.ws.rs.core.MultivaluedMap;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.queryformats.Resource;
import org.onap.aai.serialization.queryformats.Resource.Builder;
+@RunWith(MockitoJUnitRunner.class)
public class QueryParamInjectorTest {
@Mock
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Properties;
-import org.eclipse.jetty.util.security.Password;
-import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.aai.AAISetup;
@Test
public void testGetInt() throws AAIException {
int res = AAIConfig.getInt("aai.example.int");
- assertNotNull(res);
assertEquals(7748, res);
}
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
-
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
-
import javax.xml.bind.JAXBException;
-
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.JAXBMarshaller;
assertTrue(p.getName().contains("example-name-val-"));
assertTrue(p.getNickname().contains("example-nickname-val-"));
assertTrue(p.getPet().contains("example-pet-val-"));
- assertNotNull(p.getAge());
- assertNotNull(p.getHeightcm());
- assertNotNull(p.getWeightlb());
assertTrue(p.isMarried());
}
*/
package org.onap.aai.aailog.filter;
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
import org.onap.aai.aailog.logs.ServiceName;
import org.onap.logging.filter.base.AbstractMetricLogFilter;
import org.onap.logging.filter.base.Constants;
-import org.onap.logging.filter.base.MDCSetup;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.MDC;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
-import org.springframework.http.HttpHeaders;
-
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.IOException;
-import java.util.List;
-import java.util.UUID;
public class RestClientLoggingInterceptor extends AbstractMetricLogFilter<HttpRequest, ClientHttpResponse, HttpHeaders> implements ClientHttpRequestInterceptor {
@Override
String requestId = extractRequestID(requestHeaders);
addHeader(requestHeaders, ONAPLogConstants.Headers.REQUEST_ID, requestId);
addHeader(requestHeaders, Constants.HttpHeaders.HEADER_REQUEST_ID, requestId);
- if (requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID) == null ||
- requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID).isEmpty()) {
+ String transactionId = requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID);
+ if (transactionId == null || transactionId.isEmpty()) {
addHeader(requestHeaders, Constants.HttpHeaders.TRANSACTION_ID, requestId);
}
addHeader(requestHeaders, Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId);
AAIConfig.getConfigFile();
AAIConfig.reloadConfig();
- if (AAIConstants.AAI_NODENAME == null || AAIConstants.AAI_NODENAME == "") {
+ if (AAIConstants.AAI_NODENAME == null || AAIConstants.AAI_NODENAME.equals("")) {
ErrorLogHelper.logError("AAI_4005", " AAI_NODENAME is not defined");
} else {
LOGGER.info("A&AI Server Node Name = " + AAIConstants.AAI_NODENAME);
*/
package org.onap.aai.schemaif.json;
+import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
-import java.io.IOException;
+import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-
import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.schemaif.SchemaProvider;
}
try {
- SchemaServiceResponse resp = SchemaServiceResponse.fromJson(unzipAndGetJSONString(response));
+ SchemaServiceResponse resp = SchemaServiceResponse.fromJson(unzipAndGetJSONString(response.getBody()));
loadSchema(resp.getData().toJson(), version);
}
catch (Exception ex) {
logger.info(SchemaProviderMsgs.LOADED_SCHEMA_FILE, version);
}
- private String unzipAndGetJSONString(ResponseEntity<byte[]> response) throws IOException {
- StringBuffer sb = new StringBuffer("");
-
- ZipInputStream zipStream = null;
- try {
-
- zipStream = new ZipInputStream(new ByteArrayInputStream(response.getBody()));
- ZipEntry entry = null;
- while ((entry = zipStream.getNextEntry()) != null) {
- Scanner sc = new Scanner(zipStream);
- while (sc.hasNextLine()) {
- sb.append(sc.nextLine());
+ static final int BUFFER = 512;
+ static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
+ static final int TOOMANY = 1024; // Max number of files
+
+ protected String unzipAndGetJSONString(byte[] inputData) throws java.io.IOException {
+ ZipEntry entry;
+ String result = "";
+ int entries = 0;
+ long total = 0;
+ try (ByteArrayInputStream bis = new ByteArrayInputStream(inputData); ZipInputStream zis = new ZipInputStream(bis)) {
+ while ((entry = zis.getNextEntry()) != null) {
+ int count;
+ byte[] data = new byte[BUFFER];
+ if (entry.isDirectory()) {
+ continue;
}
-
- }
- } finally {
- try {
- if (zipStream != null) {
- zipStream.closeEntry();
- zipStream.close();
+ ByteArrayOutputStream fos = new ByteArrayOutputStream();
+ BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
+ while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {
+ dest.write(data, 0, count);
+ total += count;
+ }
+ dest.flush();
+ result = fos.toString();
+ dest.close();
+ zis.closeEntry();
+ entries++;
+ if (entries > TOOMANY) {
+ throw new IllegalStateException("Too many files to unzip.");
+ }
+ if (total + BUFFER > TOOBIG) {
+ throw new IllegalStateException("File being unzipped is too big.");
}
- } catch (Exception e) {
- logger.warn(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, e.toString());
-
}
}
-
- return sb.toString();
+ return result;
}
private SchemaInstance getSchemaVersion(String version) throws SchemaProviderException {
/**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2019 AT&T Intellectual Property. All rights reserved.
package org.onap.aai.schemaif.json;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
-
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.schemaif.SchemaProviderException;
JsonSchemaProviderConfig config = new JsonSchemaProviderConfig();
@Before
- public void init() throws Exception {
+ public void init() {
config.setSchemaServiceBaseUrl("https://testurl.com:8443");
config.setSchemaServiceCertFile("/c/certfile");
config.setSchemaServiceCertPwd("my-password");
config.setServiceName("test-service");
}
+ @Test
+ public void testReadZipJson() throws IOException, SchemaProviderException {
+ JsonSchemaProvider jsonSchemaProvider = new JsonSchemaProvider(config);
+
+ ByteArrayOutputStream fos = new ByteArrayOutputStream();
+ ZipOutputStream zos = new ZipOutputStream(fos);
+ zos.putNextEntry(new ZipEntry("schemaServiceResponse.json"));
+ byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/json/schemaServiceResponse.json"));
+ zos.write(fileData, 0, fileData.length);
+ zos.closeEntry();
+ zos.close();
+
+ String testSchema = readFile("src/test/resources/json/schemaServiceResponse.json");
+ SchemaServiceResponse resp = SchemaServiceResponse.fromJson(testSchema);
+
+ String result = jsonSchemaProvider.unzipAndGetJSONString(fos.toByteArray());
+ SchemaServiceResponse resp2 = SchemaServiceResponse.fromJson(result);
+ assertEquals(resp.toJson(), resp2.toJson());
+ }
+
@Test
public void testJsonSchemaLoad() {
try {
// Test Edge Schema
JsonEdgeSchema edgeSchema = null;
for (JsonEdgeSchema edge : jsonSchema.getRelationshipTypes()) {
- if ( (edge.getFrom().equals("onap.nodes.sdwan.uCPE"))
+ if ( (edge.getFrom().equals("onap.nodes.sdwan.uCPE"))
&& (edge.getTo().equals("onap.nodes.sdwan.service.SubscriberService")) ) {
edgeSchema = edge;
break;
}
}
- assertTrue(edgeSchema.getLabel().equals("onap.relationships.sdwan.BelongsTo"));
+ assertNotNull(edgeSchema);
+ assertEquals("onap.relationships.sdwan.BelongsTo", edgeSchema.getLabel());
// Test Node Schema
JsonVertexSchema vertexSchema = null;
}
}
- assertTrue(vertexSchema.getProperties().size() == 2);
+ assertNotNull(vertexSchema);
+ assertEquals(2, vertexSchema.getProperties().size());
JsonPropertySchema propSchema = null;
for (JsonPropertySchema p : vertexSchema.getProperties()) {
}
}
- assertTrue(propSchema.getRequired() == false);
- assertTrue(propSchema.getUnique() == false);
- assertTrue(propSchema.getDataType().equals("org.onap.datatypes.RuleList"));
- assertTrue(propSchema.getDefaultValue().equals(""));
- assertTrue(propSchema.getAnnotations().size() == 4);
+ assertNotNull(propSchema);
+ assertEquals(false, propSchema.getRequired());
+ assertEquals(false, propSchema.getUnique());
+ assertEquals("org.onap.datatypes.RuleList", propSchema.getDataType());
+ assertEquals("", propSchema.getDefaultValue());
+ assertEquals(4, propSchema.getAnnotations().size());
// Test DataType Schema
DataTypeDefinition dataType = null;
}
}
- assertTrue(dataType.getName().equals("org.onap.datatypes.network.VlanRequirements"));
- assertTrue(dataType.getProperties().size() == 4);
+ assertNotNull(dataType);
+ assertEquals("org.onap.datatypes.network.VlanRequirements", dataType.getName());
+ assertEquals(4, dataType.getProperties().size());
propSchema = null;
for (JsonPropertySchema p : dataType.getProperties()) {
}
}
- assertTrue(propSchema.getRequired() == false);
- assertTrue(propSchema.getDataType().equals("string"));
- assertTrue(propSchema.getDefaultValue().equals(""));
+ assertNotNull(propSchema);
+ assertEquals(false, propSchema.getRequired());
+ assertEquals("string", propSchema.getDataType());
+ assertEquals("", propSchema.getDefaultValue());
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- VertexSchema vertSchema =
- schemaProvider.getVertexSchema("tosca.nodes.objectstorage",
+ VertexSchema vertSchema =
+ schemaProvider.getVertexSchema("tosca.nodes.objectstorage",
schemaProvider.getLatestSchemaVersion());
System.out.println(vertSchema.toString());
// Validate vertex schema
- assertTrue(vertSchema.getName().equals("tosca.nodes.ObjectStorage"));
- assertTrue(vertSchema.getAnnotationValue("searchable").equals("size,name"));
- assertTrue(vertSchema.getAnnotationValue("indexedProps").equals("aai-uuid,name"));
+ assertEquals("tosca.nodes.ObjectStorage", vertSchema.getName());
+ assertEquals("size,name", vertSchema.getAnnotationValue("searchable"));
+ assertEquals("aai-uuid,name", vertSchema.getAnnotationValue("indexedProps"));
PropertySchema propSchema = vertSchema.getPropertySchema("Name");
- assertTrue(propSchema.getName().equals("name"));
- assertTrue(propSchema.getDefaultValue().equals(""));
+ assertEquals("name", propSchema.getName());
+ assertEquals("", propSchema.getDefaultValue());
assertTrue(propSchema.isRequired());
- assertTrue(!propSchema.isKey());
- assertTrue(!propSchema.isReserved());
- assertTrue(propSchema.getDataType().getType().compareTo(Type.STRING) == 0);
- assertTrue(propSchema.getAnnotationValue("Source_of_truth_type").equals("AAI"));
+ assertFalse(propSchema.isKey());
+ assertFalse(propSchema.isReserved());
+ assertEquals(0, propSchema.getDataType().getType().compareTo(Type.STRING));
+ assertEquals("AAI", propSchema.getAnnotationValue("Source_of_truth_type"));
propSchema = vertSchema.getPropertySchema("Size");
- assertTrue(propSchema.getName().equals("size"));
- assertTrue(propSchema.getDefaultValue().equals("50"));
- assertTrue(propSchema.getDataType().getType().compareTo(Type.INT) == 0);
-
+ assertEquals("size", propSchema.getName());
+ assertEquals("50", propSchema.getDefaultValue());
+ assertEquals(0, propSchema.getDataType().getType().compareTo(Type.INT));
+
propSchema = vertSchema.getPropertySchema("source-of-truth");
- assertTrue(propSchema.getName().equals("source-of-truth"));
- assertTrue(!propSchema.isRequired());
+ assertEquals("source-of-truth", propSchema.getName());
+ assertFalse(propSchema.isRequired());
assertTrue(propSchema.isReserved());
- assertTrue(propSchema.getDataType().getType().compareTo(Type.STRING) == 0);
+ assertEquals(0, propSchema.getDataType().getType().compareTo(Type.STRING));
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- EdgeSchema edgeSchema = schemaProvider.getEdgeSchema("tosca.relationships.hostedOn",
- "tosca.nodes.Softwarecomponent", "tosca.nodes.compute",
+ EdgeSchema edgeSchema = schemaProvider.getEdgeSchema("tosca.relationships.hostedOn",
+ "tosca.nodes.Softwarecomponent", "tosca.nodes.compute",
schemaProvider.getLatestSchemaVersion());
System.out.println(edgeSchema.toString());
// Validate edge schema
- assertTrue(edgeSchema.getName().equals("tosca.relationships.HostedOn"));
- assertTrue(edgeSchema.getSource().equals("tosca.nodes.SoftwareComponent"));
- assertTrue(edgeSchema.getTarget().equals("tosca.nodes.Compute"));
- assertTrue(edgeSchema.getMultiplicity().equals(EdgeSchema.Multiplicity.MANY_2_MANY));
- assertTrue(edgeSchema.getAnnotationValue("contains-other-v").equals("NONE"));
+ assertEquals("tosca.relationships.HostedOn", edgeSchema.getName());
+ assertEquals("tosca.nodes.SoftwareComponent", edgeSchema.getSource());
+ assertEquals("tosca.nodes.Compute", edgeSchema.getTarget());
+ assertEquals(edgeSchema.getMultiplicity(), EdgeSchema.Multiplicity.MANY_2_MANY);
+ assertEquals("NONE", edgeSchema.getAnnotationValue("contains-other-v"));
}
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- Set<EdgeSchema> edgeSchemaList =
- schemaProvider.getAdjacentEdgeSchema("tosca.nodes.Database",
+ Set<EdgeSchema> edgeSchemaList =
+ schemaProvider.getAdjacentEdgeSchema("tosca.nodes.Database",
schemaProvider.getLatestSchemaVersion());
// Validate edge schema
- assertTrue(edgeSchemaList.size() == 3);
+ assertEquals(3, edgeSchemaList.size());
for (EdgeSchema es : edgeSchemaList) {
System.out.println(es.toString());
- if (es.getName().equals("tosca.relationships.HostedOn")) {
- assertTrue(es.getSource().equals("tosca.nodes.Database"));
- assertTrue(es.getTarget().equals("tosca.nodes.DBMS"));
- assertTrue(es.getMultiplicity().equals(EdgeSchema.Multiplicity.MANY_2_MANY));
- }
- else if (es.getName().equals("tosca.relationships.RoutesTo")) {
- assertTrue(es.getSource().equals("tosca.nodes.LoadBalancer"));
- assertTrue(es.getTarget().equals("tosca.nodes.Database"));
- assertTrue(es.getMultiplicity().equals(EdgeSchema.Multiplicity.MANY_2_MANY));
- }
- else if (es.getName().equals("tosca.relationships.Uses")) {
- assertTrue(es.getSource().equals("tosca.nodes.LoadBalancer"));
- assertTrue(es.getTarget().equals("tosca.nodes.Database"));
- assertTrue(es.getMultiplicity().equals(EdgeSchema.Multiplicity.MANY_2_MANY));
- }
- else {
- assertTrue(false);
+ switch (es.getName()) {
+ case "tosca.relationships.HostedOn":
+ assertEquals("tosca.nodes.Database", es.getSource());
+ assertEquals("tosca.nodes.DBMS", es.getTarget());
+ assertEquals(es.getMultiplicity(), EdgeSchema.Multiplicity.MANY_2_MANY);
+ break;
+ case "tosca.relationships.RoutesTo":
+ case "tosca.relationships.Uses":
+ assertEquals("tosca.nodes.LoadBalancer", es.getSource());
+ assertEquals("tosca.nodes.Database", es.getTarget());
+ assertEquals(es.getMultiplicity(), EdgeSchema.Multiplicity.MANY_2_MANY);
+ break;
+ default:
+ fail();
+ break;
}
}
}
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- Set<EdgeSchema> edgeSchemaList =
- schemaProvider.getEdgeSchemaForSourceTarget("tosca.nodes.LoadBalancer",
- "tosca.nodes.Database",
+ Set<EdgeSchema> edgeSchemaList =
+ schemaProvider.getEdgeSchemaForSourceTarget("tosca.nodes.LoadBalancer",
+ "tosca.nodes.Database",
schemaProvider.getLatestSchemaVersion());
// Validate edge schema
- assertTrue(edgeSchemaList.size() == 2);
+ assertEquals(2, edgeSchemaList.size());
for (EdgeSchema es : edgeSchemaList) {
System.out.println(es.toString());
if (es.getName().equals("tosca.relationships.Uses")) {
- assertTrue(es.getSource().equals("tosca.nodes.LoadBalancer"));
- assertTrue(es.getTarget().equals("tosca.nodes.Database"));
- assertTrue(es.getMultiplicity().equals(EdgeSchema.Multiplicity.MANY_2_MANY));
+ assertEquals("tosca.nodes.LoadBalancer", es.getSource());
+ assertEquals("tosca.nodes.Database", es.getTarget());
+ assertEquals(es.getMultiplicity(), EdgeSchema.Multiplicity.MANY_2_MANY);
}
else if (es.getName().equals("tosca.relationships.RoutesTo")) {
- assertTrue(es.getSource().equals("tosca.nodes.LoadBalancer"));
- assertTrue(es.getTarget().equals("tosca.nodes.Database"));
- assertTrue(es.getMultiplicity().equals(EdgeSchema.Multiplicity.MANY_2_MANY));
+ assertEquals("tosca.nodes.LoadBalancer", es.getSource());
+ assertEquals("tosca.nodes.Database", es.getTarget());
+ assertEquals(es.getMultiplicity(), EdgeSchema.Multiplicity.MANY_2_MANY);
}
else {
- assertTrue(false);
+ fail();
}
}
}
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- EdgeSchema edgeSchema =
- schemaProvider.getEdgeSchema("amdocs.linkedTo", "service-instance",
+ EdgeSchema edgeSchema =
+ schemaProvider.getEdgeSchema("amdocs.linkedTo", "service-instance",
"onap.nodes.sdwan.ManagementDomain", schemaProvider.getLatestSchemaVersion());
- assertTrue(edgeSchema.getName().equals("amdocs.linkedTo"));
- assertTrue(edgeSchema.getSource().equals("service-instance"));
- assertTrue(edgeSchema.getTarget().equals("onap.nodes.sdwan.ManagementDomain"));
+ assertEquals("amdocs.linkedTo", edgeSchema.getName());
+ assertEquals("service-instance", edgeSchema.getSource());
+ assertEquals("onap.nodes.sdwan.ManagementDomain", edgeSchema.getTarget());
- edgeSchema = schemaProvider.getEdgeSchema("amdocs.linkedTo", "onap.nodes.sdwan.ManagementDomain",
+ edgeSchema = schemaProvider.getEdgeSchema("amdocs.linkedTo", "onap.nodes.sdwan.ManagementDomain",
"service-instance", schemaProvider.getLatestSchemaVersion());
- assertTrue(edgeSchema == null);
-
-
- edgeSchema =
- schemaProvider.getEdgeSchema("amdocs.unknownRelationship", "unknown",
+ assertNull(edgeSchema);
+
+
+ edgeSchema =
+ schemaProvider.getEdgeSchema("amdocs.unknownRelationship", "unknown",
"onap.nodes.sdwan.ManagementDomain", schemaProvider.getLatestSchemaVersion());
-
- assertTrue(edgeSchema.getName().equals("amdocs.unknownRelationship"));
- assertTrue(edgeSchema.getSource().equals("unknown"));
- assertTrue(edgeSchema.getTarget().equals("onap.nodes.sdwan.ManagementDomain"));
-
- edgeSchema =
- schemaProvider.getEdgeSchema("amdocs.unknownRelationship", "onap.nodes.sdwan.ManagementDomain",
+
+ assertEquals("amdocs.unknownRelationship", edgeSchema.getName());
+ assertEquals("unknown", edgeSchema.getSource());
+ assertEquals("onap.nodes.sdwan.ManagementDomain", edgeSchema.getTarget());
+
+ edgeSchema =
+ schemaProvider.getEdgeSchema("amdocs.unknownRelationship", "onap.nodes.sdwan.ManagementDomain",
"unknown", schemaProvider.getLatestSchemaVersion());
-
- assertTrue(edgeSchema.getName().equals("amdocs.unknownRelationship"));
- assertTrue(edgeSchema.getSource().equals("onap.nodes.sdwan.ManagementDomain"));
- assertTrue(edgeSchema.getTarget().equals("unknown"));
-
- Set<EdgeSchema> edgeSchemaList =
- schemaProvider.getEdgeSchemaForSourceTarget("service-instance",
- "onap.nodes.sdwan.ManagementDomain",
+
+ assertEquals("amdocs.unknownRelationship", edgeSchema.getName());
+ assertEquals("onap.nodes.sdwan.ManagementDomain", edgeSchema.getSource());
+ assertEquals("unknown", edgeSchema.getTarget());
+
+ Set<EdgeSchema> edgeSchemaList =
+ schemaProvider.getEdgeSchemaForSourceTarget("service-instance",
+ "onap.nodes.sdwan.ManagementDomain",
schemaProvider.getLatestSchemaVersion());
- assertTrue(edgeSchemaList.size() == 1);
-
- edgeSchemaList = schemaProvider.getEdgeSchemaForSourceTarget("unknown", "unknown",
+ assertEquals(1, edgeSchemaList.size());
+
+ edgeSchemaList = schemaProvider.getEdgeSchemaForSourceTarget("unknown", "unknown",
schemaProvider.getLatestSchemaVersion());
- assertTrue(edgeSchemaList.size() == 1);
-
- edgeSchemaList = schemaProvider.getEdgeSchemaForSourceTarget("service-instance", "service-instance",
+ assertEquals(1, edgeSchemaList.size());
+
+ edgeSchemaList = schemaProvider.getEdgeSchemaForSourceTarget("service-instance", "service-instance",
schemaProvider.getLatestSchemaVersion());
- assertTrue(edgeSchemaList.size() == 1);
-
-
+ assertEquals(1, edgeSchemaList.size());
+
+
edgeSchemaList = schemaProvider.getAdjacentEdgeSchema("service-instance", schemaProvider.getLatestSchemaVersion());
System.out.println("EDGE LIST: \n\n" + edgeSchemaList);
- assertTrue(edgeSchemaList.size() == 8);
+ assertEquals(8, edgeSchemaList.size());
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
-
+
@Test
- public void testInvalidVertexOrEdge() throws SchemaProviderException {
+ public void testInvalidVertexOrEdge() {
try {
String testSchema = readFile("src/test/resources/json/jsonSchema.json");
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- VertexSchema vertSchema =
+ VertexSchema vertSchema =
schemaProvider.getVertexSchema("bad-node", schemaProvider.getLatestSchemaVersion());
- assertTrue(vertSchema == null);
+ assertNull(vertSchema);
- EdgeSchema edgeSchema = schemaProvider.getEdgeSchema("org.onap.relationships.inventory.LocatedIn",
+ EdgeSchema edgeSchema = schemaProvider.getEdgeSchema("org.onap.relationships.inventory.LocatedIn",
"cloud-region", "bad-node", schemaProvider.getLatestSchemaVersion());
- assertTrue(edgeSchema == null);
+ assertNull(edgeSchema);
- Set<EdgeSchema> edgeSchemaList =
- schemaProvider.getAdjacentEdgeSchema("org.onap.nodes.bad-node",
+ Set<EdgeSchema> edgeSchemaList =
+ schemaProvider.getAdjacentEdgeSchema("org.onap.nodes.bad-node",
schemaProvider.getLatestSchemaVersion());
assertTrue(edgeSchemaList.isEmpty());
}
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- VertexSchema vertSchema =
- schemaProvider.getVertexSchema("onap.nodes.sdwan.ManagementDomain",
+ VertexSchema vertSchema =
+ schemaProvider.getVertexSchema("onap.nodes.sdwan.ManagementDomain",
schemaProvider.getLatestSchemaVersion());
System.out.println(vertSchema.toString());
- // Validate schema
+ // Validate schema
PropertySchema propSchema = vertSchema.getPropertySchema("controllers");
- assertTrue(propSchema.getDataType().getType().compareTo(Type.LIST) == 0);
+ assertEquals(0, propSchema.getDataType().getType().compareTo(Type.LIST));
ListDataType listType = (ListDataType)propSchema.getDataType();
- assertTrue(listType.getListType().getType().compareTo(Type.STRING) == 0);
+ assertEquals(0, listType.getListType().getType().compareTo(Type.STRING));
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- VertexSchema vertSchema =
- schemaProvider.getVertexSchema("onap.nodes.sdwan.ManagementDomain",
+ VertexSchema vertSchema =
+ schemaProvider.getVertexSchema("onap.nodes.sdwan.ManagementDomain",
schemaProvider.getLatestSchemaVersion());
System.out.println(vertSchema.toString());
- // Validate schema
+ // Validate schema
PropertySchema propSchema = vertSchema.getPropertySchema("analyticClusters");
- assertTrue(propSchema.getDataType().getType().compareTo(Type.MAP) == 0);
+ assertEquals(0, propSchema.getDataType().getType().compareTo(Type.MAP));
MapDataType mapType = (MapDataType)propSchema.getDataType();
- assertTrue(mapType.getMapType().getType().compareTo(Type.STRING) == 0);
+ assertEquals(0, mapType.getMapType().getType().compareTo(Type.STRING));
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
-
+
@Test
public void testJsonSchemaComplexAttribute() {
try {
JsonSchemaProvider schemaProvider = new JsonSchemaProvider(config);
schemaProvider.loadSchema(testSchema, schemaProvider.getLatestSchemaVersion());
- VertexSchema vertSchema =
- schemaProvider.getVertexSchema("org.onap.resource.extContrailCP",
+ VertexSchema vertSchema =
+ schemaProvider.getVertexSchema("org.onap.resource.extContrailCP",
schemaProvider.getLatestSchemaVersion());
System.out.println(vertSchema.toString());
System.out.println("\n\nSize: " + vertSchema.getPropertySchemaList().size());
System.out.println(vertSchema.getPropertySchemaList());
- assertTrue(vertSchema.getPropertySchemaList().size() == 22);
+ assertEquals(22, vertSchema.getPropertySchemaList().size());
- // Validate property schema
+ // Validate property schema
PropertySchema propSchema = vertSchema.getPropertySchema("exCP_naming");
- assertTrue(propSchema.getDataType().getType().compareTo(Type.COMPLEX) == 0);
+ assertEquals(0, propSchema.getDataType().getType().compareTo(Type.COMPLEX));
ComplexDataType complexType = (ComplexDataType)propSchema.getDataType();
List<PropertySchema> complexProps = complexType.getSubProperties();
- assertTrue(complexProps.size() == 4);
+ assertEquals(4, complexProps.size());
PropertySchema subProp = null;
for (PropertySchema p : complexProps) {
}
}
- assertTrue(!subProp.isRequired());
- assertTrue(subProp.getDataType().getType().compareTo(Type.STRING) == 0);
+ assertNotNull(subProp);
+ assertFalse(subProp.isRequired());
+ assertEquals(0, subProp.getDataType().getType().compareTo(Type.STRING));
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
SchemaServiceResponse resp = SchemaServiceResponse.fromJson(testSchema);
System.out.println(resp.toJson());
- assertTrue(resp.getVersion().equals("v1"));
+ assertEquals("v1", resp.getVersion());
JsonSchema jsonSchema = resp.getData();
System.out.println(jsonSchema.toJson());
- assertTrue(jsonSchema.getDataTypes().size() == 1);
+ assertEquals(1, jsonSchema.getDataTypes().size());
}
catch (Exception ex) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
}
-
+
@Test
public void testSchemaValidateSuccess() {
try {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
- System.out.println(writer.toString());
- assertTrue(false);
+ System.out.println(writer);
+ fail();
}
- }
+ }
@Test(expected = SchemaProviderException.class)
public void testSchemaValidateBadEdge() throws SchemaProviderException {
- SchemaServiceResponse schema;
+ SchemaServiceResponse schema;
try {
String testSchema = readFile("src/test/resources/json/badEdgeSchema.json");
schema = SchemaServiceResponse.fromJson(testSchema);
}
catch (Exception ex) {
- assertTrue(false);
+ fail();
return;
}
schema.getData().validate();
}
-
+
@Test(expected = SchemaProviderException.class)
public void testSchemaValidateBadVertex() throws SchemaProviderException {
- SchemaServiceResponse schema;
+ SchemaServiceResponse schema;
try {
String testSchema = readFile("src/test/resources/json/badVertexSchema.json");
schema = SchemaServiceResponse.fromJson(testSchema);
}
catch (Exception ex) {
- assertTrue(false);
+ fail();
return;
}
System.out.println("Validate");
- schema.getData().validate();
+ schema.getData().validate();
System.out.println("Validate done");
}
-
+
@Test(expected = SchemaProviderException.class)
public void testSchemaValidateBadType() throws SchemaProviderException {
- SchemaServiceResponse schema;
+ SchemaServiceResponse schema;
try {
String testSchema = readFile("src/test/resources/json/badTypeSchema.json");
schema = SchemaServiceResponse.fromJson(testSchema);
}
catch (Exception ex) {
- assertTrue(false);
+ fail();
return;
}
- schema.getData().validate();
+ schema.getData().validate();
}
-
+
@Test(expected = SchemaProviderException.class)
public void testSchemaValidateBadProp() throws SchemaProviderException {
- SchemaServiceResponse schema;
+ SchemaServiceResponse schema;
try {
String testSchema = readFile("src/test/resources/json/badPropSchema.json");
schema = SchemaServiceResponse.fromJson(testSchema);
}
catch (Exception ex) {
- assertTrue(false);
+ fail();
return;
}
- schema.getData().validate();
+ schema.getData().validate();
}
static String readFile(String path) throws IOException {
import java.util.List;
import java.util.Set;
import org.junit.Before;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.setup.AAIConfigTranslator;
import org.onap.aai.setup.SchemaConfigVersions;
import org.onap.aai.setup.Translator;
+@RunWith(MockitoJUnitRunner.class)
public class OxmSchemaServiceSetup {
@Mock
public Multimap<String, EdgeRule> getRules(EdgeRuleQuery q) throws EdgeRuleNotFoundException {
Multimap<String, EdgeRule> found = null;
- if (q.getVersion().isPresent()) {
- found = extractRules(q.getFilter(), q.getVersion().get());
+ Optional<SchemaVersion> versionOpt = q.getVersion();
+ if (versionOpt.isPresent()) {
+ found = extractRules(q.getFilter(), versionOpt.get());
} else {
found = extractRules(q.getFilter(), schemaVersions.getDefaultVersion());
}
*/
public EdgeRule getRule(EdgeRuleQuery q) throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
Multimap<String, EdgeRule> found = null;
- if (q.getVersion().isPresent()) {
- found = extractRules(q.getFilter(), q.getVersion().get());
+ Optional<SchemaVersion> versionOpt = q.getVersion();
+ if (versionOpt.isPresent()) {
+ found = extractRules(q.getFilter(), versionOpt.get());
} else {
found = extractRules(q.getFilter(), schemaVersions.getDefaultVersion());
}
* @return boolean
*/
public boolean hasRule(EdgeRuleQuery q) {
- if (q.getVersion().isPresent()) {
- return !extractRules(q.getFilter(), q.getVersion().get()).isEmpty();
+ Optional<SchemaVersion> versionOpt = q.getVersion();
+ if (versionOpt.isPresent()) {
+ return !extractRules(q.getFilter(), versionOpt.get()).isEmpty();
} else {
return !extractRules(q.getFilter(), schemaVersions.getDefaultVersion()).isEmpty();
}
/**
* Returns if the given node type has any cousin relationships in the current version.
- *
+ *
* @param nodeType
* @return boolean
*/
/**
* Returns if the given node type has any cousin relationships in the given version.
- *
+ *
* @param nodeType
* @return boolean
*/
/**
* Returns if the given node type has any child relationships (ie it contains another node type) in the current
* version.
- *
+ *
* @param nodeType
* @return boolean
*/
/**
* Returns if the given node type has any child relationships (ie it contains another node type) in the given
* version.
- *
+ *
* @param nodeType
* @return boolean
*/
/**
* Returns if the given node type has any parent relationships (ie it is contained by another node type) in the
* current version.
- *
+ *
* @param nodeType
* @return boolean
*/
/**
* Returns if the given node type has any parent relationships (ie it is contained by another node type) in the
* given version.
- *
+ *
* @param nodeType
* @return boolean
*/
package org.onap.aai.nodes;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.base.CaseFormat;
-
-import java.io.*;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-import java.util.*;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.annotation.PostConstruct;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.setup.Translator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* Instantiates the NodeIngestor bean.
- *
+ *
* @param translatorSet
*/
throws ParserConfigurationException, IOException, SAXException {
Set<String> types = new HashSet<>();
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
InputStream inputStream = inputStreams.get(0);
inputStream.reset();
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
return masterDocBuilder.parse(inputStream);
private Document createCombinedSchema(List<InputStream> inputStreams, SchemaVersion version)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
DocumentBuilder masterDocBuilder = docFactory.newDocumentBuilder();
package org.onap.aai.setup;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.onap.aai.restclient.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
-import java.io.*;
-import java.util.*;
-
-import javax.ws.rs.HttpMethod;
-
-import org.onap.aai.restclient.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
ResponseEntity<Resource> schemaResponse = restClient.getGetResource(content, uri, headersMap);
verifySchemaServiceResponse(schemaResponse.getStatusCode());
LOGGER.debug("SchemaResponse Status code" + schemaResponse.getStatusCode());
- inputStreams.add(schemaResponse.getBody().getInputStream());
+ Resource resultBody = schemaResponse.getBody();
+ if (resultBody != null) {
+ inputStreams.add(resultBody.getInputStream());
+ }
return inputStreams;
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Default duplicate rules for A&AI -
* node types may never have a duplicate definition
* within the same Version's file set.
- *
+ *
* Finds all duplicates and what files they're in.
*
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.onap.aai.nodes.validation.DuplicateNodeDefinitionValidationModule#findDuplicates(java.util.List)
*/
@Override
public String findDuplicates(List<String> files, SchemaVersion v) {
try {
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();