diff options
Diffstat (limited to 'common/src')
25 files changed, 477 insertions, 38 deletions
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 1370bb3fa3..3f9715bdef 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 @@ -116,17 +116,23 @@ public class AAISingleTransactionClient } @Override - public void put(String uri, Object body) { + protected void put(String uri, Object body) { request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri).withBody(body)); } @Override - public void delete(String uri, Object body) { - request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(body)); + protected void delete(String uri) { + request.getOperations() + .add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(new Object())); } @Override - public void patch(String uri, Object body) { + protected void delete(String uri, Object obj) { + request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(obj)); + } + + @Override + protected void patch(String uri, Object body) { request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri).withBody(body)); } 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 11e458a3da..e621566e5a 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 @@ -169,18 +169,22 @@ public class AAITransactionalClient } @Override - public void put(String uri, Object body) { + protected 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)); + protected void delete(String uri) { + currentTransaction.getDelete().add(new OperationBody().withUri(uri).withBody(null)); + } + @Override + protected void delete(String uri, Object obj) { + currentTransaction.getDelete().add(new OperationBody().withUri(uri).withBody(obj)); } @Override - public void patch(String uri, Object body) { + protected void patch(String uri, Object body) { currentTransaction.getPatch().add(new OperationBody().withUri(uri).withBody(body)); } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java index 95ed01ee94..96844ff1cb 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java @@ -47,10 +47,12 @@ public class AAIValidatorImpl implements AAIValidator { List<Pserver> pservers; boolean isLocked = false; pservers = client.getPhysicalServerByVnfId(vnfId); - for (Pserver pserver : pservers) { - if (pserver.isInMaint()) { - isLocked = true; - return isLocked; + if (pservers != null) { + for (Pserver pserver : pservers) { + if (pserver.isInMaint()) { + isLocked = true; + return isLocked; + } } } return isLocked; 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 f2f99050db..1fe9da984f 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 @@ -21,6 +21,7 @@ package org.onap.so.client.aai.entities.uri; import java.net.URI; +import java.util.regex.Pattern; import javax.ws.rs.core.UriBuilder; import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; @@ -138,4 +139,9 @@ public class AAISimpleUri extends SimpleUri implements AAIResourceUri { public AAISimpleUri format(Format format) { return (AAISimpleUri) super.format(format); } + + @Override + protected Pattern getPrefixPattern() { + return Pattern.compile("/aai/v\\d+"); + } } diff --git a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java index 4ca5690188..8ef08057e6 100644 --- a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java +++ b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java @@ -35,11 +35,12 @@ public class DefaultDmaapPropertiesImpl implements DmaapProperties { public DefaultDmaapPropertiesImpl() throws IOException { File initialFile = new File("src/test/resources/dmaap.properties"); - InputStream targetStream = new FileInputStream(initialFile); Properties properties = new Properties(); - properties.load(targetStream); - this.properties = new HashMap<>(); - properties.forEach((key, value) -> this.properties.put((String) key, (String) value)); + try (InputStream targetStream = new FileInputStream(initialFile)) { + properties.load(targetStream); + this.properties = new HashMap<>(); + properties.forEach((key, value) -> this.properties.put((String) key, (String) value)); + } } @Override 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 index 72b01c268e..a4f9496d17 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java @@ -40,6 +40,7 @@ public class GraphInventoryCommonObjectMapperProvider extends CommonObjectMapper mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.enable(MapperFeature.USE_ANNOTATIONS); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); 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 index 5fc8726427..45ac1f741d 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java @@ -33,8 +33,7 @@ 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 { +public abstract class GraphInventoryTransactionClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel> { protected static Logger logger = LoggerFactory.getLogger(GraphInventoryTransactionClient.class); @@ -181,7 +180,7 @@ public abstract class GraphInventoryTransactionClient<Self, Uri extends GraphInv 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(), ""); + this.delete(uri.resourceVersion(resourceVersion).build().toString()); incrementActionAmount(); return (Self) this; } @@ -192,6 +191,14 @@ public abstract class GraphInventoryTransactionClient<Self, Uri extends GraphInv protected abstract String getGraphDBName(); + protected abstract void put(String uri, Object body); + + protected abstract void delete(String uri); + + protected abstract void delete(String uri, Object obj); + + protected abstract void patch(String uri, Object body); + /** * @param obj - can be any object which will marshal into a valid A&AI payload * @param uri 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 index f7f5d78604..e301edb0fd 100644 --- 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 @@ -32,9 +32,9 @@ public class DSLNodeKey implements QueryStep { private boolean not = false; private final StringBuilder query = new StringBuilder(); private final String keyName; - private final List<String> values; + private final List<Object> values; - public DSLNodeKey(String keyName, String... value) { + public DSLNodeKey(String keyName, Object... value) { this.keyName = keyName; this.values = Arrays.asList(value); @@ -54,14 +54,18 @@ public class DSLNodeKey implements QueryStep { result.append(" !"); } result.append("('").append(keyName).append("', "); - List<String> temp = new ArrayList<>(); - for (String item : values) { + List<Object> temp = new ArrayList<>(); + for (Object item : values) { if ("null".equals(item)) { temp.add(String.format("' %s '", item)); } else if ("".equals(item)) { temp.add("' '"); } else { - temp.add(String.format("'%s'", item)); + if (item instanceof String) { + temp.add(String.format("'%s'", item)); + } else { + temp.add(item); + } } } result.append(Joiner.on(", ").join(temp)).append(")"); 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 index ffbb86f023..540472a88d 100644 --- 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 @@ -20,12 +20,15 @@ package org.onap.so.client.graphinventory.entities; +import java.lang.reflect.Field; 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 org.onap.so.client.graphinventory.GraphInventoryObjectName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.common.base.Joiner; @@ -33,6 +36,7 @@ public class DSLQueryBuilder<S, E> implements QueryStep { private List<QueryStep> steps = new ArrayList<>(); private String suffix = ""; + private static final Logger logger = LoggerFactory.getLogger(DSLQueryBuilder.class); public DSLQueryBuilder() { @@ -49,8 +53,25 @@ public class DSLQueryBuilder<S, E> implements QueryStep { } public DSLQueryBuilder<S, E> output() { - if (steps.get(steps.size() - 1) instanceof DSLNode) { + Object obj = steps.get(steps.size() - 1); + if (obj instanceof DSLNode) { ((DSLNode) steps.get(steps.size() - 1)).output(); + } else if (obj.getClass().getName().contains("$$Lambda$")) { + // process lambda expressions + for (Field f : obj.getClass().getDeclaredFields()) { + f.setAccessible(true); + Object o; + try { + o = f.get(obj); + if (o instanceof DSLQueryBuilder && ((DSLQueryBuilder) o).steps.get(0) instanceof DSLNode) { + ((DSLNode) ((DSLQueryBuilder) o).steps.get(0)).output(); + } + } catch (IllegalArgumentException | IllegalAccessException e) { + logger.error("Exception occured", e); + } + f.setAccessible(false); + break; + } } return this; } 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 index 2fdd6574e5..87d4d84cac 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java @@ -45,7 +45,7 @@ public class __ { return __.<DSLNode>start(new DSLNode(name, key)); } - public static DSLNodeKey key(String keyName, String... value) { + public static DSLNodeKey key(String keyName, Object... value) { return new DSLNodeKey(keyName, value); } 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 41ba07ad6c..ffe47c5c51 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 @@ -29,6 +29,7 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; import javax.ws.rs.core.UriBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.onap.so.client.graphinventory.Format; @@ -61,7 +62,7 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { protected SimpleUri(GraphInventoryObjectType type, URI uri) { this.type = type; this.pluralType = null; - this.internalURI = UriBuilder.fromPath(uri.getRawPath().replaceAll("/aai/v\\d+", "")); + this.internalURI = UriBuilder.fromPath(uri.getRawPath().replaceAll(getPrefixPattern().toString(), "")); this.values = new Object[0]; } @@ -174,6 +175,10 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { return build(this.values); } + protected Pattern getPrefixPattern() { + return Pattern.compile("/.*?/v\\d+"); + } + protected URI build(Object... values) { // This is a workaround because resteasy does not encode URIs correctly final String[] encoded = new String[values.length]; diff --git a/common/src/main/java/org/onap/so/listener/ListenerRunner.java b/common/src/main/java/org/onap/so/listener/ListenerRunner.java new file mode 100644 index 0000000000..a489be6070 --- /dev/null +++ b/common/src/main/java/org/onap/so/listener/ListenerRunner.java @@ -0,0 +1,56 @@ +/*- + * ============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.listener; + +import java.lang.annotation.Annotation; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.Priority; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; + +public abstract class ListenerRunner { + + @Autowired + protected ApplicationContext context; + + public <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) { + return validators.stream().filter(item -> { + return !item.getClass().isAnnotationPresent(Skip.class) && predicate.test(item); + }).sorted(Comparator.comparing(item -> { + Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() { + public int value() { + return 1000; + } + + @Override + public Class<? extends Annotation> annotationType() { + return Priority.class; + } + }); + return p.value(); + })).collect(Collectors.toList()); + } + +} diff --git a/common/src/main/java/org/onap/so/listener/Skip.java b/common/src/main/java/org/onap/so/listener/Skip.java new file mode 100644 index 0000000000..aa3ec2a204 --- /dev/null +++ b/common/src/main/java/org/onap/so/listener/Skip.java @@ -0,0 +1,29 @@ +/*- + * ============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.listener; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Skip { + +} diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java index 9fceed1641..a72229a25c 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java @@ -57,6 +57,9 @@ public class RequestParameters implements Serializable { @JsonProperty("rebuildVolumeGroups") private Boolean rebuildVolumeGroups; + @JsonProperty("enforceValidNfValues") + private Boolean enforceValidNfValues = false; + @Override public String toString() { return new ToStringBuilder(this).append("subscriptionServiceType", subscriptionServiceType) @@ -64,7 +67,15 @@ public class RequestParameters implements Serializable { .append("usePreload", usePreload).append("autoBuildVfModules", autoBuildVfModules) .append("cascadeDelete", cascadeDelete).append("testApi", testApi) .append("retainAssignments", retainAssignments).append("rebuildVolumeGroups", rebuildVolumeGroups) - .toString(); + .append("enforceValidNfValues", enforceValidNfValues).toString(); + } + + public Boolean getEnforceValidNfValues() { + return enforceValidNfValues; + } + + public void setEnforceValidNfValues(Boolean enforceValidNfValues) { + this.enforceValidNfValues = enforceValidNfValues; } public String getSubscriptionServiceType() { diff --git a/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java b/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java new file mode 100644 index 0000000000..e43b431821 --- /dev/null +++ b/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java @@ -0,0 +1,46 @@ +package org.onap.so.utils; + +import java.security.GeneralSecurityException; +import org.camunda.bpm.client.ExternalTaskClient; +import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; +import org.camunda.bpm.client.interceptor.auth.BasicAuthProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class ExternalTaskServiceUtils { + + @Autowired + public Environment env; + + private static final Logger logger = LoggerFactory.getLogger(ExternalTaskServiceUtils.class); + + public ExternalTaskClient createExternalTaskClient() throws Exception { + String auth = getAuth(); + ClientRequestInterceptor interceptor = createClientInterceptor(auth); + return ExternalTaskClient.create().baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1) + .addInterceptor(interceptor).asyncResponseTimeout(120000).build(); + } + + protected ClientRequestInterceptor createClientInterceptor(String auth) { + return new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); + } + + protected String getAuth() throws Exception { + try { + return CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); + } catch (IllegalStateException | GeneralSecurityException e) { + logger.error("Error Decrypting Password", e); + throw new Exception("Cannot load password"); + } + } + + public int getMaxClients() { + return Integer.parseInt(env.getProperty("workflow.topics.maxClients", "3")); + } + + +} diff --git a/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java b/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java new file mode 100644 index 0000000000..349767fc5b --- /dev/null +++ b/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java @@ -0,0 +1,46 @@ +package org.onap.so.utils; + +import org.camunda.bpm.client.task.ExternalTask; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public abstract class ExternalTaskUtils { + + @Autowired + Environment env; + + private static final Logger logger = LoggerFactory.getLogger(ExternalTaskUtils.class); + + public long calculateRetryDelay(int currentRetries) { + int retrySequence = getRetrySequence().length - currentRetries; + return Integer.parseInt(getRetrySequence()[retrySequence]) * getRetryMutiplier(); + } + + protected Long getRetryMutiplier() { + return Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000")); + } + + protected String[] getRetrySequence() { + String[] seq = {"1", "1", "2", "3", "5", "8", "13", "20"}; + if (env.getProperty("mso.workflow.topics.retrySequence") != null) { + seq = env.getProperty("mso.workflow.topics.retrySequence", String[].class); + } + return seq; + } + + protected void setupMDC(ExternalTask externalTask) { + logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); + String msoRequestId = externalTask.getVariable("mso-request-id"); + if (msoRequestId != null && !msoRequestId.isEmpty()) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); + } + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, externalTask.getTopicName()); + } + +} diff --git a/common/src/main/java/org/onap/so/utils/TargetEntities.java b/common/src/main/java/org/onap/so/utils/TargetEntities.java index 94385ec8ea..67016a1fa9 100644 --- a/common/src/main/java/org/onap/so/utils/TargetEntities.java +++ b/common/src/main/java/org/onap/so/utils/TargetEntities.java @@ -20,6 +20,8 @@ package org.onap.so.utils; -public interface TargetEntities { +import java.io.Serializable; + +public interface TargetEntities extends Serializable { } 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 1c49c11382..b07d893adb 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 @@ -24,6 +24,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -32,12 +33,14 @@ import static org.mockito.Mockito.verify; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; +import javax.ws.rs.core.GenericType; 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; @@ -46,7 +49,6 @@ import org.onap.so.client.aai.entities.singletransaction.SingleTransactionReques 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.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; @@ -60,11 +62,13 @@ public class AAISingleTransactionClientTest { private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/singletransaction/"; AAIResourceUri uriA = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "pserver-hostname"); AAIResourceUri uriB = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, "my-complex"); + AAIResourceUri uriC = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, "my-complex2"); ObjectMapper mapper; public AAIClient client = new AAIClient(); + @Spy public AAIResourcesClient aaiClient = new AAIResourcesClient(); @Before @@ -82,9 +86,11 @@ public class AAISingleTransactionClientTest { pserver2.setFqdn("patched-fqdn"); Complex complex = new Complex(); complex.setCity("my-city"); - AAISingleTransactionClient singleTransaction = - aaiClient.beginSingleTransaction().create(uriA, pserver).update(uriA, pserver2).create(uriB, complex); - + Map<String, Object> map = new HashMap<>(); + map.put("resource-version", "1234"); + doReturn(Optional.of(map)).when(aaiClient).get(any(GenericType.class), eq(uriC)); + AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction().create(uriA, pserver) + .update(uriA, pserver2).create(uriB, complex).delete(uriC); SingleTransactionRequest actual = singleTransaction.getRequest(); 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 adbdbb419f..305cdf59cc 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 @@ -22,6 +22,7 @@ package org.onap.so.client.aai; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -31,19 +32,19 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import javax.ws.rs.core.GenericType; 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; @@ -61,11 +62,13 @@ public class AAITransactionalClientTest { AAIResourceUri uriD = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test4"); AAIResourceUri uriE = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test5"); AAIResourceUri uriF = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test6"); + AAIResourceUri uriG = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test7"); ObjectMapper mapper; public AAIClient client = new AAIClient(); + @Spy public AAIResourcesClient aaiClient = new AAIResourcesClient(); @Before @@ -95,9 +98,12 @@ public class AAITransactionalClientTest { List<AAIResourceUri> uris = new ArrayList<AAIResourceUri>(); uris.add(uriB); + Map<String, Object> map = new HashMap<>(); + map.put("resource-version", "1234"); + doReturn(Optional.of(map)).when(aaiClient).get(any(GenericType.class), eq(uriG)); AAIResourceUri uriAClone = uriA.clone(); AAITransactionalClient transactions = aaiClient.beginTransaction().connect(uriA, uris).connect(uriC, uriD) - .beginNewTransaction().connect(uriE, uriF); + .beginNewTransaction().connect(uriE, uriF).beginNewTransaction().delete(uriG); String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions()); Map<String, Object> actual = diff --git a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java index 5fa2ff0295..b91d0e705a 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java @@ -91,6 +91,13 @@ public class AAIValidatorTest { } @Test + public void test_IsPhysicalServerLocked_NoServers_False() throws IOException { + when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(null); + boolean locked = validator.isPhysicalServerLocked(vnfName); + assertEquals(false, locked); + } + + @Test public void test_IsVNFLocked_False() { when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(false)); boolean locked = validator.isVNFLocked(vnfName); 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 index 6e55fe17fa..fb45652d53 100644 --- a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java +++ b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.onap.so.client.graphinventory.entities.DSLNode; +import org.onap.so.client.graphinventory.entities.DSLNodeKey; import org.onap.so.client.graphinventory.entities.DSLQueryBuilder; import org.onap.so.client.graphinventory.entities.__; @@ -108,4 +109,40 @@ public class DSLQueryBuilderTest { builder.equals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')")); assertTrue(builder.equals(builder)); } + + + @Test + public void mixedTypeTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION, + __.key("cloud-owner", "owner"), __.key("cloud-region-id", "id"))); + builder.to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", 167), __.key("my-boolean", true)).output()); + assertTrue(builder.equals( + "cloud-region('cloud-owner', 'owner')('cloud-region-id', 'id') > vlan-tag*('vlan-id-outer', 167)('my-boolean', true)")); + } + + @Test + public void outputOnNodeLambdasTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = + new DSLQueryBuilder<>(new DSLNode(AAIObjectType.L_INTERFACE, new DSLNodeKey("interface-id", "myId"))); + + builder.to(AAIObjectType.VSERVER, __.key("vserver-name", "myName")).output().to(AAIObjectType.P_INTERFACE) + .output(); + assertEquals("l-interface('interface-id', 'myId') > vserver*('vserver-name', 'myName') > p-interface*", + builder.build()); + } + + @Test + public void skipOutputOnUnionTest() { + 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()))) + .output(); + + assertEquals( + "generic-vnf*('vnf-id', 'vnfId') > " + "[ pserver* > complex*, " + "vserver > pserver* > complex* ]", + builder.build()); + } } diff --git a/common/src/test/java/org/onap/so/utils/ExternalTaskServiceUtilsTest.java b/common/src/test/java/org/onap/so/utils/ExternalTaskServiceUtilsTest.java new file mode 100644 index 0000000000..b2db986d02 --- /dev/null +++ b/common/src/test/java/org/onap/so/utils/ExternalTaskServiceUtilsTest.java @@ -0,0 +1,61 @@ +package org.onap.so.utils; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import org.camunda.bpm.client.ExternalTaskClient; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.core.env.Environment; + +@RunWith(MockitoJUnitRunner.class) +public class ExternalTaskServiceUtilsTest { + + @Spy + @InjectMocks + private ExternalTaskServiceUtils utils = new ExternalTaskServiceUtils(); + + @Mock + private Environment mockEnv; + + @Mock + private ExternalTaskClient mockClient; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + doReturn("3").when(mockEnv).getProperty("workflow.topics.maxClients", "3"); + doReturn("07a7159d3bf51a0e53be7a8f89699be7").when(mockEnv).getRequiredProperty("mso.msoKey"); + doReturn("6B466C603A260F3655DBF91E53CE54667041C01406D10E8CAF9CC24D8FA5388D06F90BFE4C852052B436").when(mockEnv) + .getRequiredProperty("mso.auth"); + doReturn("someid").when(mockEnv).getRequiredProperty("mso.config.cadi.aafId"); + doReturn("http://camunda.com").when(mockEnv).getRequiredProperty("mso.workflow.endpoint"); + } + + @Test + public void testCreateExternalTaskClient() throws Exception { + ExternalTaskClient actualClient = utils.createExternalTaskClient(); + Assert.assertNotNull(actualClient); + } + + @Test + public void testGetAuth() throws Exception { + String actual = utils.getAuth(); + String expected = "Att32054Life!@"; + assertEquals(expected, actual); + } + + @Test + public void testGetMaxClients() throws Exception { + int actual = utils.getMaxClients(); + int expected = 3; + assertEquals(expected, actual); + } + +} diff --git a/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java b/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java new file mode 100644 index 0000000000..f918781b39 --- /dev/null +++ b/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java @@ -0,0 +1,65 @@ +package org.onap.so.utils; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.core.env.Environment; + +@RunWith(MockitoJUnitRunner.class) +public class ExternalTaskUtilsTest { + + @Mock + private Environment mockenv; + + @InjectMocks + private ExternalTaskUtils externalTaskUtilsAnony = new ExternalTaskUtils() { + + }; + + @Test + public void retry_sequence_calculation_Test() { + Mockito.when(mockenv.getProperty("mso.workflow.topics.retryMultiplier", "6000")).thenReturn("6000"); + long firstRetry = externalTaskUtilsAnony.calculateRetryDelay(8); + assertEquals(6000L, firstRetry); + long secondRetry = externalTaskUtilsAnony.calculateRetryDelay(7); + assertEquals(6000L, secondRetry); + long thirdRetry = externalTaskUtilsAnony.calculateRetryDelay(6); + assertEquals(12000L, thirdRetry); + long fourthRetry = externalTaskUtilsAnony.calculateRetryDelay(5); + assertEquals(18000L, fourthRetry); + long fifthRetry = externalTaskUtilsAnony.calculateRetryDelay(4); + assertEquals(30000L, fifthRetry); + long sixRetry = externalTaskUtilsAnony.calculateRetryDelay(3); + assertEquals(48000L, sixRetry); + long seventhRetry = externalTaskUtilsAnony.calculateRetryDelay(2); + assertEquals(78000L, seventhRetry); + long eigthRetry = externalTaskUtilsAnony.calculateRetryDelay(1); + assertEquals(120000L, eigthRetry); + } + + @Test + public void retry_sequence_Test() { + Mockito.when(mockenv.getProperty("mso.workflow.topics.retryMultiplier", "6000")).thenReturn("6000"); + long firstRetry = externalTaskUtilsAnony.calculateRetryDelay(8); + assertEquals(6000L, firstRetry); + long secondRetry = externalTaskUtilsAnony.calculateRetryDelay(7); + assertEquals(6000L, secondRetry); + long thirdRetry = externalTaskUtilsAnony.calculateRetryDelay(6); + assertEquals(12000L, thirdRetry); + long fourthRetry = externalTaskUtilsAnony.calculateRetryDelay(5); + assertEquals(18000L, fourthRetry); + long fifthRetry = externalTaskUtilsAnony.calculateRetryDelay(4); + assertEquals(30000L, fifthRetry); + long sixRetry = externalTaskUtilsAnony.calculateRetryDelay(3); + assertEquals(48000L, sixRetry); + long seventhRetry = externalTaskUtilsAnony.calculateRetryDelay(2); + assertEquals(78000L, seventhRetry); + long eigthRetry = externalTaskUtilsAnony.calculateRetryDelay(1); + assertEquals(120000L, eigthRetry); + } + +} diff --git a/common/src/test/resources/__files/aai/bulkprocess/test-request.json b/common/src/test/resources/__files/aai/bulkprocess/test-request.json index f5ffe38285..5a2953c632 100644 --- a/common/src/test/resources/__files/aai/bulkprocess/test-request.json +++ b/common/src/test/resources/__files/aai/bulkprocess/test-request.json @@ -18,5 +18,9 @@ "related-link" : "/cloud-infrastructure/pservers/pserver/test6" } } ] - } ] + }, { + "delete" : [ { + "uri" : "/network/generic-vnfs/generic-vnf/test7?resource-version=1234" + } ] + }] }
\ No newline at end of file diff --git a/common/src/test/resources/__files/aai/singletransaction/sample-request.json b/common/src/test/resources/__files/aai/singletransaction/sample-request.json index f0761a07b6..69024dca83 100644 --- a/common/src/test/resources/__files/aai/singletransaction/sample-request.json +++ b/common/src/test/resources/__files/aai/singletransaction/sample-request.json @@ -21,6 +21,12 @@ "body": { "city": "my-city" } + }, + { + "action": "delete", + "uri": "/cloud-infrastructure/complexes/complex/my-complex2?resource-version=1234", + "body" : { + } } ] }
\ No newline at end of file |