diff options
Diffstat (limited to 'common')
57 files changed, 1923 insertions, 921 deletions
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIClient.java b/common/src/main/java/org/onap/so/client/aai/AAIClient.java index be553420ac..21bbc51f89 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIClient.java @@ -27,20 +27,24 @@ import javax.ws.rs.core.UriBuilder; import org.onap.so.client.RestClient; import org.onap.so.client.graphinventory.GraphInventoryClient; +import org.onap.so.client.graphinventory.GraphInventoryVersion; import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public abstract class AAIClient extends GraphInventoryClient { +public class AAIClient extends GraphInventoryClient { private static final String AAI_ROOT = "/aai"; protected static Logger logger = LoggerFactory.getLogger(AAIClient.class); protected AAIVersion version; - public AAIClient() { + protected AAIClient() { + super(AAIProperties.class); + } + + protected AAIClient(AAIVersion version) { super(AAIProperties.class); } - @Override protected URI constructPath(GraphInventoryUri uri) { @@ -48,7 +52,7 @@ public abstract class AAIClient extends GraphInventoryClient { } @Override - protected RestClient createClient(GraphInventoryUri uri) { + public RestClient createClient(GraphInventoryUri uri) { try { return new AAIRestClient(getRestProperties(), constructPath(uri)); } catch (GraphInventoryUriComputationException | NotFoundException e) { @@ -57,11 +61,18 @@ public abstract class AAIClient extends GraphInventoryClient { } } - protected AAIVersion getVersion() { + @Override + public AAIVersion getVersion() { if (version == null) { return this.<AAIProperties>getRestProperties().getDefaultVersion(); } else { return this.version; } } + + + @Override + public String getGraphDBName() { + return "A&AI"; + } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java index 33c9769400..9c8345d4b6 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java +++ b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java @@ -20,16 +20,12 @@ package org.onap.so.client.aai; -import com.fasterxml.jackson.databind.module.SimpleModule; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperPatchProvider; -public class AAICommonObjectMapperPatchProvider extends AAICommonObjectMapperProvider { +public class AAICommonObjectMapperPatchProvider extends GraphInventoryCommonObjectMapperPatchProvider { public AAICommonObjectMapperPatchProvider() { super(); - EmptyStringToNullSerializer sp = new EmptyStringToNullSerializer(); - SimpleModule emptyStringModule = new SimpleModule(); - emptyStringModule.addSerializer(String.class, sp); - mapper.registerModule(emptyStringModule); } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java index 0e2071842f..15bc2ea8ef 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java +++ b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java @@ -20,33 +20,12 @@ package org.onap.so.client.aai; -import org.onap.so.client.policy.CommonObjectMapperProvider; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.AnnotationIntrospector; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; -import com.fasterxml.jackson.databind.type.TypeFactory; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; - -public class AAICommonObjectMapperProvider extends CommonObjectMapperProvider { +public class AAICommonObjectMapperProvider extends GraphInventoryCommonObjectMapperProvider { public AAICommonObjectMapperProvider() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - mapper.enable(MapperFeature.USE_ANNOTATIONS); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); - mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); - AnnotationIntrospector aiJackson = new JacksonAnnotationIntrospector(); - // first Jaxb, second Jackson annotations - mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(aiJaxb, aiJackson)); + super(); } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java b/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java new file mode 100644 index 0000000000..e9b58b469d --- /dev/null +++ b/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.aai; + +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.GraphInventoryQueryClient; +import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; + +public class AAIDSLQueryClient extends GraphInventoryQueryClient<AAIDSLQueryClient> { + + public AAIDSLQueryClient() { + super(new AAIClient()); + } + + public AAIDSLQueryClient(AAIVersion version) { + super(new AAIClient(version)); + } + + @Override + protected GraphInventoryUri getQueryUri() { + return AAIUriFactory.createResourceUri(AAIObjectType.DSL); + } + +} diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java index 66ff59d94f..21e36cde6c 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java @@ -26,8 +26,7 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Set; - -import javax.annotation.Priority; +import java.util.regex.Pattern; import org.onap.aai.annotations.Metadata; import org.onap.aai.domain.yang.AggregateRoute; @@ -61,6 +60,7 @@ import org.onap.aai.domain.yang.RouteTableReference; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.ServiceSubscription; import org.onap.aai.domain.yang.SpPartner; +import org.onap.aai.domain.yang.SriovPf; import org.onap.aai.domain.yang.Subnet; import org.onap.aai.domain.yang.Tenant; import org.onap.aai.domain.yang.TunnelXconnect; @@ -119,6 +119,7 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { public static final AAIObjectType MODEL_VER = new AAIObjectType(AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/models/model/{model-invariant-id}", ModelVer.class); public static final AAIObjectType TUNNEL_XCONNECT = new AAIObjectType(AAIObjectType.ALLOTTED_RESOURCE.uriTemplate(), TunnelXconnect.class); public static final AAIObjectType P_INTERFACE = new AAIObjectType(AAIObjectType.PSERVER.uriTemplate(), PInterface.class); + public static final AAIObjectType SRIOV_PF = new AAIObjectType(AAIObjectType.P_INTERFACE.uriTemplate(), SriovPf.class); public static final AAIObjectType PHYSICAL_LINK = new AAIObjectType(AAINamespaceConstants.NETWORK, PhysicalLink.class); public static final AAIObjectType INSTANCE_GROUP = new AAIObjectType(AAINamespaceConstants.NETWORK, InstanceGroup.class); public static final AAIObjectType COLLECTION = new AAIObjectType(AAINamespaceConstants.NETWORK, Collection.class); @@ -134,6 +135,7 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { public static final AAIObjectType AGGREGATE_ROUTE = new AAIObjectType(AAINamespaceConstants.NETWORK, AggregateRoute.class); public static final AAIObjectType L_INTERFACE = new AAIObjectType(AAIObjectType.VSERVER.uriTemplate(), LInterface.class); public static final AAIObjectType UNKNOWN = new AAIObjectType("", "", "unknown"); + public static final AAIObjectType DSL = new AAIObjectType("/dsl", "", "dsl"); private final String uriTemplate; private final String parentUri; @@ -217,6 +219,6 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { } protected String removeParentUri(Class<?> aaiObjectClass, String parentUri) { - return aaiObjectClass.getAnnotation(Metadata.class).uriTemplate().replace(parentUri, ""); + return aaiObjectClass.getAnnotation(Metadata.class).uriTemplate().replaceFirst(Pattern.quote(parentUri), ""); } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java b/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java index 184b4e5251..c3523e94c2 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java @@ -20,64 +20,28 @@ package org.onap.so.client.aai; -import java.util.Optional; - -import org.onap.so.client.RestClient; -import org.onap.so.client.aai.entities.CustomQuery; import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.client.graphinventory.Format; +import org.onap.so.client.graphinventory.GraphInventoryQueryClient; import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; -public class AAIQueryClient extends AAIClient { +public class AAIQueryClient extends GraphInventoryQueryClient<AAIQueryClient> { - private Optional<String> depth = Optional.empty(); - private boolean nodesOnly = false; - private Optional<AAISubgraphType> subgraph = Optional.empty(); - public AAIQueryClient() { - super(); + super(new AAIClient()); } public AAIQueryClient(AAIVersion version) { - super(); - this.version = version; - } - - public String query(Format format, CustomQuery query) { - return this.createClient(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY).queryParam("format", format.toString())) - .put(query, String.class); - } - - public AAIQueryClient depth (String depth) { - this.depth = Optional.of(depth); - return this; + super(new AAIClient(version)); } - public AAIQueryClient nodesOnly() { - this.nodesOnly = true; - return this; - } - public AAIQueryClient subgraph(AAISubgraphType type){ - - subgraph = Optional.of(type); - return this; + @Override + protected GraphInventoryUri getQueryUri() { + return AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY); } - protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) { - GraphInventoryUri clone = uri.clone(); - if (this.depth.isPresent()) { - clone.queryParam("depth", depth.get()); - } - if (this.nodesOnly) { - clone.queryParam("nodesOnly", ""); - } - if (this.subgraph.isPresent()) { - clone.queryParam("subgraph", this.subgraph.get().toString()); - } - return clone; - } @Override - protected RestClient createClient(GraphInventoryUri uri) { - return super.createClient(setupQueryParams(uri)); + protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) { + return super.setupQueryParams(uri); } + } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java index 87951d516b..ee1736feeb 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java @@ -20,321 +20,58 @@ package org.onap.so.client.aai; -import java.lang.reflect.InvocationTargetException; -import java.util.Map; import java.util.Optional; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - import org.onap.aai.domain.yang.Relationship; -import org.onap.so.client.RestClient; -import org.onap.so.client.RestProperties; import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUri; -import org.onap.so.client.graphinventory.entities.uri.Depth; +import org.onap.so.client.graphinventory.GraphInventoryResourcesClient; +import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel; +import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri; -public class AAIResourcesClient extends AAIClient { - - public AAIResourcesClient() { - super(); - } +public class AAIResourcesClient extends GraphInventoryResourcesClient<AAIResourcesClient, AAIResourceUri, AAIEdgeLabel, AAIResultWrapper, AAITransactionalClient, AAISingleTransactionClient> { - public AAIResourcesClient(AAIVersion version) { - super(); - this.version = version; - } - - /** - * creates a new object in A&AI - * - * @param obj - can be any object which will marshal into a valid A&AI payload - * @param uri - * @return - */ - public void create(AAIResourceUri uri, Object obj) { - RestClient aaiRC = this.createClient(uri); - aaiRC.put(obj); - return; - } - - /** - * creates a new object in A&AI with no payload body - * - * @param uri - * @return - */ - public void createEmpty(AAIResourceUri uri) { - RestClient aaiRC = this.createClient(uri); - aaiRC.put(""); - return; - } - - /** - * returns false if the object does not exist in A&AI - * - * @param uri - * @return - */ - public boolean exists(AAIResourceUri uri) { - AAIUri forceMinimal = this.addParams(Optional.of(Depth.ZERO), true, uri); - try { - RestClient aaiRC = this.createClient(forceMinimal); - - return aaiRC.get().getStatus() == Status.OK.getStatusCode(); - } catch (NotFoundException e) { - return false; - } - } - - /** - * Adds a relationship between two objects in A&AI - * @param uriA - * @param uriB - * @return - */ - public void connect(AAIResourceUri uriA, AAIResourceUri uriB) { - AAIResourceUri uriAClone = uriA.clone(); - RestClient aaiRC = this.createClient(uriAClone.relationshipAPI()); - aaiRC.put(this.buildRelationship(uriB)); - return; - } - - /** - * Adds a relationship between two objects in A&AI - * with a given edge label - * @param uriA - * @param uriB - * @param edge label - * @return - */ - public void connect(AAIResourceUri uriA, AAIResourceUri uriB, AAIEdgeLabel label) { - AAIResourceUri uriAClone = uriA.clone(); - RestClient aaiRC = this.createClient(uriAClone.relationshipAPI()); - aaiRC.put(this.buildRelationship(uriB, label)); - return; - } - - /** - * Removes relationship from two objects in A&AI - * - * @param uriA - * @param uriB - * @return - */ - public void disconnect(AAIResourceUri uriA, AAIResourceUri uriB) { - AAIResourceUri uriAClone = uriA.clone(); - RestClient aaiRC = this.createClient(uriAClone.relationshipAPI()); - aaiRC.delete(this.buildRelationship(uriB)); - return; - } - - /** - * Deletes object from A&AI. Automatically handles resource-version. - * - * @param uri - * @return - */ - public void delete(AAIResourceUri uri) { - AAIResourceUri clone = uri.clone(); - RestClient aaiRC = this.createClient(clone); - Map<String, Object> result = aaiRC.get(new GenericType<Map<String, Object>>(){}) - .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in A&AI")); - String resourceVersion = (String) result.get("resource-version"); - aaiRC = this.createClient(clone.resourceVersion(resourceVersion)); - aaiRC.delete(); - return; - } - - /** - * @param obj - can be any object which will marshal into a valid A&AI payload - * @param uri - * @return - */ - public void update(AAIResourceUri uri, Object obj) { - RestClient aaiRC = this.createClient(uri); - aaiRC.patch(obj); - return; - } - - /** - * Retrieves an object from A&AI and unmarshalls it into the Class specified - * @param clazz - * @param uri - * @return - */ - public <T> Optional<T> get(Class<T> clazz, AAIResourceUri uri) { - try { - return this.createClient(uri).get(clazz); - } catch (NotFoundException e) { - if (this.getRestProperties().mapNotFoundToEmpty()) { - return Optional.empty(); - } else { - throw e; - } - } - } - - /** - * Retrieves an object from A&AI and returns complete response - * @param uri - * @return - */ - public Response getFullResponse(AAIResourceUri uri) { - try { - return this.createClient(uri).get(); - } catch (NotFoundException e) { - if (this.getRestProperties().mapNotFoundToEmpty()) { - return e.getResponse(); - } else { - throw e; - } - } - } + private AAIClient aaiClient; - /** - * Retrieves an object from A&AI and automatically unmarshalls it into a Map or List - * @param resultClass - * @param uri - * @return - */ - public <T> Optional<T> get(GenericType<T> resultClass, AAIResourceUri uri) { - try { - return this.createClient(uri).get(resultClass); - } catch (NotFoundException e) { - if (this.getRestProperties().mapNotFoundToEmpty()) { - return Optional.empty(); - } else { - throw e; - } - } + public AAIResourcesClient() { + super(new AAIClient()); + aaiClient = (AAIClient) super.client; } - /** - * Retrieves an object from A&AI wrapped in a helper class which offer additional features - * - * @param uri - * @return - */ - public AAIResultWrapper get(AAIResourceUri uri) { - String json; - try { - json = this.createClient(uri).get(String.class).orElse(null); - } catch (NotFoundException e) { - if (this.getRestProperties().mapNotFoundToEmpty()) { - json = null; - } else { - throw e; - } - } - return new AAIResultWrapper(json); + public AAIResourcesClient(AAIVersion version) { + super(new AAIClient(version)); + aaiClient = (AAIClient) super.client; } - - /** - * Retrieves an object from A&AI wrapped in a helper class which offer additional features - * If the object cannot be found in A&AI the method will throw the runtime exception - * included as an argument - * @param uri - * @return - */ - public AAIResultWrapper get(AAIResourceUri uri, Class<? extends RuntimeException> c) { - String json; - try { - json = this.createClient(uri).get(String.class) - .orElseThrow(() -> createException(c, uri.build() + " not found in A&AI", Optional.empty())); - } catch (NotFoundException e) { - throw createException(c, "could not construct uri for use with A&AI", Optional.of(e)); - } + @Override + public AAIResultWrapper createWrapper(String json) { return new AAIResultWrapper(json); } - - private RuntimeException createException(Class<? extends RuntimeException> c, String message, Optional<Throwable> t) { - RuntimeException e; - try { - if (t.isPresent()) { - e = c.getConstructor(String.class, Throwable.class).newInstance(message, t.get()); - } else { - e = c.getConstructor(String.class).newInstance(message); - } - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException e1) { - throw new IllegalArgumentException("could not create instance for " + c.getName()); - } - - return e; - } - - protected Relationship buildRelationship(AAIResourceUri uri) { - return buildRelationship(uri, Optional.empty()); - } - - protected Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) { - return buildRelationship(uri, Optional.of(label)); - } - protected Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) { - final Relationship result = new Relationship(); - result.setRelatedLink(uri.build().toString()); - if (label.isPresent()) { - result.setRelationshipLabel(label.get().toString()); - } - return result; - } - - /** - * Will automatically create the object if it does not exist - * - * @param obj - Optional object which serializes to a valid A&AI payload - * @param uri - * @return - */ - public AAIResourcesClient createIfNotExists(AAIResourceUri uri, Optional<Object> obj) { - if(!this.exists(uri)){ - if (obj.isPresent()) { - this.create(uri, obj.get()); - } else { - this.createEmpty(uri); - } - - } - return this; - } - /** - * Starts a transaction which encloses multiple A&AI mutations - * - * @return - */ + @Override public AAITransactionalClient beginTransaction() { - return new AAITransactionalClient(this.getVersion()); + return new AAITransactionalClient(this, aaiClient); } - - /** - * Starts a transaction groups multiple A&AI mutations - * - * @return - */ + + @Override public AAISingleTransactionClient beginSingleTransaction() { - return new AAISingleTransactionClient(this.getVersion()); + return new AAISingleTransactionClient(this, aaiClient); } - private AAIUri addParams(Optional<Depth> depth, boolean nodesOnly, AAIUri uri) { - AAIUri clone = uri.clone(); - if (depth.isPresent()) { - clone.depth(depth.get()); - } - if (nodesOnly) { - clone.nodesOnly(nodesOnly); - } - - return clone; + @Override + protected Relationship buildRelationship(GraphInventoryResourceUri uri) { + return super.buildRelationship(uri, Optional.empty()); + } + + @Override + protected Relationship buildRelationship(GraphInventoryResourceUri uri, GraphInventoryEdgeLabel label) { + return super.buildRelationship(uri, Optional.of(label)); } + @Override - public <T extends RestProperties> T getRestProperties() { - return super.getRestProperties(); + protected Relationship buildRelationship(GraphInventoryResourceUri uri, Optional<GraphInventoryEdgeLabel> label) { + return super.buildRelationship(uri, label); } + } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java index 4f235c35f1..a2651195ee 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java @@ -28,6 +28,7 @@ import javax.ws.rs.core.Response; import org.onap.so.client.ResponseExceptionMapper; import org.onap.so.client.RestClientSSL; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; import org.onap.so.client.policy.CommonObjectMapperProvider; import org.onap.so.utils.TargetEntity; @@ -36,7 +37,7 @@ public class AAIRestClient extends RestClientSSL { private final AAIProperties aaiProperties; private static final AAICommonObjectMapperProvider standardProvider = new AAICommonObjectMapperProvider(); - private final AAIPatchConverter patchConverter = new AAIPatchConverter(); + private final GraphInventoryPatchConverter patchConverter = new GraphInventoryPatchConverter(); protected AAIRestClient(AAIProperties props, URI uri) { super(props, Optional.of(uri)); @@ -81,7 +82,7 @@ public class AAIRestClient extends RestClientSSL { return super.patch(convertToPatchFormat(obj), resultClass); } - protected AAIPatchConverter getPatchConverter() { + protected GraphInventoryPatchConverter getPatchConverter() { return this.patchConverter; } diff --git a/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java b/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java index 2ecdb7c480..ee15e10e01 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java @@ -22,178 +22,45 @@ package org.onap.so.client.aai; import java.io.IOException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.Optional; -import javax.ws.rs.NotFoundException; import javax.ws.rs.core.GenericType; -import org.onap.aai.domain.yang.Relationship; import org.onap.so.client.RestClient; import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.AAIError; -import org.onap.so.client.aai.entities.bulkprocess.Transactions; import org.onap.so.client.aai.entities.singletransaction.OperationBodyRequest; import org.onap.so.client.aai.entities.singletransaction.OperationBodyResponse; import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRequest; import org.onap.so.client.aai.entities.singletransaction.SingleTransactionResponse; import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; +import org.onap.so.client.graphinventory.GraphInventoryTransactionClient; import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; -public class AAISingleTransactionClient extends AAIClient { +public class AAISingleTransactionClient extends GraphInventoryTransactionClient<AAISingleTransactionClient, AAIResourceUri, AAIEdgeLabel> { private final SingleTransactionRequest request; - private final AAIVersion version; - private int actionCount = 0; - - private final AAIPatchConverter patchConverter = new AAIPatchConverter(); - - protected AAISingleTransactionClient(AAIVersion version) { + private AAIResourcesClient resourcesClient; + private AAIClient aaiClient; + protected AAISingleTransactionClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) { super(); - this.version = version; + this.resourcesClient = resourcesClient; + this.aaiClient = aaiClient; this.request = new SingleTransactionRequest(); } - - /** - * creates a new object in A&AI - * - * @param obj - can be any object which will marshal into a valid A&AI payload - * @param uri - * @return - */ - public AAISingleTransactionClient create(AAIResourceUri uri, Object obj) { - request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri.build().toString()).withBody(obj)); - incrementActionAmount(); - return this; - } - - /** - * creates a new object in A&AI with no payload body - * - * @param uri - * @return - */ - public AAISingleTransactionClient createEmpty(AAIResourceUri uri) { - request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri.build().toString()).withBody(new HashMap<String, String>())); - incrementActionAmount(); - return this; - } - - /** - * Adds a relationship between two objects in A&AI - * @param uriA - * @param uriB - * @return - */ - public AAISingleTransactionClient connect(AAIResourceUri uriA, AAIResourceUri uriB) { - AAIResourceUri uriAClone = uriA.clone(); - request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB))); - incrementActionAmount(); - return this; - } - - /** - * relationship between multiple objects in A&AI - connects A to all objects specified in list - * - * @param uriA - * @param uris - * @return - */ - public AAISingleTransactionClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris) { - for (AAIResourceUri uri : uris) { - this.connect(uriA, uri); - } - return this; - } - - public AAISingleTransactionClient connect(AAIResourceUri uriA, AAIResourceUri uriB, AAIEdgeLabel label) { - AAIResourceUri uriAClone = uriA.clone(); - RestClient aaiRC = this.createClient(uriAClone.relationshipAPI()); - aaiRC.put(this.buildRelationship(uriB, label)); - return this; - } - public AAISingleTransactionClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris, AAIEdgeLabel label) { - for (AAIResourceUri uri : uris) { - this.connect(uriA, uri, label); - } - return this; - } - - /** - * Removes relationship from two objects in A&AI - * - * @param uriA - * @param uriB - * @return - */ - public AAISingleTransactionClient disconnect(AAIResourceUri uriA, AAIResourceUri uriB) { - AAIResourceUri uriAClone = uriA.clone(); - request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB))); - incrementActionAmount(); - return this; - } - - /** - * Removes relationship from multiple objects - disconnects A from all objects specified in list - * @param uriA - * @param uris - * @return - */ - public AAISingleTransactionClient disconnect(AAIResourceUri uriA, List<AAIResourceUri> uris) { - for (AAIResourceUri uri : uris) { - this.disconnect(uriA, uri); - } - return this; - } - /** - * Deletes object from A&AI. Automatically handles resource-version. - * - * @param uri - * @return - */ - public AAISingleTransactionClient delete(AAIResourceUri uri) { - AAIResourcesClient client = new AAIResourcesClient(); - AAIResourceUri clone = uri.clone(); - Map<String, Object> result = client.get(new GenericType<Map<String, Object>>(){}, clone) - .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in A&AI")); - String resourceVersion = (String) result.get("resource-version"); - request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(clone.resourceVersion(resourceVersion).build().toString()).withBody("")); - incrementActionAmount(); - return this; - } - - /** - * @param obj - can be any object which will marshal into a valid A&AI payload - * @param uri - * @return - */ - public AAISingleTransactionClient update(AAIResourceUri uri, Object obj) { - - final String payload = getPatchConverter().convertPatchFormat(obj); - request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri.build().toString()).withBody(payload)); - incrementActionAmount(); - return this; - } - - private void incrementActionAmount() { - actionCount++; - } - /** - * Executes all created transactions in A&AI - * @throws BulkProcessFailed + /* (non-Javadoc) + * @see org.onap.so.client.aai.GraphInventoryTransactionClient#execute() */ + @Override public void execute() throws BulkProcessFailed { - RestClient client = this.createClient(AAIUriFactory.createResourceUri(AAIObjectType.SINGLE_TRANSACTION)); + RestClient client = aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.SINGLE_TRANSACTION)); try { SingleTransactionResponse response = client.post(this.request, SingleTransactionResponse.class); if (response != null) { @@ -235,33 +102,44 @@ public class AAISingleTransactionClient extends AAIClient { return Optional.empty(); } } + - private Relationship buildRelationship(AAIResourceUri uri) { - return buildRelationship(uri, Optional.empty()); + protected SingleTransactionRequest getRequest() { + return this.request; } - - private Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) { - return buildRelationship(uri, Optional.of(label)); + + @Override + public void put(String uri, Object body) { + request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri).withBody(body)); } - private Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) { - final Relationship result = new Relationship(); - result.setRelatedLink(uri.build().toString()); - if (label.isPresent()) { - result.setRelationshipLabel(label.toString()); - } - return result; + + @Override + public void delete(String uri, Object body) { + request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(body)); } @Override - protected AAIVersion getVersion() { - return this.version; + public void patch(String uri, Object body) { + request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri).withBody(body)); + } + + @Override + protected <T> Optional<T> get(GenericType<T> genericType, AAIResourceUri clone) { + return resourcesClient.get(genericType, clone); } - protected SingleTransactionRequest getRequest() { - return this.request; + @Override + protected boolean exists(AAIResourceUri uri) { + return resourcesClient.exists(uri); + } + + @Override + protected String getGraphDBName() { + return aaiClient.getGraphDBName(); } - protected AAIPatchConverter getPatchConverter() { + @Override + protected GraphInventoryPatchConverter getPatchConverter() { return this.patchConverter; } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java b/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java index 118a3edf1c..474ae89ff9 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java @@ -20,17 +20,13 @@ package org.onap.so.client.aai; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; - import java.io.IOException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; -import javax.ws.rs.NotFoundException; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; @@ -42,8 +38,9 @@ import org.onap.so.client.aai.entities.bulkprocess.OperationBody; import org.onap.so.client.aai.entities.bulkprocess.Transaction; import org.onap.so.client.aai.entities.bulkprocess.Transactions; import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; +import org.onap.so.client.graphinventory.GraphInventoryTransactionClient; import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed; import org.onap.so.jsonpath.JsonPathUtil; @@ -51,18 +48,17 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; -public class AAITransactionalClient extends AAIClient { +public class AAITransactionalClient extends GraphInventoryTransactionClient<AAITransactionalClient, AAIResourceUri, AAIEdgeLabel> { private final Transactions transactions; private Transaction currentTransaction; - private final AAIVersion version; - private int actionCount = 0; - - private final AAIPatchConverter patchConverter = new AAIPatchConverter(); - protected AAITransactionalClient(AAIVersion version) { + private AAIResourcesClient resourcesClient; + private AAIClient aaiClient; + protected AAITransactionalClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) { super(); - this.version = version; + this.resourcesClient = resourcesClient; + this.aaiClient = aaiClient; this.transactions = new Transactions(); startTransaction(); } @@ -73,146 +69,20 @@ public class AAITransactionalClient extends AAIClient { currentTransaction = transaction; } - /** - * adds an additional transaction and closes the previous transaction - * - * @return AAITransactionalClient + /* (non-Javadoc) + * @see org.onap.so.client.aai.GraphInventoryTransactionalClient#beginNewTransaction() */ public AAITransactionalClient beginNewTransaction() { startTransaction(); return this; } - /** - * creates a new object in A&AI - * - * @param obj - can be any object which will marshal into a valid A&AI payload - * @param uri - * @return - */ - public AAITransactionalClient create(AAIResourceUri uri, Object obj) { - currentTransaction.getPut().add(new OperationBody().withUri(uri.build().toString()).withBody(obj)); - incrementActionAmount(); - return this; - } - - /** - * creates a new object in A&AI with no payload body - * - * @param uri - * @return - */ - public AAITransactionalClient createEmpty(AAIResourceUri uri) { - currentTransaction.getPut().add(new OperationBody().withUri(uri.build().toString()).withBody(new HashMap<String, String>())); - incrementActionAmount(); - return this; - } - - /** - * Adds a relationship between two objects in A&AI - * @param uriA - * @param uriB - * @return - */ - public AAITransactionalClient connect(AAIResourceUri uriA, AAIResourceUri uriB) { - AAIResourceUri uriAClone = uriA.clone(); - currentTransaction.getPut().add(new OperationBody().withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB))); - incrementActionAmount(); - return this; - } - - /** - * relationship between multiple objects in A&AI - connects A to all objects specified in list - * - * @param uriA - * @param uris - * @return - */ - public AAITransactionalClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris) { - for (AAIResourceUri uri : uris) { - this.connect(uriA, uri); - } - return this; - } - - public AAITransactionalClient connect(AAIResourceUri uriA, AAIResourceUri uriB, AAIEdgeLabel label) { - AAIResourceUri uriAClone = uriA.clone(); - RestClient aaiRC = this.createClient(uriAClone.relationshipAPI()); - aaiRC.put(this.buildRelationship(uriB, label)); - return this; - } - - public AAITransactionalClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris, AAIEdgeLabel label) { - for (AAIResourceUri uri : uris) { - this.connect(uriA, uri, label); - } - return this; - } - - /** - * Removes relationship from two objects in A&AI - * - * @param uriA - * @param uriB - * @return - */ - public AAITransactionalClient disconnect(AAIResourceUri uriA, AAIResourceUri uriB) { - AAIResourceUri uriAClone = uriA.clone(); - currentTransaction.getDelete().add(new OperationBody().withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB))); - incrementActionAmount(); - return this; - } - - /** - * Removes relationship from multiple objects - disconnects A from all objects specified in list - * @param uriA - * @param uris - * @return - */ - public AAITransactionalClient disconnect(AAIResourceUri uriA, List<AAIResourceUri> uris) { - for (AAIResourceUri uri : uris) { - this.disconnect(uriA, uri); - } - return this; - } - /** - * Deletes object from A&AI. Automatically handles resource-version. - * - * @param uri - * @return - */ - public AAITransactionalClient delete(AAIResourceUri uri) { - AAIResourcesClient client = new AAIResourcesClient(); - AAIResourceUri clone = uri.clone(); - Map<String, Object> result = client.get(new GenericType<Map<String, Object>>(){}, clone) - .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in A&AI")); - String resourceVersion = (String) result.get("resource-version"); - currentTransaction.getDelete().add(new OperationBody().withUri(clone.resourceVersion(resourceVersion).build().toString()).withBody("")); - incrementActionAmount(); - return this; - } - - /** - * @param obj - can be any object which will marshal into a valid A&AI payload - * @param uri - * @return - */ - public AAITransactionalClient update(AAIResourceUri uri, Object obj) { - final String payload = getPatchConverter().convertPatchFormat(obj); - currentTransaction.getPatch().add(new OperationBody().withUri(uri.build().toString()).withBody(payload)); - incrementActionAmount(); - return this; - } - - private void incrementActionAmount() { - actionCount++; - } - /** - * Executes all created transactions in A&AI - * @throws BulkProcessFailed + /* (non-Javadoc) + * @see org.onap.so.client.aai.GraphInventoryTransactionalClient#execute() */ + @Override public void execute() throws BulkProcessFailed { - RestClient client = this.createClient(AAIUriFactory.createResourceUri(AAIObjectType.BULK_PROCESS)); + RestClient client = aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.BULK_PROCESS)); try { Response response = client.put(this.transactions); if (response.hasEntity()) { @@ -283,17 +153,44 @@ public class AAITransactionalClient extends AAIClient { } return result; } + + protected Transactions getTransactions() { + return this.transactions; + } + + @Override + public void put(String uri, Object body) { + currentTransaction.getPut().add(new OperationBody().withUri(uri).withBody(body)); + } + + @Override + public void delete(String uri, Object body) { + currentTransaction.getDelete().add(new OperationBody().withUri(uri).withBody(body)); + + } + + @Override + public void patch(String uri, Object body) { + currentTransaction.getPatch().add(new OperationBody().withUri(uri).withBody(body)); + } @Override - protected AAIVersion getVersion() { - return this.version; + protected <T> Optional<T> get(GenericType<T> genericType, AAIResourceUri clone) { + return resourcesClient.get(genericType, clone); } - protected Transactions getTransactions() { - return this.transactions; + @Override + protected boolean exists(AAIResourceUri uri) { + return resourcesClient.exists(uri); + } + + @Override + protected String getGraphDBName() { + return aaiClient.getGraphDBName(); } - protected AAIPatchConverter getPatchConverter() { + @Override + protected GraphInventoryPatchConverter getPatchConverter() { return this.patchConverter; } } diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java index 77ea9bcdfe..9b3f98baa4 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java @@ -20,96 +20,22 @@ package org.onap.so.client.aai.entities; -import java.io.IOException; import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import org.onap.so.client.aai.AAICommonObjectMapperProvider; -import org.onap.so.jsonpath.JsonPathUtil; +import org.onap.so.client.graphinventory.entities.GraphInventoryResultWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class AAIResultWrapper implements Serializable { +public class AAIResultWrapper extends GraphInventoryResultWrapper implements Serializable { private static final long serialVersionUID = 5895841925807816737L; - private final String jsonBody; - private final ObjectMapper mapper; - private final transient Logger logger = LoggerFactory.getLogger(AAIResultWrapper.class); + private final static transient Logger logger = LoggerFactory.getLogger(AAIResultWrapper.class); public AAIResultWrapper(String json) { - this.jsonBody = json; - this.mapper = new AAICommonObjectMapperProvider().getMapper(); + super(json, logger); } public AAIResultWrapper(Object aaiObject) { - this.mapper = new AAICommonObjectMapperProvider().getMapper(); - this.jsonBody = mapObjectToString(aaiObject); - } - - protected String mapObjectToString(Object aaiObject) { - try { - return mapper.writeValueAsString(aaiObject); - } catch (JsonProcessingException e) { - logger.warn("could not parse object into json - defaulting to {}"); - return "{}"; - } + super(aaiObject, logger); } - public Optional<Relationships> getRelationships() { - final String path = "$.relationship-list"; - if (isEmpty()) { - return Optional.empty(); - } - Optional<String> result = JsonPathUtil.getInstance().locateResult(jsonBody, path); - if (result.isPresent()) { - return Optional.of(new Relationships(result.get())); - } else { - return Optional.empty(); - } - } - - public String getJson() { - if(jsonBody == null) { - return "{}"; - } else { - return jsonBody; - } - } - - public Map<String, Object> asMap() { - if (isEmpty()) { - return new HashMap<>(); - } - try { - return mapper.readValue(this.jsonBody, new TypeReference<Map<String, Object>>(){}); - } catch (IOException e) { - return new HashMap<>(); - } - } - - public <T> Optional<T> asBean(Class<T> clazz) { - if (isEmpty()) { - return Optional.empty(); - } - try { - return Optional.of(mapper.readValue(this.jsonBody, clazz)); - } catch (IOException e) { - return Optional.empty(); - } - } - - public boolean isEmpty() { - return jsonBody == null; - } - @Override - public String toString() { - return this.getJson(); - } - } diff --git a/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java b/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java new file mode 100644 index 0000000000..b056fd0e40 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.aai.entities; + +@FunctionalInterface +public interface QueryStep { + + + public String build(); +} diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java index 76413c2594..7cb37d9c3a 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java @@ -59,6 +59,10 @@ public class AAISimpleUri extends SimpleUri implements AAIResourceUri { super(parentUri, childType, childValues); } + protected AAISimpleUri(AAIResourceUri parentUri, AAIObjectPlurals childType) { + super(parentUri, childType); + } + @Override public AAISimpleUri relationshipAPI() { return (AAISimpleUri) super.relationshipAPI(); diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java index 77c61089a4..ac0aba3c36 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java @@ -85,6 +85,11 @@ public class AAIUriFactory { return new AAISimpleUri(parentUri, childType, childValues); } + public static AAIResourceUri createResourceFromParentURI(AAIResourceUri parentUri, AAIObjectPlurals childType) { + + return new AAISimpleUri(parentUri, childType); + } + /** * Creates a uri for a plural type e.g. /cloud-infrastructure/pservers * diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java index dde0b31c90..dea00dd08f 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java +++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.so.client.dmaap; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.Base64; import java.util.Map; import java.util.Optional; @@ -31,13 +32,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; - +import org.onap.so.utils.CryptoUtils; public abstract class DmaapClient { - + protected static Logger logger = LoggerFactory.getLogger(DmaapClient.class); protected final Map<String, String> msoProperties; protected final Properties properties; + public DmaapClient(String filepath) throws IOException { Resource resource = new ClassPathResource(filepath); DmaapProperties dmaapProperties = DmaapPropertiesLoader.getInstance().getNewImpl(); @@ -48,27 +50,34 @@ public abstract class DmaapClient { this.msoProperties = dmaapProperties.getProperties(); this.properties = new Properties(); this.properties.load(resource.getInputStream()); - this.properties.put("password", this.deobfuscatePassword(this.getPassword())); - this.properties.put("username", this.getUserName()); + try { + this.properties.put("auth", CryptoUtils.decrypt(this.getAuth(), this.getKey()).getBytes()); + } catch (GeneralSecurityException e) { + logger.error(e.getMessage(), e); + } + this.properties.put("key", this.getKey()); this.properties.put("topic", this.getTopic()); Optional<String> host = this.getHost(); if (host.isPresent()) { this.properties.put("host", host.get()); } } - protected String deobfuscatePassword(String password) { - + + protected String deobfuscatePassword(String decrypted_key) { + try { - return new String(Base64.getDecoder().decode(password.getBytes())); - } catch(IllegalArgumentException iae) { - logger.error("llegal Arguments",iae); - return password; + return new String(Base64.getDecoder().decode(decrypted_key.getBytes())); + } catch (IllegalArgumentException iae) { + logger.error("llegal Arguments", iae); + return decrypted_key; } } - - - public abstract String getUserName(); - public abstract String getPassword(); + + public abstract String getKey(); + + public abstract String getAuth(); + public abstract String getTopic(); + public abstract Optional<String> getHost(); } diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java b/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java index 0438ff237a..9fd8c05cb5 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java +++ b/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java @@ -17,34 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.so.client.dmaap.rest; import java.net.URL; -import java.util.Base64; import java.util.Map; import org.onap.so.client.RestClient; +import org.onap.so.utils.CryptoUtils; import org.onap.so.utils.TargetEntity; public class DMaaPRestClient extends RestClient { - private final String username; - private final String password; - public DMaaPRestClient(URL url, String contentType, String username, String password) { + private final String auth; + private final String key; + + public DMaaPRestClient(URL url, String contentType, String auth, String key) { super(url, contentType); - this.username = username; - this.password = password; + this.auth = auth; + this.key = key; } - @Override - public TargetEntity getTargetEntity(){ - return TargetEntity.DMAAP; - } + @Override + public TargetEntity getTargetEntity() { + return TargetEntity.DMAAP; + } @Override protected void initializeHeaderMap(Map<String, String> headerMap) { - headerMap.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes())); + if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) { + addBasicAuthHeader(auth, key); + } } } diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java b/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java index f43c65808a..18849217f8 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java +++ b/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java @@ -24,8 +24,8 @@ import java.util.Properties; public class PropertiesBean { - private String username; - private String password; + private String auth; + private String key; private String environment; private String partition; private String contentType; @@ -35,8 +35,8 @@ public class PropertiesBean { public PropertiesBean(Properties properties) { - this.withUsername(properties.getProperty("username")) - .withPassword(properties.getProperty("password")) + this.withAuth(properties.getProperty("auth")) + .withKey(properties.getProperty("key")) .withTopic(properties.getProperty("topic")) .withEnvironment(properties.getProperty("environment")) .withHost(properties.getProperty("host")) @@ -44,24 +44,24 @@ public class PropertiesBean { .withPartition(properties.getProperty("partition")) .withContentType(properties.getProperty("contentType", "application/json")); } - public String getUsername() { - return username; + public String getAuth() { + return auth; } - public void setUsername(String username) { - this.username = username; + public void setAuth(String auth) { + this.auth = auth; } - public PropertiesBean withUsername(String username) { - this.username = username; + public PropertiesBean withAuth(String auth) { + this.auth = auth; return this; } - public String getPassword() { - return password; + public String getKey() { + return key; } - public void setPassword(String password) { - this.password = password; + public void setKey(String key) { + this.key = key; } - public PropertiesBean withPassword(String password) { - this.password = password; + public PropertiesBean withKey(String key) { + this.key = key; return this; } public String getEnvironment() { diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java b/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java index 39af15635a..bee5a0c2ca 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java +++ b/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java @@ -37,7 +37,7 @@ public class RestConsumer implements Consumer { private final RestClient client; public RestConsumer(Properties properties) { PropertiesBean bean = new PropertiesBean(properties); - client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getUsername(), bean.getPassword()); + client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getAuth(), bean.getKey()); } private URL createURL(PropertiesBean properties) { diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java b/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java index 090e50543b..af660c2aa4 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java +++ b/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java @@ -35,7 +35,7 @@ public class RestPublisher implements Publisher { public RestPublisher(Properties properties) { PropertiesBean bean = new PropertiesBean(properties); - client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getUsername(), bean.getPassword()); + client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getAuth(), bean.getKey()); } private URL createURL(PropertiesBean properties) { diff --git a/common/src/main/java/org/onap/so/client/aai/EmptyStringToNullSerializer.java b/common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java index 1120ebe0b9..e21386f809 100644 --- a/common/src/main/java/org/onap/so/client/aai/EmptyStringToNullSerializer.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.client.aai; +package org.onap.so.client.graphinventory; import java.io.IOException; diff --git a/common/src/main/java/org/onap/so/client/graphinventory/Format.java b/common/src/main/java/org/onap/so/client/graphinventory/Format.java index 5cbf1320c1..0a3e0b498c 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/Format.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/Format.java @@ -23,6 +23,7 @@ package org.onap.so.client.graphinventory; public enum Format { RESOURCE("resource"), + RESOURCE_AND_URL("resource_and_url"), SIMPLE("simple"), RAW("raw"), CONSOLE("console"), diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java index 0d10c21886..30e91dce03 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java @@ -37,12 +37,16 @@ public abstract class GraphInventoryClient { } protected abstract URI constructPath(GraphInventoryUri uri); - protected abstract RestClient createClient(GraphInventoryUri uri); + public abstract RestClient createClient(GraphInventoryUri uri); - protected <T extends RestProperties> T getRestProperties() { + public <T extends RestProperties> T getRestProperties() { if (props == null) { throw new IllegalStateException("No RestProperty implementation found on classpath"); } return (T)props; } + + public abstract GraphInventoryVersion getVersion(); + + public abstract String getGraphDBName(); } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java new file mode 100644 index 0000000000..47c9e77b84 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory; + +import com.fasterxml.jackson.databind.module.SimpleModule; + +public class GraphInventoryCommonObjectMapperPatchProvider extends GraphInventoryCommonObjectMapperProvider { + + + public GraphInventoryCommonObjectMapperPatchProvider() { + super(); + EmptyStringToNullSerializer sp = new EmptyStringToNullSerializer(); + SimpleModule emptyStringModule = new SimpleModule(); + emptyStringModule.addSerializer(String.class, sp); + mapper.registerModule(emptyStringModule); + } +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java new file mode 100644 index 0000000000..f9857424a2 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory; + +import org.onap.so.client.policy.CommonObjectMapperProvider; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.AnnotationIntrospector; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; +import com.fasterxml.jackson.databind.type.TypeFactory; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; + +public class GraphInventoryCommonObjectMapperProvider extends CommonObjectMapperProvider { + + public GraphInventoryCommonObjectMapperProvider() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + mapper.enable(MapperFeature.USE_ANNOTATIONS); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); + AnnotationIntrospector aiJackson = new JacksonAnnotationIntrospector(); + // first Jaxb, second Jackson annotations + mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(aiJaxb, aiJackson)); + } + +} diff --git a/common/src/main/java/org/onap/so/client/aai/AAIPatchConverter.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java index 6ccb592409..00e597b189 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIPatchConverter.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java @@ -18,29 +18,31 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.client.aai; +package org.onap.so.client.graphinventory; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +import org.onap.so.client.aai.AAICommonObjectMapperPatchProvider; +import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException; import org.onap.so.jsonpath.JsonPathUtil; import com.fasterxml.jackson.core.JsonProcessingException; -public class AAIPatchConverter { +public class GraphInventoryPatchConverter { private static final AAICommonObjectMapperProvider standardProvider = new AAICommonObjectMapperProvider(); private static final AAICommonObjectMapperPatchProvider patchProvider = new AAICommonObjectMapperPatchProvider(); private static final Pattern LOCATE_COMPLEX_OBJECT = Pattern.compile("^((?!relationship-list).)+?\\['[^\\[\\]]+?'\\]$"); - protected String convertPatchFormat(Object obj) { + public String convertPatchFormat(Object obj) { return validatePatchObject(marshallObjectToPatchFormat(obj)); } - protected String validatePatchObject(String payload) { + public String validatePatchObject(String payload) { if (hasComplexObject(payload)) { throw new GraphInventoryPatchDepthExceededException(payload); } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java new file mode 100644 index 0000000000..aa4842fe2a --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory; + +import java.util.Optional; + +import org.onap.so.client.aai.entities.CustomQuery; +import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; + +public abstract class GraphInventoryQueryClient<S> { + + private Optional<String> depth = Optional.empty(); + private boolean nodesOnly = false; + private Optional<GraphInventorySubgraphType> subgraph = Optional.empty(); + private GraphInventoryClient client; + + public GraphInventoryQueryClient(GraphInventoryClient client) { + this.client = client; + } + + protected abstract GraphInventoryUri getQueryUri(); + + public String query(Format format, CustomQuery query) { + return client.createClient(setupQueryParams(getQueryUri().queryParam("format", format.toString()))).put(query, String.class); + } + + public S depth (String depth) { + this.depth = Optional.of(depth); + return (S) this; + } + public S nodesOnly() { + this.nodesOnly = true; + return (S) this; + } + public S subgraph(GraphInventorySubgraphType type){ + + subgraph = Optional.of(type); + + return (S) this; + } + + protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) { + GraphInventoryUri clone = uri.clone(); + if (this.depth.isPresent()) { + clone.queryParam("depth", depth.get()); + } + if (this.nodesOnly) { + clone.queryParam("nodesOnly", ""); + } + if (this.subgraph.isPresent()) { + clone.queryParam("subgraph", this.subgraph.get().toString()); + } + return clone; + } +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java new file mode 100644 index 0000000000..39d2d01da9 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java @@ -0,0 +1,306 @@ +package org.onap.so.client.graphinventory; + +import java.lang.reflect.InvocationTargetException; +import java.util.Map; +import java.util.Optional; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.onap.aai.domain.yang.Relationship; +import org.onap.so.client.RestClient; +import org.onap.so.client.RestProperties; +import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel; +import org.onap.so.client.graphinventory.entities.GraphInventoryResultWrapper; +import org.onap.so.client.graphinventory.entities.uri.Depth; +import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri; +import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; + +public abstract class GraphInventoryResourcesClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel, Wrapper extends GraphInventoryResultWrapper, TransactionalClient, SingleTransactionClient> { + + protected GraphInventoryClient client; + + protected GraphInventoryResourcesClient(GraphInventoryClient client) { + this.client = client; + } + /** + * creates a new object in GraphInventory + * + * @param obj - can be any object which will marshal into a valid GraphInventory payload + * @param uri + * @return + */ + public void create(Uri uri, Object obj) { + RestClient giRC = client.createClient(uri); + giRC.put(obj); + } + + /** + * creates a new object in GraphInventory with no payload body + * + * @param uri + * @return + */ + public void createEmpty(Uri uri) { + RestClient giRC = client.createClient(uri); + giRC.put(""); + } + + /** + * returns false if the object does not exist in GraphInventory + * + * @param uri + * @return + */ + public boolean exists(Uri uri) { + GraphInventoryUri forceMinimal = this.addParams(Optional.of(Depth.ZERO), true, uri); + try { + RestClient giRC = client.createClient(forceMinimal); + + return giRC.get().getStatus() == Status.OK.getStatusCode(); + } catch (NotFoundException e) { + return false; + } + } + + /** + * Adds a relationship between two objects in GraphInventory + * @param uriA + * @param uriB + * @return + */ + public void connect(Uri uriA, Uri uriB) { + GraphInventoryResourceUri uriAClone = uriA.clone(); + RestClient giRC = client.createClient(uriAClone.relationshipAPI()); + giRC.put(this.buildRelationship(uriB)); + } + + /** + * Adds a relationship between two objects in GraphInventory + * with a given edge label + * @param uriA + * @param uriB + * @param edge label + * @return + */ + public void connect(Uri uriA, Uri uriB, EdgeLabel label) { + GraphInventoryResourceUri uriAClone = uriA.clone(); + RestClient giRC = client.createClient(uriAClone.relationshipAPI()); + giRC.put(this.buildRelationship(uriB, label)); + } + + /** + * Removes relationship from two objects in GraphInventory + * + * @param uriA + * @param uriB + * @return + */ + public void disconnect(Uri uriA, Uri uriB) { + GraphInventoryResourceUri uriAClone = uriA.clone(); + RestClient giRC = client.createClient(uriAClone.relationshipAPI()); + giRC.delete(this.buildRelationship(uriB)); + } + + /** + * Deletes object from GraphInventory. Automatically handles resource-version. + * + * @param uri + * @return + */ + public void delete(Uri uri) { + GraphInventoryResourceUri clone = uri.clone(); + RestClient giRC = client.createClient(clone); + Map<String, Object> result = giRC.get(new GenericType<Map<String, Object>>(){}) + .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in " + client.getGraphDBName())); + String resourceVersion = (String) result.get("resource-version"); + giRC = client.createClient(clone.resourceVersion(resourceVersion)); + giRC.delete(); + } + + /** + * @param obj - can be any object which will marshal into a valid GraphInventory payload + * @param uri + * @return + */ + public void update(Uri uri, Object obj) { + RestClient giRC = client.createClient(uri); + giRC.patch(obj); + } + + /** + * Retrieves an object from GraphInventory and unmarshalls it into the Class specified + * @param clazz + * @param uri + * @return + */ + public <T> Optional<T> get(Class<T> clazz, Uri uri) { + try { + return client.createClient(uri).get(clazz); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + return Optional.empty(); + } else { + throw e; + } + } + } + + /** + * Retrieves an object from GraphInventory and returns complete response + * @param uri + * @return + */ + public Response getFullResponse(Uri uri) { + try { + return client.createClient(uri).get(); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + return e.getResponse(); + } else { + throw e; + } + } + } + + /** + * Retrieves an object from GraphInventory and automatically unmarshalls it into a Map or List + * @param resultClass + * @param uri + * @return + */ + public <T> Optional<T> get(GenericType<T> resultClass, Uri uri) { + try { + return client.createClient(uri).get(resultClass); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + return Optional.empty(); + } else { + throw e; + } + } + } + /** + * Retrieves an object from GraphInventory wrapped in a helper class which offer additional features + * + * @param uri + * @return + */ + public Wrapper get(Uri uri) { + String json; + try { + json = client.createClient(uri).get(String.class).orElse(null); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + json = null; + } else { + throw e; + } + } + return this.createWrapper(json); + } + + /** + * Retrieves an object from GraphInventory wrapped in a helper class which offer additional features + * If the object cannot be found in GraphInventory the method will throw the runtime exception + * included as an argument + * @param uri + * @return + */ + public Wrapper get(Uri uri, Class<? extends RuntimeException> c) { + String json; + try { + json = client.createClient(uri).get(String.class) + .orElseThrow(() -> createException(c, uri.build() + " not found in " + client.getGraphDBName(), Optional.empty())); + } catch (NotFoundException e) { + throw createException(c, "could not construct uri for use with " + client.getGraphDBName(), Optional.of(e)); + } + + return this.createWrapper(json); + } + + private RuntimeException createException(Class<? extends RuntimeException> c, String message, Optional<Throwable> t) { + RuntimeException e; + try { + if (t.isPresent()) { + e = c.getConstructor(String.class, Throwable.class).newInstance(message, t.get()); + } else { + e = c.getConstructor(String.class).newInstance(message); + } + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException | SecurityException e1) { + throw new IllegalArgumentException("could not create instance for " + c.getName()); + } + + return e; + } + + /** + * Will automatically create the object if it does not exist + * + * @param obj - Optional object which serializes to a valid GraphInventory payload + * @param uri + * @return + */ + public Self createIfNotExists(Uri uri, Optional<Object> obj) { + if(!this.exists(uri)){ + if (obj.isPresent()) { + this.create(uri, obj.get()); + } else { + this.createEmpty(uri); + } + + } + return (Self)this; + } + protected Relationship buildRelationship(GraphInventoryResourceUri uri) { + return buildRelationship(uri, Optional.empty()); + } + + protected Relationship buildRelationship(GraphInventoryResourceUri uri, GraphInventoryEdgeLabel label) { + return buildRelationship(uri, Optional.of(label)); + } + protected Relationship buildRelationship(GraphInventoryResourceUri uri, Optional<GraphInventoryEdgeLabel> label) { + final Relationship result = new Relationship(); + result.setRelatedLink(uri.build().toString()); + if (label.isPresent()) { + result.setRelationshipLabel(label.get().toString()); + } + return result; + } + + public abstract Wrapper createWrapper(String json); + + /** + * Starts a transaction which encloses multiple GraphInventory mutations + * + * @return + */ + public abstract TransactionalClient beginTransaction(); + + /** + * Starts a transaction groups multiple GraphInventory mutations + * + * @return + */ + public abstract SingleTransactionClient beginSingleTransaction(); + + private GraphInventoryUri addParams(Optional<Depth> depth, boolean nodesOnly, GraphInventoryUri uri) { + GraphInventoryUri clone = uri.clone(); + if (depth.isPresent()) { + clone.depth(depth.get()); + } + if (nodesOnly) { + clone.nodesOnly(nodesOnly); + } + + return clone; + } + + public <T extends RestProperties> T getRestProperties() { + return client.getRestProperties(); + } + +}
\ No newline at end of file diff --git a/common/src/main/java/org/onap/so/client/aai/AAISubgraphType.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java index e9beb143fd..4bbbe202cc 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAISubgraphType.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java @@ -18,16 +18,16 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.client.aai; +package org.onap.so.client.graphinventory; -public enum AAISubgraphType { +public enum GraphInventorySubgraphType { STAR("star"), PRUNE("prune"); private final String name; - private AAISubgraphType(String name) { + private GraphInventorySubgraphType(String name) { this.name = name; } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java new file mode 100644 index 0000000000..8d1a945c1b --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.GenericType; + +import org.onap.aai.domain.yang.Relationship; +import org.onap.so.client.aai.AAIVersion; +import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRequest; +import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel; +import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri; +import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class GraphInventoryTransactionClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel> implements TransactionBuilder { + + protected static Logger logger = LoggerFactory.getLogger(GraphInventoryTransactionClient.class); + + protected int actionCount = 0; + + protected final GraphInventoryPatchConverter patchConverter = new GraphInventoryPatchConverter(); + + protected GraphInventoryTransactionClient() { + } + + /** + * creates a new object in A&AI + * + * @param obj - can be any object which will marshal into a valid A&AI payload + * @param uri + * @return + */ + public Self create(Uri uri, Object obj) { + this.put(uri.build().toString(), obj); + incrementActionAmount(); + return (Self)this; + } + + /** + * creates a new object in A&AI with no payload body + * + * @param uri + * @return + */ + public Self createEmpty(Uri uri) { + this.put(uri.build().toString(), new HashMap<String, String>()); + incrementActionAmount(); + return (Self)this; + } + + /** + * Will automatically create the object if it does not exist + * + * @param obj - Optional object which serializes to a valid GraphInventory payload + * @param uri + * @return + */ + public Self createIfNotExists(Uri uri, Optional<Object> obj) { + if(!this.exists(uri)){ + if (obj.isPresent()) { + this.create(uri, obj.get()); + incrementActionAmount(); + } else { + this.createEmpty(uri); + incrementActionAmount(); + } + + } + return (Self)this; + } + + /** + * Adds a relationship between two objects in A&AI + * @param uriA + * @param uriB + * @return + */ + public Self connect(Uri uriA, Uri uriB) { + GraphInventoryResourceUri uriAClone = uriA.clone(); + this.put(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB)); + incrementActionAmount(); + return (Self)this; + } + + /** + * relationship between multiple objects in A&AI - connects A to all objects specified in list + * + * @param uriA + * @param uris + * @return + */ + public Self connect(Uri uriA, List<Uri> uris) { + for (Uri uri : uris) { + this.connect(uriA, uri); + } + return (Self)this; + } + + /** + * relationship between multiple objects in A&AI - connects A to all objects specified in list + * + * @param uriA + * @param uris + * @return + */ + public Self connect(Uri uriA, Uri uriB, EdgeLabel label) { + GraphInventoryResourceUri uriAClone = uriA.clone(); + this.put(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB, label)); + return (Self)this; + } + + /** + * relationship between multiple objects in A&AI - connects A to all objects specified in list + * + * @param uriA + * @param uris + * @return + */ + public Self connect(Uri uriA, List<Uri> uris, EdgeLabel label) { + for (Uri uri : uris) { + this.connect(uriA, uri, label); + } + return (Self)this; + } + + /** + * Removes relationship from two objects in A&AI + * + * @param uriA + * @param uriB + * @return + */ + public Self disconnect(Uri uriA, Uri uriB) { + GraphInventoryResourceUri uriAClone = uriA.clone(); + this.delete(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB)); + incrementActionAmount(); + return (Self)this; + } + + /** + * Removes relationship from multiple objects - disconnects A from all objects specified in list + * @param uriA + * @param uris + * @return + */ + public Self disconnect(Uri uriA, List<Uri> uris) { + for (Uri uri : uris) { + this.disconnect(uriA, uri); + } + return (Self)this; + } + /** + * Deletes object from A&AI. Automatically handles resource-version. + * + * @param uri + * @return + */ + public Self delete(Uri uri) { + Map<String, Object> result = this.get(new GenericType<Map<String, Object>>(){}, (Uri)uri.clone()) + .orElseThrow(() -> new NotFoundException(uri.build() + " does not exist in " + this.getGraphDBName())); + String resourceVersion = (String) result.get("resource-version"); + this.delete(uri.resourceVersion(resourceVersion).build().toString(), ""); + incrementActionAmount(); + return (Self)this; + } + + protected abstract <T> Optional<T> get(GenericType<T> genericType, Uri clone); + + protected abstract boolean exists(Uri uri); + + protected abstract String getGraphDBName(); + + /** + * @param obj - can be any object which will marshal into a valid A&AI payload + * @param uri + * @return + */ + public Self update(Uri uri, Object obj) { + + final String payload = getPatchConverter().convertPatchFormat(obj); + this.patch(uri.build().toString(), payload); + incrementActionAmount(); + return (Self)this; + } + + private void incrementActionAmount() { + actionCount++; + } + /** + * Executes all created transactions in A&AI + * @throws BulkProcessFailed + */ + public abstract void execute() throws BulkProcessFailed; + + private Relationship buildRelationship(Uri uri) { + return buildRelationship(uri, Optional.empty()); + } + + private Relationship buildRelationship(Uri uri, EdgeLabel label) { + return buildRelationship(uri, Optional.of(label)); + } + private Relationship buildRelationship(Uri uri, Optional<EdgeLabel> label) { + final Relationship result = new Relationship(); + result.setRelatedLink(uri.build().toString()); + if (label.isPresent()) { + result.setRelationshipLabel(label.toString()); + } + return result; + } + + protected GraphInventoryPatchConverter getPatchConverter() { + return this.patchConverter; + } + +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java b/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java new file mode 100644 index 0000000000..2cab4b5654 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java @@ -0,0 +1,10 @@ +package org.onap.so.client.graphinventory; + +public interface TransactionBuilder { + + + void put(String uri, Object body); + void delete(String uri, Object body); + void patch(String uri,Object body); + +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java new file mode 100644 index 0000000000..7da1408f2d --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory.entities; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.onap.so.client.aai.entities.QueryStep; +import org.onap.so.client.graphinventory.GraphInventoryObjectName; + +public class DSLNode implements QueryStep { + + private final String nodeName; + private final List<DSLNodeKey> nodeKeys; + private final StringBuilder query = new StringBuilder(); + private boolean output = false; + + public DSLNode() { + this.nodeName = ""; + this.nodeKeys = new ArrayList<>(); + + } + public DSLNode(GraphInventoryObjectName name) { + this.nodeName = name.typeName(); + this.nodeKeys = new ArrayList<>(); + query.append(nodeName); + } + public DSLNode(GraphInventoryObjectName name, DSLNodeKey... key) { + this.nodeName = name.typeName(); + this.nodeKeys = Arrays.asList(key); + query.append(nodeName); + } + + public DSLNode output() { + this.output = true; + + return this; + } + + public DSLNode and(DSLNodeKey... key) { + this.nodeKeys.addAll(Arrays.asList(key)); + + return this; + } + + @Override + public String build() { + if (output) { + query.append("*"); + } + for (DSLNodeKey key : nodeKeys) { + query.append(key.build()); + } + + return query.toString(); + } +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java new file mode 100644 index 0000000000..159bfb1c29 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory.entities; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.onap.so.client.aai.entities.QueryStep; + +import com.google.common.base.Joiner; + + +public class DSLNodeKey implements QueryStep { + + private boolean not = false; + private final StringBuilder query = new StringBuilder(); + private final String keyName; + private final List<String> values; + public DSLNodeKey(String keyName, String... value) { + + this.keyName = keyName; + this.values = Arrays.asList(value); + } + + public DSLNodeKey not() { + + this.not = true; + return this; + } + + @Override + public String build() { + + if (not) { + query.append(" !"); + } + query.append("('").append(keyName).append("', "); + List<String> temp = new ArrayList<>(); + for (String item : values) { + if (item.equals("null")) { + temp.add(String.format("' %s '", item)); + } else if (item.equals("")){ + temp.add("' '"); + } else { + temp.add(String.format("'%s'", item)); + } + } + query.append(Joiner.on(", ").join(temp)).append(")"); + + return query.toString(); + } +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java new file mode 100644 index 0000000000..c8ab015b26 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory.entities; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DSLQuery { + + private String dsl; + + public DSLQuery() { + + } + + public DSLQuery(String dsl) { + this.dsl = dsl; + } + + public String getDsl() { + return dsl; + } + + public void setDsl(String dsl) { + this.dsl = dsl; + } + + +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java new file mode 100644 index 0000000000..73dccea8e6 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory.entities; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.onap.so.client.aai.entities.QueryStep; + +import com.google.common.base.Joiner; + + +public class DSLQueryBuilder<S, E> implements QueryStep { + + private List<QueryStep> steps = new ArrayList<>(); + + + public DSLQueryBuilder() { + + } + public DSLQueryBuilder(DSLNode node) { + steps.add(node); + } + + public DSLQueryBuilder<S, DSLNode> node(DSLNode node) { + steps.add(node); + + return (DSLQueryBuilder<S, DSLNode>) this; + } + public DSLQueryBuilder<S, E> output() { + if (steps.get(steps.size() -1) instanceof DSLNode) { + ((DSLNode)steps.get(steps.size() -1)).output(); + } + return this; + } + + public <E2> DSLQueryBuilder<S, E2> union(final DSLQueryBuilder<?, E2>... union) { + + List<DSLQueryBuilder<?, ?>> unions = Arrays.asList(union); + steps.add(() -> { + StringBuilder query = new StringBuilder(); + + query.append("> [ ").append( + Joiner.on(", ").join( + unions.stream().map(item -> item.build()).collect(Collectors.toList()))) + .append(" ]"); + return query.toString(); + }); + + return (DSLQueryBuilder<S, E2>) this; + } + + public DSLQueryBuilder<S, E> where(DSLQueryBuilder<?, ?> where) { + + steps.add(() -> { + StringBuilder query = new StringBuilder(); + query.append(where.build()).append(")"); + String result = query.toString(); + if (!result.startsWith(">")) { + result = "> " + result; + } + return "(" + result; + }); + return this; + } + + public DSLQueryBuilder<S, E> to(DSLQueryBuilder<?, ?> to) { + steps.add(() -> { + StringBuilder query = new StringBuilder(); + + query.append("> ").append(to.build()); + return query.toString(); + }); + return this; + } + + public String limit(int limit) { + return compile() + " LIMIT " + limit; + } + + @Override + public String build() { + return compile(); + } + + private String compile() { + return Joiner.on(" ").join(steps.stream().map(item -> item.build()).collect(Collectors.toList())); + } + + protected QueryStep getFirst() { + return steps.get(0); + } +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java new file mode 100644 index 0000000000..cc1ce0063b --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory.entities; + +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import org.onap.so.client.aai.AAICommonObjectMapperProvider; +import org.onap.so.client.aai.entities.Relationships; +import org.onap.so.jsonpath.JsonPathUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class GraphInventoryResultWrapper implements Serializable { + + private static final long serialVersionUID = 5895841925807816727L; + protected final String jsonBody; + protected final ObjectMapper mapper; + private final transient Logger logger; + + protected GraphInventoryResultWrapper(String json, Logger logger) { + this.jsonBody = json; + this.mapper = new AAICommonObjectMapperProvider().getMapper(); + this.logger = logger; + } + + protected GraphInventoryResultWrapper(Object aaiObject, Logger logger) { + this.mapper = new AAICommonObjectMapperProvider().getMapper(); + this.jsonBody = mapObjectToString(aaiObject); + this.logger = logger; + } + + protected String mapObjectToString(Object aaiObject) { + try { + return mapper.writeValueAsString(aaiObject); + } catch (JsonProcessingException e) { + logger.warn("could not parse object into json - defaulting to {}"); + return "{}"; + } + } + public Optional<Relationships> getRelationships() { + final String path = "$.relationship-list"; + if (isEmpty()) { + return Optional.empty(); + } + Optional<String> result = JsonPathUtil.getInstance().locateResult(jsonBody, path); + if (result.isPresent()) { + return Optional.of(new Relationships(result.get())); + } else { + return Optional.empty(); + } + } + + public String getJson() { + if(jsonBody == null) { + return "{}"; + } else { + return jsonBody; + } + } + + public Map<String, Object> asMap() { + if (isEmpty()) { + return new HashMap<>(); + } + try { + return mapper.readValue(this.jsonBody, new TypeReference<Map<String, Object>>(){}); + } catch (IOException e) { + return new HashMap<>(); + } + } + + public <T> Optional<T> asBean(Class<T> clazz) { + if (isEmpty()) { + return Optional.empty(); + } + try { + return Optional.of(mapper.readValue(this.jsonBody, clazz)); + } catch (IOException e) { + return Optional.empty(); + } + } + + public boolean isEmpty() { + return jsonBody == null; + } + @Override + public String toString() { + return this.getJson(); + } + +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java new file mode 100644 index 0000000000..184f412adb --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.graphinventory.entities; + +import org.onap.so.client.graphinventory.GraphInventoryObjectName; + +public class __ { + + protected __() { + + } + + public static <A> DSLQueryBuilder<A, A> identity() { + return new DSLQueryBuilder<>(); + } + public static <A> DSLQueryBuilder<A, A> start(DSLNode node) { + return new DSLQueryBuilder<>(node); + } + public static DSLQueryBuilder<DSLNode, DSLNode> node(GraphInventoryObjectName name) { + + return __.<DSLNode>start(new DSLNode(name)); + } + + public static DSLQueryBuilder<DSLNode, DSLNode> node(GraphInventoryObjectName name, DSLNodeKey... key) { + return __.<DSLNode>start(new DSLNode(name, key)); + } + + public static DSLNodeKey key(String keyName, String... value) { + return new DSLNodeKey(keyName, value); + } + + public static <A, B> DSLQueryBuilder<A, B> union(final DSLQueryBuilder<?, B>... traversal) { + + return __.<A>identity().union(traversal); + } + +public static <A> DSLQueryBuilder<A, A> where(DSLQueryBuilder<A, A> traversal) { + + return __.<A>identity().where(traversal); + } +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java index 93de9139f9..dc4179a86f 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java @@ -98,6 +98,13 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { validateValuesSize(childType.partialUri(), values); } + protected SimpleUri(GraphInventoryResourceUri parentUri, GraphInventoryObjectPlurals childType) { + this.type = null; + this.pluralType = childType; + this.internalURI = UriBuilder.fromUri(parentUri.build()).path(childType.partialUri()); + this.values = new Object[0]; + } + protected void setInternalURI(UriBuilder builder) { this.internalURI = builder; } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java index c94e561274..121708fc46 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + package org.onap.so.client.graphinventory.exceptions; public class IncorrectNumberOfUriKeys extends RuntimeException { diff --git a/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java b/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java index 1d4e014300..93a2d96c5e 100644 --- a/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java +++ b/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java @@ -32,13 +32,13 @@ public class RubyCreateTicketRequestPublisher extends DmaapPublisher{ } @Override - public String getUserName() { - return msoProperties.get("ruby.create-ticket-request.dmaap.username"); + public String getAuth() { + return msoProperties.get("ruby.create-ticket-request.dmaap.auth"); } @Override - public String getPassword() { - return msoProperties.get("ruby.create-ticket-request.dmaap.password"); + public String getKey() { + return msoProperties.get("mso.msoKey"); } @Override diff --git a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java index 8154b9137d..a76c47c805 100644 --- a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java +++ b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java @@ -42,13 +42,13 @@ public class SDNOHealthCheckDmaapConsumer extends DmaapConsumer { } @Override - public String getUserName() { - return msoProperties.get("sdno.health-check.dmaap.username"); + public String getAuth() { + return msoProperties.get("sdno.health-check.dmaap.auth"); } @Override - public String getPassword() { - return msoProperties.get("sdno.health-check.dmaap.password"); + public String getKey() { + return msoProperties.get("mso.msoKey"); } @Override diff --git a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java index 2556e67e3c..f4af2052ac 100644 --- a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java +++ b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java @@ -33,13 +33,13 @@ public class SDNOHealthCheckDmaapPublisher extends DmaapPublisher { } @Override - public String getUserName() { - return msoProperties.get("sdno.health-check.dmaap.username"); + public String getAuth() { + return msoProperties.get("sdno.health-check.dmaap.auth"); } @Override - public String getPassword() { - return msoProperties.get("sdno.health-check.dmaap.password"); + public String getKey() { + return msoProperties.get("sdno.health-check.dmaap.msoKey"); } @Override diff --git a/common/src/main/resources/dmaap/default-consumer.properties b/common/src/main/resources/dmaap/default-consumer.properties index f19b64242d..3f492e1d33 100644 --- a/common/src/main/resources/dmaap/default-consumer.properties +++ b/common/src/main/resources/dmaap/default-consumer.properties @@ -16,6 +16,7 @@ maxBatchSize=100 maxAgeMs=250 group=MSO id=dev +timeout=60000 AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler AFT_DME2_REQ_TRACE_ON=true diff --git a/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java b/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java index d4eaf0873b..64a83f92ab 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java @@ -80,4 +80,11 @@ public class AAIObjectTypeTest { assertEquals("/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces/p-interface/{interface-name}", type.uriTemplate()); assertEquals("/p-interfaces/p-interface/{interface-name}", type.partialUri()); } + + @Test + public void networkPolicyObjectTypeTest() { + final String id = "test1"; + AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, id); + assertEquals("/network/network-policies/network-policy/test1", aaiUri.build().toString()); + } } diff --git a/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java index 43616ba0c2..84c3cad0f9 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java @@ -20,11 +20,8 @@ package org.onap.so.client.aai; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -36,9 +33,8 @@ import javax.ws.rs.core.Response; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.RestClient; import org.onap.so.client.aai.entities.CustomQuery; @@ -46,6 +42,8 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.Format; +import org.onap.so.client.graphinventory.GraphInventoryClient; +import org.onap.so.client.graphinventory.GraphInventorySubgraphType; @RunWith(MockitoJUnitRunner.class) @@ -57,7 +55,10 @@ public class AAIQueryClientTest { @Mock RestClient restClient; - @Spy + @Mock + GraphInventoryClient client; + + @InjectMocks AAIQueryClient aaiQueryClient = new AAIQueryClient(); @Test @@ -67,16 +68,16 @@ public class AAIQueryClientTest { Format format = Format.SIMPLE; CustomQuery query = new CustomQuery(uris); - doReturn(restClient).when(aaiQueryClient).createClient(isA(AAIUri.class)); + doReturn(restClient).when(client).createClient(isA(AAIUri.class)); aaiQueryClient.query(format, query); - verify(aaiQueryClient, times(1)).createClient(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY).queryParam("format", format.toString())); + verify(client, times(1)).createClient(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY).queryParam("format", format.toString())); verify(restClient, times(1)).put(query, String.class); } @Test public void testCreateClient() { String depth = "testDepth"; - AAISubgraphType subgraph = AAISubgraphType.STAR; + GraphInventorySubgraphType subgraph = GraphInventorySubgraphType.STAR; aaiQueryClient.depth(depth); aaiQueryClient.nodesOnly(); diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java index 32a9ca54a8..a55fbc9517 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java @@ -35,18 +35,26 @@ import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.Relationship; import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; +import org.onap.so.client.graphinventory.GraphInventoryClient; import com.github.tomakehurst.wiremock.admin.NotFoundException; import com.github.tomakehurst.wiremock.junit.WireMockRule; + +@RunWith(MockitoJUnitRunner.class) public class AAIResourcesClientTest { @@ -56,6 +64,18 @@ public class AAIResourcesClientTest { @Rule public ExpectedException thrown = ExpectedException.none(); + + @Spy + public AAIClient client; + + @InjectMocks + public AAIResourcesClient aaiClient = new AAIResourcesClient(); + + @Before + public void beforeTest() { + doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); + } + @Test public void verifyNotExists() { AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test"); @@ -66,7 +86,7 @@ public class AAIResourcesClientTest { .withHeader("Content-Type", "text/plain") .withBody("hello") .withStatus(404))); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; boolean result = client.exists(path); assertEquals("path not found", false, result); } @@ -87,7 +107,7 @@ public class AAIResourcesClientTest { .willReturn( aResponse() .withStatus(204))); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; client.delete(path); } @@ -102,7 +122,7 @@ public class AAIResourcesClientTest { .withHeader("Content-Type", "application/json") .withBodyFile("aai/resources/mockObject.json") .withStatus(200))); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; client.get(path); } @@ -118,7 +138,7 @@ public class AAIResourcesClientTest { .withStatus(200))); AAIResourceUri pathClone = path.clone(); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; client.connect(path, path2); assertEquals("uri not modified", pathClone.build().toString(), path.build().toString()); } @@ -135,7 +155,7 @@ public class AAIResourcesClientTest { .withStatus(204))); AAIResourceUri pathClone = path.clone(); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; client.disconnect(path, path2); assertEquals("uri not modified", pathClone.build().toString(), path.build().toString()); } @@ -150,7 +170,7 @@ public class AAIResourcesClientTest { aResponse() .withStatus(200))); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; client.update(path, "{}"); } @@ -165,7 +185,7 @@ public class AAIResourcesClientTest { .withHeader("Content-Type", "text/plain") .withBody("hello") .withStatus(404))); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; AAIResultWrapper result = client.get(path); assertEquals("is empty", true, result.isEmpty()); } @@ -180,7 +200,7 @@ public class AAIResourcesClientTest { .withHeader("Content-Type", "text/plain") .withBody("hello") .withStatus(404))); - AAIResourcesClient client= createClient(); + AAIResourcesClient client= aaiClient; thrown.expect(NotFoundException.class); thrown.expectMessage(containsString(path.build() + " not found in A&AI")); AAIResultWrapper result = client.get(path, NotFoundException.class); @@ -188,7 +208,7 @@ public class AAIResourcesClientTest { @Test public void buildRelationshipTest() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test"); Relationship relationship = new Relationship(); relationship.setRelatedLink(uri.build().toString()); @@ -200,10 +220,5 @@ public class AAIResourcesClientTest { assertThat("expect equal has label", actual, sameBeanAs(relationship)); } - - private AAIResourcesClient createClient() { - AAIResourcesClient client = spy(new AAIResourcesClient()); - doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); - return client; - } + } diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java index 3d23213ff0..5493d6778e 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java @@ -40,6 +40,10 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.entities.uri.ServiceInstanceUri; @@ -47,6 +51,7 @@ import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; import com.github.tomakehurst.wiremock.junit.WireMockRule; +@RunWith(MockitoJUnitRunner.class) public class AAIResourcesClientWithServiceInstanceUriTest { @Rule @@ -55,9 +60,17 @@ public class AAIResourcesClientWithServiceInstanceUriTest { @Rule public ExpectedException thrown = ExpectedException.none(); + @Spy + public AAIClient client; + + @InjectMocks + public AAIResourcesClient aaiClient = new AAIResourcesClient(); + private ServiceInstanceUri uri; @Before public void setUp() { + + doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); wireMockRule.stubFor(get(urlMatching("/aai/v[0-9]+/nodes.*")) .willReturn(aResponse() .withStatus(404) @@ -65,12 +78,12 @@ public class AAIResourcesClientWithServiceInstanceUriTest { .withHeader("Mock", "true"))); uri = spy((ServiceInstanceUri)AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "id")); - doReturn(createClient()).when(uri).getResourcesClient(); + doReturn(aaiClient).when(uri).getResourcesClient(); } @Test public void getWithClass() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; Optional<String> result = client.get(String.class, uri); assertThat(result.isPresent(), equalTo(false)); @@ -78,42 +91,38 @@ public class AAIResourcesClientWithServiceInstanceUriTest { @Test public void getFullResponse() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; Response result = client.getFullResponse(uri); assertThat(result.getStatus(), equalTo(Status.NOT_FOUND.getStatusCode())); } @Test public void getWithGenericType() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; Optional<List<String>> result = client.get(new GenericType<List<String>>() {}, uri); assertThat(result.isPresent(), equalTo(false)); } @Test public void getAAIWrapper() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; AAIResultWrapper result = client.get(uri); assertThat(result.isEmpty(), equalTo(true)); } @Test public void getWithException() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; this.thrown.expect(IllegalArgumentException.class); AAIResultWrapper result = client.get(uri, IllegalArgumentException.class); } @Test public void existsTest() { - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; doReturn(uri).when(uri).clone(); boolean result = client.exists(uri); assertThat(result, equalTo(false)); } - private AAIResourcesClient createClient() { - AAIResourcesClient client = spy(new AAIResourcesClient()); - doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); - return client; - } + } diff --git a/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java index ad15417b71..95b30f934b 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java @@ -41,6 +41,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.RestClientSSL; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -68,7 +69,7 @@ public class AAIRestClientTest { public void verifyPatchValidation() throws URISyntaxException { AAIRestClient client = new AAIRestClient(props, new URI("")); AAIRestClient spy = spy(client); - AAIPatchConverter patchValidatorMock = mock(AAIPatchConverter.class); + GraphInventoryPatchConverter patchValidatorMock = mock(GraphInventoryPatchConverter.class); doReturn(patchValidatorMock).when(spy).getPatchConverter(); String payload = "{}"; doReturn(Response.ok().build()).when(spy).method(eq("PATCH"), any()); diff --git a/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java index 428fa276db..d875f384b0 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java @@ -38,6 +38,10 @@ import java.util.Optional; import org.json.JSONException; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.Pserver; import org.onap.aai.domain.yang.v9.Complex; import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRequest; @@ -45,6 +49,7 @@ import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRespon import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; import org.skyscreamer.jsonassert.JSONAssert; import com.fasterxml.jackson.core.JsonParseException; @@ -52,6 +57,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +@RunWith(MockitoJUnitRunner.class) public class AAISingleTransactionClientTest { private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/singletransaction/"; @@ -60,6 +66,10 @@ public class AAISingleTransactionClientTest { ObjectMapper mapper; + public AAIClient client = new AAIClient(); + + public AAIResourcesClient aaiClient = new AAIResourcesClient(); + @Before public void before() throws JsonParseException, JsonMappingException, IOException { mapper = new AAICommonObjectMapperProvider().getMapper(); @@ -68,7 +78,6 @@ public class AAISingleTransactionClientTest { @Test public void testRequest() throws JSONException,IOException { - AAIResourcesClient client = createClient(); Pserver pserver = new Pserver(); pserver.setHostname("pserver-hostname"); pserver.setFqdn("pserver-bulk-process-single-transactions-multiple-actions-1-fqdn"); @@ -77,7 +86,7 @@ public class AAISingleTransactionClientTest { Complex complex = new Complex(); complex.setCity("my-city"); AAISingleTransactionClient singleTransaction = - client.beginSingleTransaction() + aaiClient.beginSingleTransaction() .create(uriA, pserver) .update(uriA, pserver2) .create(uriB, complex); @@ -92,8 +101,7 @@ public class AAISingleTransactionClientTest { @Test public void testFailure() throws IOException { - AAIResourcesClient client = createClient(); - AAISingleTransactionClient singleTransaction = client.beginSingleTransaction(); + AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction(); SingleTransactionResponse expected = mapper.readValue(this.getJson("sample-response-failure.json"), SingleTransactionResponse.class); Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected); @@ -104,8 +112,7 @@ public class AAISingleTransactionClientTest { @Test public void testSuccessResponse() throws IOException { - AAIResourcesClient client = createClient(); - AAISingleTransactionClient singleTransaction = client.beginSingleTransaction(); + AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction(); SingleTransactionResponse expected = mapper.readValue(this.getJson("sample-response.json"), SingleTransactionResponse.class); Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected); @@ -116,8 +123,8 @@ public class AAISingleTransactionClientTest { @Test public void confirmPatchFormat() { - AAISingleTransactionClient singleTransaction = spy(new AAISingleTransactionClient(AAIVersion.LATEST)); - AAIPatchConverter mock = mock(AAIPatchConverter.class); + AAISingleTransactionClient singleTransaction = spy(new AAISingleTransactionClient(aaiClient, client)); + GraphInventoryPatchConverter mock = mock(GraphInventoryPatchConverter.class); doReturn(mock).when(singleTransaction).getPatchConverter(); singleTransaction.update(uriA, "{}"); verify(mock, times(1)).convertPatchFormat(any()); @@ -126,9 +133,4 @@ public class AAISingleTransactionClientTest { return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename))); } - private AAIResourcesClient createClient() { - AAIResourcesClient client = spy(new AAIResourcesClient()); - doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); - return client; - } } diff --git a/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java index 621375882b..3e2801c452 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java @@ -38,11 +38,15 @@ import java.util.Optional; import org.junit.Before; import org.junit.Test; - +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.Relationship; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; @@ -50,6 +54,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +@RunWith(MockitoJUnitRunner.class) public class AAITransactionalClientTest { private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/bulkprocess/"; @@ -62,6 +67,10 @@ public class AAITransactionalClientTest { ObjectMapper mapper; + public AAIClient client = new AAIClient(); + + public AAIResourcesClient aaiClient = new AAIResourcesClient(); + @Before public void before() throws JsonParseException, JsonMappingException, IOException { mapper = new AAICommonObjectMapperProvider().getMapper(); @@ -73,7 +82,7 @@ public class AAITransactionalClientTest { final Relationship body = new Relationship(); body.setRelatedLink(uriB.build().toString()); - AAITransactionalClient transactions = createClient().beginTransaction() + AAITransactionalClient transactions = aaiClient.beginTransaction() .create(uriA.clone().relationshipAPI(), body); String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions()); @@ -89,7 +98,7 @@ public class AAITransactionalClientTest { uris.add(uriB); AAIResourceUri uriAClone = uriA.clone(); - AAITransactionalClient transactions = createClient() + AAITransactionalClient transactions = aaiClient .beginTransaction().connect(uriA, uris).connect(uriC, uriD) .beginNewTransaction().connect(uriE, uriF); @@ -106,7 +115,7 @@ public class AAITransactionalClientTest { List<AAIResourceUri> uris = new ArrayList<AAIResourceUri>(); uris.add(uriB); - AAITransactionalClient transactions = createClient().beginTransaction() + AAITransactionalClient transactions = aaiClient.beginTransaction() .disconnect(uriA, uris); String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions()); @@ -122,7 +131,7 @@ public class AAITransactionalClientTest { body.setRelatedLink(uriB.build().toString()); AAIResourceUri uriAClone = uriA.clone().relationshipAPI(); - AAITransactionalClient transactions = createClient().beginTransaction().update(uriAClone, body); + AAITransactionalClient transactions = aaiClient.beginTransaction().update(uriAClone, body); String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions()); Map<String, Object> actual = mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>(){}); @@ -133,7 +142,7 @@ public class AAITransactionalClientTest { @Test public void verifyResponse() throws IOException { - AAITransactionalClient transactions = createClient() + AAITransactionalClient transactions = aaiClient .beginTransaction(); assertEquals("success status", Optional.empty(), transactions.locateErrorMessages(getJson("response-success.json"))); @@ -142,10 +151,10 @@ public class AAITransactionalClientTest { @Test public void confirmPatchFormat() { - AAITransactionalClient client = spy(new AAITransactionalClient(AAIVersion.LATEST)); - AAIPatchConverter mock = mock(AAIPatchConverter.class); - doReturn(mock).when(client).getPatchConverter(); - client.update(uriA, "{}"); + AAITransactionalClient transactionClient = spy(new AAITransactionalClient(aaiClient, client)); + GraphInventoryPatchConverter mock = mock(GraphInventoryPatchConverter.class); + doReturn(mock).when(transactionClient).getPatchConverter(); + transactionClient.update(uriA, "{}"); verify(mock, times(1)).convertPatchFormat(any()); } @@ -153,9 +162,4 @@ public class AAITransactionalClientTest { return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename))); } - private AAIResourcesClient createClient() { - AAIResourcesClient client = spy(new AAIResourcesClient()); - doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); - return client; - } } diff --git a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java new file mode 100644 index 0000000000..69d46de96a --- /dev/null +++ b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.aai; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.so.client.graphinventory.entities.DSLNode; +import org.onap.so.client.graphinventory.entities.DSLQueryBuilder; +import org.onap.so.client.graphinventory.entities.__; + +public class DSLQueryBuilderTest { + + + @Test + public void whereTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION, + __.key("cloud-owner", "att-nc"), + __.key("cloud-region-id", "test"))); + + builder.to(__.node(AAIObjectType.VLAN_TAG)).where( + __.node(AAIObjectType.OWNING_ENTITY, + __.key("owning-entity-name", "name") + ) + ).to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", "108")).output()); + + assertEquals("cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'test') > " + + "vlan-tag (> owning-entity('owning-entity-name', 'name')) > " + + "vlan-tag*('vlan-id-outer', '108')", builder.build()); + } + + @Test + public void unionTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF, + __.key("vnf-id", "vnfId")).output()); + + builder.union(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output()), + __.node(AAIObjectType.VSERVER).to(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output()))); + + assertEquals("generic-vnf*('vnf-id', 'vnfId') > " + "[ pserver* > complex*, " + + "vserver > pserver* > complex* ]", builder.build()); + } + + @Test + public void whereUnionTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF, + __.key("vnf-id", "vnfId")).output()); + + builder.where( + __.union( + __.node(AAIObjectType.PSERVER, __.key("hostname", "hostname1")), + __.node(AAIObjectType.VSERVER).to(__.node(AAIObjectType.PSERVER, __.key("hostname", "hostname1"))))); + + assertEquals("generic-vnf*('vnf-id', 'vnfId') (> [ pserver('hostname', 'hostname1'), " + + "vserver > pserver('hostname', 'hostname1') ])", builder.build()); + } + + @Test + public void notNullTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION, + __.key("cloud-owner", "", "null").not()).output()); + + assertEquals("cloud-region* !('cloud-owner', ' ', ' null ')", builder.build()); + } +} diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java index 729f0e50e9..e84326e95f 100644 --- a/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java +++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + package org.onap.so.client.aai.entities.uri; import static org.hamcrest.CoreMatchers.equalTo; diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java index 6059e7bd23..15c1c24ae2 100644 --- a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java +++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java @@ -26,7 +26,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -45,10 +44,16 @@ import java.util.Optional; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.UriBuilder; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.client.aai.AAIClient; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; @@ -58,6 +63,7 @@ import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundExc import com.github.tomakehurst.wiremock.junit.WireMockRule; +@RunWith(MockitoJUnitRunner.class) public class ServiceInstanceUriTest { private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/resources/"; @@ -68,6 +74,16 @@ public class ServiceInstanceUriTest { @Rule public final ExpectedException exception = ExpectedException.none(); + @Spy + public AAIClient client; + + @InjectMocks + public AAIResourcesClient aaiClient = new AAIResourcesClient(); + + @Before + public void beforeTest() { + doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); + } @Test public void found() throws IOException { final String content = new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "service-instance-pathed-query.json"))); @@ -179,7 +195,7 @@ public class ServiceInstanceUriTest { public void noVertexFound() throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException { ServiceInstanceUri instance = new ServiceInstanceUri("key3"); ServiceInstanceUri spy = spy(instance); - AAIResourcesClient client = createClient(); + AAIResourcesClient client = aaiClient; doReturn(client).when(spy).getResourcesClient(); stubFor(get(urlPathMatching("/aai/v[0-9]+/nodes/service-instances/service-instance/key3")) .willReturn(aResponse() @@ -189,10 +205,4 @@ public class ServiceInstanceUriTest { exception.expect(NotFoundException.class); spy.build(); } - - private AAIResourcesClient createClient() { - AAIResourcesClient client = spy(new AAIResourcesClient()); - doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties(); - return client; - } } diff --git a/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java b/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java index b964e905de..3979902962 100644 --- a/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java +++ b/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + package org.onap.so.client.aai.objects; import org.onap.so.client.aai.AAINamespaceConstants; diff --git a/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java b/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java new file mode 100644 index 0000000000..f4490faacc --- /dev/null +++ b/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Nokia. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.adapter.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.net.URISyntaxException; +import java.security.GeneralSecurityException; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.onap.so.client.policy.JettisonStyleMapperProvider; +import org.onap.so.utils.CryptoUtils; +import org.onap.so.utils.TargetEntity; + +public class AdapterRestClientTest { + + private static final String CRYPTO_KEY = "546573746F736973546573746F736973"; + private static final String INVALID_CRYPTO_KEY = "1234"; + + private Map<String, String> headerMap; + private AdapterRestProperties adapterRestPropertiesMock; + + @Before + public void setup() { + headerMap = new HashMap<>(); + adapterRestPropertiesMock = mock(AdapterRestProperties.class); + } + + @Test + public void initializeHeaderMap_success() throws URISyntaxException, GeneralSecurityException { + // given + String encyptedMessage = CryptoUtils.encrypt("testAdapter", CRYPTO_KEY); + when(adapterRestPropertiesMock.getAuth()).thenReturn(encyptedMessage); + when(adapterRestPropertiesMock.getKey()).thenReturn(CRYPTO_KEY); + AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI("")); + // when + testedObject.initializeHeaderMap(headerMap); + // then + assertThat(headerMap).containsOnly(entry("Authorization", getExpectedEncodedString(encyptedMessage))); + } + + @Test + public void initializeHeaderMap_putNullToMapWhenAuthIsNull() throws URISyntaxException { + // given + AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI("")); + // when + testedObject.initializeHeaderMap(headerMap); + // then + assertThat(headerMap).containsOnly(entry("Authorization", null)); + } + + @Test + public void initializeHeaderMap_putNullToMapWhenExOccurs() throws URISyntaxException, GeneralSecurityException { + // given + String encyptedMessage = CryptoUtils.encrypt("testAdapter", CRYPTO_KEY); + when(adapterRestPropertiesMock.getAuth()).thenReturn(encyptedMessage); + when(adapterRestPropertiesMock.getKey()).thenReturn(INVALID_CRYPTO_KEY); + AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI(""), + "accept", "contentType"); + // when + testedObject.initializeHeaderMap(headerMap); + // then + assertThat(headerMap).containsOnly(entry("Authorization", null)); + } + + @Test + public void getTargetEntity_success() throws URISyntaxException { + AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI("")); + assertThat(testedObject.getTargetEntity()).isEqualTo(TargetEntity.OPENSTACK_ADAPTER); + } + + @Test + public void getCommonObjectMapperProvider_success() throws URISyntaxException { + AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI("")); + assertThat(testedObject.getCommonObjectMapperProvider()).isInstanceOf(JettisonStyleMapperProvider.class); + } + + private String getExpectedEncodedString(String encryptedMessage) throws GeneralSecurityException { + String auth = CryptoUtils.decrypt(encryptedMessage, CRYPTO_KEY); + byte[] encoded = Base64.encodeBase64(auth.getBytes()); + String encodedString = new String(encoded); + return "Basic " + encodedString; + } +} diff --git a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java index c0633c1cca..0836ed23eb 100644 --- a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java +++ b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java @@ -29,13 +29,13 @@ public class DmaapPublisherTest { DmaapPublisher dmaapPublisher = new DmaapPublisher(120) { @Override - public String getUserName() { - return "test"; + public String getAuth() { + return "8F73A1691F6271E769329C176EE3EA48F52786AF12A3E16259007EED2A0F0CC3CB965F4AB5318483015723CCE1C0B48AB6C4DED6E251869393B01E4EC532FC88D4A128B92F4CDB34719B171923"; } @Override - public String getPassword() { - return "test"; + public String getKey() { + return "07a7159d3bf51a0e53be7a8f89699be7"; } @Override diff --git a/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java b/common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java index 0d4490f51d..d24b3ff147 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java +++ b/common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.client.aai; +package org.onap.so.client.graphinventory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -35,6 +35,8 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.so.client.aai.AAICommonObjectMapperProvider; +import org.onap.so.client.graphinventory.GraphInventoryPatchConverter; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -42,13 +44,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(MockitoJUnitRunner.class) -public class AAIPatchConverterTest { +public class GraphInventoryPatchConverterTest { private ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper(); @Test public void convertObjectToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { - AAIPatchConverter validator = new AAIPatchConverter(); + GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter(); GenericVnf vnf = new GenericVnf(); vnf.setIpv4Loopback0Address(""); String result = validator.marshallObjectToPatchFormat(vnf); @@ -60,7 +62,7 @@ public class AAIPatchConverterTest { @Test public void convertStringToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { - AAIPatchConverter validator = new AAIPatchConverter(); + GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter(); String payload = "{\"ipv4-loopback0-address\":\"\"}"; String result = validator.marshallObjectToPatchFormat(payload); @@ -69,7 +71,7 @@ public class AAIPatchConverterTest { @Test public void convertStringToPatchFormatNull_Test() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { - AAIPatchConverter validator = new AAIPatchConverter(); + GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter(); String payload = "{\"ipv4-loopback0-address\": null}"; String result = validator.marshallObjectToPatchFormat(payload); System.out.println(result); @@ -78,7 +80,7 @@ public class AAIPatchConverterTest { @Test public void convertMapToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { - AAIPatchConverter validator = new AAIPatchConverter(); + GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter(); HashMap<String, String> map = new HashMap<>(); map.put("ipv4-loopback0-address", ""); map.put("ipv4-loopback1-address", "192.168.1.1"); @@ -89,7 +91,7 @@ public class AAIPatchConverterTest { @Test public void hasComplexObjectTest() { - AAIPatchConverter validator = new AAIPatchConverter(); + GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter(); String hasNesting = "{ \"hello\" : \"world\", \"nested\" : { \"key\" : \"value\" } }"; String noNesting = "{ \"hello\" : \"world\" }"; String arrayCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"nestedComplex\" : [{\"key\" : \"value\"}]}"; diff --git a/common/src/test/resources/dmaap.properties b/common/src/test/resources/dmaap.properties index 7ce101996c..5593455da3 100644 --- a/common/src/test/resources/dmaap.properties +++ b/common/src/test/resources/dmaap.properties @@ -4,4 +4,7 @@ sdno.health-check.dmaap.subscriber.topic=com.att.sdno.test-health-diagnostic-v02 sdno.health-check.dmaap.publisher.topic=com.att.sdno.test-health-diagnostic-v02 ruby.create-ticket-request.dmaap.username=testuser ruby.create-ticket-request.dmaap.password=eHQ1cUJrOUc -ruby.create-ticket-request.publisher.topic=com.att.pdas.st1.msoCMFallout-v1
\ No newline at end of file +ruby.create-ticket-request.publisher.topic=com.att.pdas.st1.msoCMFallout-v1 +ruby.create-ticket-request.dmaap.auth=81B7E3533B91A6706830611FB9A8ECE529BBCCE754B1F1520FA7C8698B42F97235BEFA993A387E664D6352C63A6185D68DA7F0B1D360637CBA102CB166E3E62C11EB1F75386D3506BCECE51E54 +sdno.health-check.dmaap.auth=81B7E3533B91A6706830611FB9A8ECE529BBCCE754B1F1520FA7C8698B42F97235BEFA993A387E664D6352C63A6185D68DA7F0B1D360637CBA102CB166E3E62C11EB1F75386D3506BCECE51E54 +mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7
\ No newline at end of file |