diff options
Diffstat (limited to 'mso-api-handlers')
120 files changed, 6918 insertions, 1359 deletions
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java index e6e81671cf..5dd99f51cd 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java @@ -29,7 +29,6 @@ import java.util.UUID; import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -38,8 +37,6 @@ import org.onap.so.apihandler.camundabeans.CamundaInput; import org.onap.so.apihandler.camundabeans.CamundaIntegerInput; import org.onap.so.apihandler.camundabeans.CamundaRequest; import org.onap.so.apihandler.camundabeans.CamundaVIDRequest; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -60,7 +57,7 @@ public class CamundaClient extends RequestClient { @Override public HttpResponse post(String camundaReqXML, String requestId, String requestTimeout, String schemaVersion, - String serviceInstanceId, String action) throws ClientProtocolException, IOException { + String serviceInstanceId, String action) throws IOException { HttpPost post = new HttpPost(url); logger.debug(CAMUNDA_URL_MESAGE + url); String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion); @@ -83,44 +80,18 @@ public class CamundaClient extends RequestClient { private void setupHeaders(HttpPost post) { post.addHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); post.addHeader(ONAPLogConstants.Headers.INVOCATION_ID, UUID.randomUUID().toString()); - - String encryptedCredentials = null; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } + addAuthorizationHeader(post); } @Override - public HttpResponse post(String jsonReq) throws ClientProtocolException, IOException { + public HttpResponse post(String jsonReq) throws IOException { HttpPost post = new HttpPost(url); logger.debug(CAMUNDA_URL_MESAGE + url); StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); setupHeaders(post); - - String encryptedCredentials = null; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } - - + addAuthorizationHeader(post); post.setEntity(input); HttpResponse response = client.execute(post); logger.debug(CAMUNDA_RESPONSE, response); @@ -128,7 +99,7 @@ public class CamundaClient extends RequestClient { return response; } - public HttpResponse post(RequestClientParameter parameterObject) throws ClientProtocolException, IOException { + public HttpResponse post(RequestClientParameter parameterObject) throws IOException { HttpPost post = new HttpPost(url); logger.debug(CAMUNDA_URL_MESAGE + url); String jsonReq = wrapVIDRequest(parameterObject.getRequestId(), parameterObject.isBaseVfModule(), @@ -143,23 +114,8 @@ public class CamundaClient extends RequestClient { StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); - - setupHeaders(post); - - String encryptedCredentials = null; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } - + addAuthorizationHeader(post); post.setEntity(input); HttpResponse response = client.execute(post); logger.debug(CAMUNDA_RESPONSE, response); @@ -203,8 +159,7 @@ public class CamundaClient extends RequestClient { jsonReq = mapper.writeValueAsString(camundaRequest); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapRequest", - ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); + logger.error("Error in APIH Warp request", e); } return jsonReq; } @@ -242,7 +197,6 @@ public class CamundaClient extends RequestClient { CamundaInput recipeParamsInput = new CamundaInput(); CamundaInput instanceGroupIdInput = new CamundaInput(); - // host.setValue(parseURL()); requestIdInput.setValue(StringUtils.defaultString(requestId)); isBaseVfModuleInput.setValue(isBaseVfModule); recipeTimeoutInput.setValue(recipeTimeout); @@ -295,8 +249,7 @@ public class CamundaClient extends RequestClient { jsonReq = mapper.writeValueAsString(camundaRequest); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest", - ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); + logger.error("Error in APIH Warp request", e); } return jsonReq; } @@ -312,4 +265,19 @@ public class CamundaClient extends RequestClient { } return host; } + + private void addAuthorizationHeader(HttpPost post) { + String encryptedCredentials; + if (props != null) { + encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); + if (encryptedCredentials != null) { + String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, + props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); + if (userCredentials != null) { + post.addHeader(AUTHORIZATION, + BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); + } + } + } + } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java index ad8cc3f250..e2ea021811 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java @@ -52,7 +52,7 @@ public class PathResourceResolver implements LSResourceResolver { try { stream = new FileInputStream(path + systemId); } catch (FileNotFoundException e) { - logger.debug("Could not resolve resource based on file: {}", path + systemId, e); + logger.debug("Could not resolve resource based on file: ", e); } input.setPublicId(publicId); diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java index 9b7801711f..318b3ba5af 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java @@ -25,7 +25,6 @@ package org.onap.so.apihandler.common; import java.io.IOException; import java.security.GeneralSecurityException; import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; @@ -70,22 +69,12 @@ public abstract class RequestClient { public abstract HttpResponse post(String request, String requestId, String requestTimeout, String schemaVersion, String serviceInstanceId, String action) throws IOException; - public abstract HttpResponse post(String request) throws ClientProtocolException, IOException; + public abstract HttpResponse post(String request) throws IOException; - public abstract HttpResponse post(RequestClientParameter parameterObject) - throws ClientProtocolException, IOException; + public abstract HttpResponse post(RequestClientParameter parameterObject) throws IOException; public abstract HttpResponse get() throws IOException; - protected String decryptPropValue(String prop, String defaultValue, String encryptionKey) { - try { - return CryptoUtils.decrypt(prop, encryptionKey); - } catch (GeneralSecurityException e) { - logger.debug("Security exception", e); - } - return defaultValue; - } - protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) { try { return CryptoUtils.decrypt(prop, encryptionKey); diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java index 4149d5ee45..c2ffa7e004 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java @@ -4,6 +4,9 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * * 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 @@ -20,9 +23,7 @@ package org.onap.so.apihandler.common; - - -import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -34,7 +35,7 @@ public class RequestClientFactory { private Environment env; // based on URI, returns BPEL, CamundaTask or Camunda client - public RequestClient getRequestClient(String orchestrationURI) throws IllegalStateException { + public RequestClient getRequestClient(String orchestrationURI) { RequestClient retClient; String url; @@ -45,7 +46,7 @@ public class RequestClientFactory { url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI; retClient = new CamundaClient(); } - retClient.setClient(new DefaultHttpClient()); + retClient.setClient(HttpClientBuilder.create().build()); retClient.setProps(env); retClient.setUrl(url); return retClient; diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java index b972f7e1db..2b08d1130f 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java @@ -32,8 +32,6 @@ import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.commons.io.IOUtils; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; @@ -94,8 +92,7 @@ public class XMLValidator { return "ErrorDetails: " + e.getMessage(); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_CANNOT_READ_SCHEMA.toString(), ErrorCode.SchemaError.getValue(), - "APIH cannot read schema file", e); + logger.error("APIH cannot read schema file", e); return "ErrorDetails: " + "Unable to read the schema file"; } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java index 399e0650f9..a1c1dd1cc4 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java @@ -52,7 +52,7 @@ public class RequestIdFilter implements ContainerRequestFilter { if (infraActiveRequests != null) { MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(HttpStatus.SC_BAD_REQUEST)); - logger.error("RequestID exists in RequestDB.InfraActiveRequests : " + requestId); + logger.error("RequestID exists in RequestDB.InfraActiveRequests : {}", requestId); } } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/ResponseUpdateFilter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/ResponseUpdateFilter.java new file mode 100644 index 0000000000..eb52625bb6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/ResponseUpdateFilter.java @@ -0,0 +1,103 @@ +/*- + * ============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.apihandler.filters; + +import java.io.IOException; +import java.sql.Timestamp; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import javax.ws.rs.ext.Providers; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +@Provider +@ResponseUpdater +public class ResponseUpdateFilter implements ContainerResponseFilter { + + protected static Logger logger = LoggerFactory.getLogger(ResponseUpdateFilter.class); + + @Context + private HttpServletRequest httpServletRequest; + + @Context + private Providers providers; + + @Autowired + protected RequestsDbClient infraActiveRequestsClient; + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { + try { + logger.info("updating requests status"); + updateRequestDBToFailed(responseContext); + } catch (Exception e) { + logger.warn("Error in outgoing JAX-RS Inteceptor updating request db to failed", e); + } + } + + private void updateRequestDBToFailed(ContainerResponseContext responseContext) { + String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + if (requestId != null && !Response.Status.Family.familyOf(responseContext.getStatus()) + .equals(Response.Status.Family.SUCCESSFUL)) { + InfraActiveRequests currentRequest = infraActiveRequestsClient.getInfraActiveRequestbyRequestId(requestId); + if (currentRequest != null) { + Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); + RequestError error; + try { + error = (RequestError) responseContext.getEntity(); + } catch (Exception e) { + logger.warn("Error Casting Entity to Request Error, generating unknown Error", e); + error = new RequestError(); + ServiceException serviceException = new ServiceException(); + serviceException.setText("Unknown Error Occured during processing"); + error.setServiceException(serviceException); + } + if (error.getServiceException() != null && error.getServiceException().getText() != null + && !error.getServiceException().getText().isEmpty()) { + currentRequest.setStatusMessage(error.getServiceException().getText()); + } else { + currentRequest.setStatusMessage("Unknown Error Occured during processing"); + } + currentRequest.setRequestStatus(Status.FAILED.toString()); + currentRequest.setEndTime(endTimeStamp); + currentRequest.setProgress(100L); + infraActiveRequestsClient.updateInfraActiveRequests(currentRequest); + } + } + } +} + diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/ResponseUpdater.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/ResponseUpdater.java new file mode 100644 index 0000000000..eb2dad03f3 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/ResponseUpdater.java @@ -0,0 +1,34 @@ +/*- + * ============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.apihandler.filters; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.ws.rs.NameBinding; + + +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface ResponseUpdater { +} diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java index 77dbff9ebb..6957e1fe73 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -24,5 +24,27 @@ package org.onap.so.apihandlerinfra; * Enum for Status values returned by API Handler to Tail-F */ public enum Action implements Actions { - createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers + createInstance, + updateInstance, + deleteInstance, + configureInstance, + replaceInstance, + activateInstance, + deactivateInstance, + enablePort, + disablePort, + addRelationships, + removeRelationships, + inPlaceSoftwareUpdate, + applyUpdatedConfig, + completeTask, + assignInstance, + unassignInstance, + compareModel, + scaleInstance, + deactivateAndCloudDelete, + scaleOut, + recreateInstance, + addMembers, + removeMembers } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java index 3b977639fc..66b86a6961 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java @@ -37,16 +37,14 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.RequestError; import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @Provider public class ApiExceptionMapper implements ExceptionMapper<ApiException> { @@ -134,8 +132,7 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { } catch (JsonProcessingException | JAXBException e) { String errorMsg = "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage(); - logger.error("{} {} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), "BuildServiceErrorResponse", - ErrorCode.DataError.getValue(), errorMsg, e); + logger.error("BuildServiceErrorResponse", e); return errorMsg; } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java index 21e9b44b19..42198e2d0c 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java @@ -30,6 +30,7 @@ public class DuplicateRequestException extends ApiException { } + public static class Builder extends ApiException.Builder<Builder> { diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RecipeNotFoundException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RecipeNotFoundException.java index 620103be4e..3b62e318e4 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RecipeNotFoundException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RecipeNotFoundException.java @@ -27,6 +27,7 @@ public class RecipeNotFoundException extends ApiException { super(builder); } + public static class Builder extends ApiException.Builder<Builder> { diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java new file mode 100644 index 0000000000..86b12ae8f6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019 Samsung. 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.apihandler.common; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class RequestClientTest { + + private static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; + + private RequestClient requestClient; + + @Before + public void init() { + requestClient = Mockito.mock(RequestClient.class, Mockito.CALLS_REAL_METHODS); + } + + @Test + public void getEncryptedPropValueWithSuccess() { + + String encryptedValue = requestClient.getEncryptedPropValue( + "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE", + "defaultValue", ENCRYPTION_KEY); + + Assert.assertEquals("apihBpmn:camunda-R1512!", encryptedValue); + } + + @Test + public void getDefaultEncryptedPropValue() { + + String encryptedValue = + requestClient.getEncryptedPropValue("012345678901234567890123456789", "defaultValue", ENCRYPTION_KEY); + + Assert.assertEquals("defaultValue", encryptedValue); + } + +} diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java index 6c674db9f4..9bf83153b3 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.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.apihandler.filters; import static org.junit.Assert.assertEquals; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java index 77dbff9ebb..d0302f2e59 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -20,9 +20,30 @@ package org.onap.so.apihandlerinfra; -/* - * Enum for Status values returned by API Handler to Tail-F - */ + public enum Action implements Actions { - createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers + createInstance, + updateInstance, + deleteInstance, + configureInstance, + replaceInstance, + replaceInstanceRetainAssignments, + activateInstance, + deactivateInstance, + enablePort, + disablePort, + addRelationships, + removeRelationships, + inPlaceSoftwareUpdate, + applyUpdatedConfig, + completeTask, + assignInstance, + unassignInstance, + compareModel, + scaleInstance, + deactivateAndCloudDelete, + scaleOut, + recreateInstance, + addMembers, + removeMembers } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java index bc1972a593..5beb4810ec 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java @@ -21,17 +21,18 @@ package org.onap.so.apihandlerinfra; import java.util.concurrent.Executor; -import org.springframework.beans.factory.annotation.Autowired; +import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; @SpringBootApplication(scanBasePackages = {"org.onap"}) @EnableAsync +@EnableScheduling public class ApiHandlerApplication { @Value("${mso.async.core-pool-size}") @@ -53,6 +54,7 @@ public class ApiHandlerApplication { public static void main(String[] args) { SpringApplication.run(ApiHandlerApplication.class, args); + java.security.Security.setProperty("networkaddress.cache.ttl", "10"); System.getProperties().setProperty("mso.db", "MARIADB"); System.getProperties().setProperty("server.name", "Springboot"); setLogsDir(); @@ -69,4 +71,5 @@ public class ApiHandlerApplication { executor.initialize(); return executor; } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index 3996d511a7..835a24c4ce 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java @@ -38,6 +38,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONObject; @@ -228,8 +229,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString()); return response; @@ -280,8 +281,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); return resp; } @@ -306,7 +307,7 @@ public class E2EServiceInstances { try { operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Request DB - Infra Request Lookup", e); Response response = @@ -321,8 +322,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT, MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB", ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from RequestDB when searching by serviceId"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; @@ -350,8 +351,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -375,8 +376,8 @@ public class E2EServiceInstances { return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -414,8 +415,9 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug("End of the transaction, the final response is: " + resp.getEntity()); return resp; } @@ -424,8 +426,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -455,8 +457,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -473,8 +475,8 @@ public class E2EServiceInstances { if (requestId != null) { logger.debug("Logging failed message to the database"); } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -483,7 +485,7 @@ public class E2EServiceInstances { try { recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), @@ -495,8 +497,8 @@ public class E2EServiceInstances { } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -530,8 +532,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; @@ -541,8 +544,8 @@ public class E2EServiceInstances { Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; } @@ -572,8 +575,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -590,8 +593,8 @@ public class E2EServiceInstances { if (requestId != null) { logger.debug("Logging failed message to the database"); } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -600,7 +603,7 @@ public class E2EServiceInstances { try { recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), @@ -610,8 +613,8 @@ public class E2EServiceInstances { } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -644,8 +647,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -654,8 +658,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -684,8 +688,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -695,7 +699,7 @@ public class E2EServiceInstances { // TODO Get the service template model version uuid from AAI. recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, @@ -708,8 +712,8 @@ public class E2EServiceInstances { return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", @@ -747,8 +751,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine", e); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -757,8 +762,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -790,8 +795,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), - ErrorCode.BusinessProcesssError.getValue(), + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), + requestClient.getUrl(), ErrorCode.BusinessProcesssError.getValue(), "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java index 4d283f26b1..3d4b2c76fb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java @@ -25,6 +25,7 @@ package org.onap.so.apihandlerinfra; import java.net.URI; import java.util.Collections; +import org.onap.so.logger.LoggingAnchor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -112,7 +113,7 @@ public class GlobalHealthcheckHandler { try { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); // set APIH status, this is the main entry point rsp.setApih(HealthcheckStatus.UP.toString()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index c1f55c7555..c582e429ff 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -253,7 +253,7 @@ public class InstanceManagement { if (workflow == null) { return null; } else { - String workflowName = workflow.getArtifactName(); + String workflowName = workflow.getName(); recipeUri = "/mso/async/services/" + workflowName; } return new RecipeLookupResult(recipeUri, 180); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java index 7c0d327db7..00d36b3ff9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java @@ -27,6 +27,16 @@ import org.glassfish.jersey.servlet.ServletProperties; import org.onap.so.apihandler.filters.RequestIdFilter; import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper; +import org.onap.so.apihandlerinfra.infra.rest.Network; +import org.onap.so.apihandlerinfra.infra.rest.ServiceInstance; +import org.onap.so.apihandlerinfra.infra.rest.VfModules; +import org.onap.so.apihandlerinfra.infra.rest.Vnf; +import org.onap.so.apihandlerinfra.infra.rest.Volumes; +import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.AAIEntityNotFoundMapper; +import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.CloudConfigurationNotFoundMapper; +import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.NoRecipeExceptionMapper; +import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.RequestConflictMapper; +import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.WorkflowEngineConnectionMapper; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.ModelDistributionRequest; @@ -50,6 +60,11 @@ public class JerseyConfiguration extends ResourceConfig { register(CloudOrchestration.class); register(CloudResourcesOrchestration.class); register(OrchestrationRequests.class); + register(VfModules.class); + register(Vnf.class); + register(Network.class); + register(Volumes.class); + register(ServiceInstance.class); register(JaxRsFilterLogging.class); register(ManualTasks.class); register(TasksHandler.class); @@ -63,6 +78,11 @@ public class JerseyConfiguration extends ResourceConfig { register(WorkflowSpecificationsHandler.class); register(InstanceManagement.class); register(ResumeOrchestrationRequest.class); + register(AAIEntityNotFoundMapper.class); + register(CloudConfigurationNotFoundMapper.class); + register(NoRecipeExceptionMapper.class); + register(RequestConflictMapper.class); + register(WorkflowEngineConnectionMapper.class); // this registration seems to be needed to get predictable // execution behavior for the above JSON Exception Mappers register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java index 3c06804594..47f978a9e2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java @@ -34,6 +34,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; @@ -91,7 +92,7 @@ public class ManualTasks { @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); long startTime = System.currentTimeMillis(); logger.debug("requestId is: {}", requestId); TasksRequest taskRequest = null; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index 401a6a9db6..cbfe927adf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -25,14 +25,12 @@ package org.onap.so.apihandlerinfra; import java.io.IOException; import java.io.StringWriter; -import java.net.URL; import java.sql.Timestamp; 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 java.util.StringTokenizer; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; @@ -44,13 +42,13 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; -import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation; import org.onap.so.apihandlerinfra.validation.CustomWorkflowValidation; import org.onap.so.apihandlerinfra.validation.InPlaceSoftwareUpdateValidation; import org.onap.so.apihandlerinfra.validation.InstanceIdMapValidation; +import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ModelInfoValidation; import org.onap.so.apihandlerinfra.validation.PlatformLOBValidation; import org.onap.so.apihandlerinfra.validation.ProjectOwningEntityValidation; @@ -68,9 +66,7 @@ import org.onap.so.apihandlerinfra.vnfbeans.VnfRequest; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; -import org.onap.so.logger.ErrorCode; import org.onap.so.logger.LogConstants; -import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.InstanceDirection; import org.onap.so.serviceinstancebeans.ModelInfo; @@ -151,8 +147,7 @@ public class MsoRequest { mapper.setSerializationInclusion(Include.NON_DEFAULT); requestErrorStr = mapper.writeValueAsString(re); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in buildServiceErrorResponse writing exceptionType to string ", e); + logger.error("Exception in buildServiceErrorResponse writing exceptionType to string ", e); } return builder.buildResponse(httpResponseCode, null, requestErrorStr, version); @@ -396,8 +391,7 @@ public class MsoRequest { aq.setRequestStatus(status.toString()); aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error("Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -437,8 +431,7 @@ public class MsoRequest { aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error("Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -465,8 +458,7 @@ public class MsoRequest { request.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), - ErrorCode.DataError.getValue(), "Exception when updating record in DB"); + logger.error("Exception when updating record in DB", e); logger.debug("Exception: ", e); } } @@ -547,8 +539,7 @@ public class MsoRequest { return null; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in domToStr", e); + logger.error("Exception in domToStr", e); } return null; } @@ -785,23 +776,4 @@ public class MsoRequest { } - public Optional<URL> buildSelfLinkUrl(String url, String requestId) { - Optional<URL> selfLinkUrl = Optional.empty(); - String version = ""; - try { - URL aUrl = new URL(url); - String aPath = aUrl.getPath(); - if (aPath.indexOf("/v") == -1) { - version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4); - } else { - version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4); - } - String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId); - selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); - } catch (Exception e) { - selfLinkUrl = Optional.empty(); // ignore - logger.info(e.getMessage()); - } - return selfLinkUrl; - } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java index fd0df1d2b0..13f1e52068 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java @@ -20,9 +20,14 @@ package org.onap.so.apihandlerinfra; public enum MsoSubsystems { - APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK( - "Openstack Adapter"), REQUESTDB( - "RequestDB Adapter"), REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter"); + APIH("API Handler"), + ASDC("ASDC Controller"), + BPMN("BPMN Infra"), + CATALOGDB("CatalogDb Adapter"), + OPENSTACK("Openstack Adapter"), + REQUESTDB("RequestDB Adapter"), + REQUESTDBATT("RequestDB Adapter ATT Svc"), + SDNC("SDNC Adapter"); private String subsystem; private MsoSubsystems(String subsystem) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java index 9810895ad9..3337c62afd 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java @@ -30,6 +30,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -57,7 +58,7 @@ public class NodeHealthcheckHandler { public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); return HEALTH_CHECK_RESPONSE; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index ff8b5d14cd..b4a3128de8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -94,8 +94,8 @@ public class OrchestrationRequests { @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@PathParam("requestId") String requestId, - @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest) - throws ApiException { + @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest, + @QueryParam("extSystemErrorSource") boolean extSystemErrorSource) throws ApiException { String apiVersion = version.substring(1); GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); @@ -142,7 +142,8 @@ public class OrchestrationRequests { throw validateException; } - Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest); + Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest, extSystemErrorSource); + if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -158,7 +159,8 @@ public class OrchestrationRequests { @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version, - @QueryParam("includeCloudRequest") boolean includeCloudRequest) throws ApiException { + @QueryParam("includeCloudRequest") boolean includeCloudRequest, + @QueryParam("extSystemErrorSource") boolean extSystemErrorSource) throws ApiException { long startTime = System.currentTimeMillis(); @@ -195,7 +197,8 @@ public class OrchestrationRequests { List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); RequestList requestList = new RequestList(); - Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest); + Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest, extSystemErrorSource); + if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -290,8 +293,8 @@ public class OrchestrationRequests { return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); } - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest) - throws ApiException { + protected Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest, + boolean extSystemErrorSource) throws ApiException { String requestBody = iar.getRequestBody(); Request request = new Request(); @@ -304,6 +307,11 @@ public class OrchestrationRequests { String flowStatusMessage = iar.getFlowStatus(); String retryStatusMessage = iar.getRetryStatusMessage(); + String originalRequestId = iar.getOriginalRequestId(); + if (originalRequestId != null) { + request.setOriginalRequestId(originalRequestId); + } + InstanceReferences ir = new InstanceReferences(); if (iar.getNetworkId() != null) ir.setNetworkInstanceId(iar.getNetworkId()); @@ -422,10 +430,19 @@ public class OrchestrationRequests { }); } + mapExtSystemErrorSourceToRequest(iar, status, extSystemErrorSource); + request.setRequestStatus(status); return request; } + protected void mapExtSystemErrorSourceToRequest(InfraActiveRequests iar, RequestStatus status, + boolean extSystemErrorSource) { + if (extSystemErrorSource) { + status.setExtSystemErrorSource(iar.getExtSystemErrorSource()); + } + } + public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData( List<org.onap.so.db.request.beans.RequestProcessingData> processingData) { List<org.onap.so.serviceinstancebeans.RequestProcessingData> addedRequestProcessingData = new ArrayList<>(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index f6fc88d559..86e2f5ce93 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -59,7 +59,10 @@ import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; +import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.catalog.beans.VfModule; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -67,6 +70,7 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RelatedInstance; import org.onap.so.serviceinstancebeans.RelatedInstanceList; @@ -92,7 +96,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; @Component -public class RequestHandlerUtils { +public class RequestHandlerUtils extends AbstractRestHandler { private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class); @@ -180,8 +184,8 @@ public class RequestHandlerUtils { ObjectMapper mapper = new ObjectMapper(); jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); - Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), - requestClientParameter.getRequestId()); + Optional<URL> selfLinkUrl = + buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); if (selfLinkUrl.isPresent()) { jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); } else { @@ -621,7 +625,8 @@ public class RequestHandlerUtils { } protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest, - String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId) { + String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId, + String originalRequestId) throws ApiException { InfraActiveRequests request = new InfraActiveRequests(); request.setRequestId(requestId); request.setStartTime(startTimeStamp); @@ -630,17 +635,96 @@ public class RequestHandlerUtils { request.setProgress(new Long(5)); request.setRequestorId(requestorId); request.setRequestStatus(Status.IN_PROGRESS.toString()); + request.setOriginalRequestId(originalRequestId); request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); if (infraActiveRequest != null) { request.setTenantId(infraActiveRequest.getTenantId()); - request.setRequestBody(infraActiveRequest.getRequestBody()); + request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId)); request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); request.setRequestScope(infraActiveRequest.getRequestScope()); - request.setServiceInstanceId(infraActiveRequest.getServiceInstanceId()); - request.setServiceInstanceName(infraActiveRequest.getServiceInstanceName()); request.setRequestAction(infraActiveRequest.getRequestAction()); + setInstanceIdAndName(infraActiveRequest, request); } return request; } + protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest, + InfraActiveRequests currentActiveRequest) throws ApiException { + String requestScope = infraActiveRequest.getRequestScope(); + try { + ModelType type = ModelType.valueOf(requestScope); + String instanceName = type.getName(infraActiveRequest); + if (instanceName == null && type.equals(ModelType.vfModule)) { + logger.error("vfModule for requestId: {} being resumed does not have an instanceName.", + infraActiveRequest.getRequestId()); + ValidateException validateException = new ValidateException.Builder( + "vfModule for requestId: " + infraActiveRequest.getRequestId() + + " being resumed does not have an instanceName.", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).build(); + updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + } + if (instanceName != null) { + type.setName(currentActiveRequest, instanceName); + } + type.setId(currentActiveRequest, type.getId(infraActiveRequest)); + } catch (IllegalArgumentException e) { + logger.error( + "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.", + requestScope); + } + } + + protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType, + String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException { + // Get VF Module-specific base module indicator + VfModule vfm = null; + String modelVersionId = modelInfo.getModelVersionId(); + Boolean isBaseVfModule = false; + + if (modelVersionId != null) { + vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); + } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { + vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), + modelInfo.getModelVersion()); + } + + if (vfm != null) { + if (vfm.getIsBase()) { + isBaseVfModule = true; + } + } else if (action == Action.createInstance || action == Action.updateInstance) { + String serviceVersionText = ""; + if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { + serviceVersionText = " with version " + sdcServiceModelVersion; + } + String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + + serviceVersionText + " not found in MSO Catalog DB"; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + throw vfModuleException; + } + return isBaseVfModule; + } + + protected ModelType getModelType(Actions action, ModelInfo modelInfo) { + if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { + return ModelType.vnf; + } else if (action == Action.addMembers || action == Action.removeMembers) { + return ModelType.instanceGroup; + } else { + return modelInfo.getModelType(); + } + } + + protected String updateRequestorIdInRequestBody(InfraActiveRequests infraActiveRequest, String newRequestorId) { + String requestBody = infraActiveRequest.getRequestBody(); + return requestBody.replaceAll( + "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))", + "$1" + newRequestorId + "$3"); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java index 6ca23a339b..32d2c50978 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -47,6 +47,8 @@ import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.logger.LogConstants; import org.onap.so.logger.MdcConstants; import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,6 +76,8 @@ public class ResumeOrchestrationRequest { @Autowired private RequestsDbClient requestsDbClient; + @Autowired + private MsoRequest msoRequest; @POST @Path("/{version:[vV][7]}/requests/{requestId}/resume") @@ -106,7 +110,7 @@ public class ResumeOrchestrationRequest { } InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest( - infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId); + infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId, requestId); if (infraActiveRequest == null) { logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); @@ -128,24 +132,26 @@ public class ResumeOrchestrationRequest { String requestBody = infraActiveRequest.getRequestBody(); Action action = Action.valueOf(infraActiveRequest.getRequestAction()); String requestId = currentActiveRequest.getRequestId(); - String serviceInstanceName = infraActiveRequest.getServiceInstanceName(); String requestScope = infraActiveRequest.getRequestScope(); - String serviceInstanceId = infraActiveRequest.getServiceInstanceId(); + String instanceName = getInstanceName(infraActiveRequest, requestScope, currentActiveRequest); + HashMap<String, String> instanceIdMap = setInstanceIdMap(infraActiveRequest, requestScope); - checkForInProgressRequest(currentActiveRequest, serviceInstanceId, requestScope, serviceInstanceName, action); + checkForInProgressRequest(currentActiveRequest, instanceIdMap, requestScope, instanceName, action); ServiceInstancesRequest sir = null; sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri); Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); - if (aLaCarte == null) { - aLaCarte = false; - } String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir); - RecipeLookupResult recipeLookupResult = serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + RecipeLookupResult recipeLookupResult = serviceInstances.getServiceInstanceOrchestrationURI(sir, action, + msoRequest.getAlacarteFlag(sir), currentActiveRequest); requestDbSave(currentActiveRequest); + if (aLaCarte == null) { + aLaCarte = setALaCarteFlagIfNull(requestScope, action); + } + RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version, infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir); @@ -153,40 +159,60 @@ public class ResumeOrchestrationRequest { recipeLookupResult.getOrchestrationURI(), requestScope); } - protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest, String serviceInstanceId, - String requestScope, String serviceInstanceName, Action action) throws ApiException { - boolean inProgress = false; - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, - serviceInstanceName, requestScope, currentActiveRequest); - if (requestInProgress != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest); + protected Boolean setALaCarteFlagIfNull(String requestScope, Action action) { + Boolean aLaCarteFlag; + if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) { + aLaCarteFlag = true; + } else { + aLaCarteFlag = false; } - if (inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, - serviceInstanceName, requestScope, requestInProgress); + return aLaCarteFlag; + } + + protected HashMap<String, String> setInstanceIdMap(InfraActiveRequests infraActiveRequest, String requestScope) { + HashMap<String, String> instanceIdMap = new HashMap<>(); + ModelType type; + try { + type = ModelType.valueOf(requestScope); + instanceIdMap.put(type.name() + "InstanceId", type.getId(infraActiveRequest)); + } catch (IllegalArgumentException e) { + logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope); } + return instanceIdMap; } - protected RecipeLookupResult serviceRecipeLookup(InfraActiveRequests currentActiveRequest, - ServiceInstancesRequest sir, Action action, Boolean aLaCarte) - throws ValidateException, RequestDbFailureException { - RecipeLookupResult recipeLookupResult = null; + protected String getInstanceName(InfraActiveRequests infraActiveRequest, String requestScope, + InfraActiveRequests currentActiveRequest) throws ValidateException, RequestDbFailureException { + ModelType type; + String instanceName = ""; try { - recipeLookupResult = serviceInstances.getServiceURI(sir, action, aLaCarte); - } catch (IOException e) { - logger.error("IOException while performing service recipe lookup", e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = - new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + type = ModelType.valueOf(requestScope); + instanceName = type.getName(infraActiveRequest); + } catch (IllegalArgumentException e) { + logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope); + ValidateException validateException = new ValidateException.Builder( + "requestScope: \"" + requestScope + "\" from request: " + infraActiveRequest.getRequestId() + + " does not match a ModelType enum.", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build(); requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); throw validateException; } - return recipeLookupResult; + return instanceName; + } + + protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest, + HashMap<String, String> instanceIdMap, String requestScope, String instanceName, Action action) + throws ApiException { + boolean inProgress = false; + InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, + requestScope, currentActiveRequest); + if (requestInProgress != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest); + } + if (inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, instanceName, + requestScope, requestInProgress); + } } protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException { @@ -204,23 +230,37 @@ public class ResumeOrchestrationRequest { protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version, InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId, - Boolean aLaCarte, ServiceInstancesRequest sir) throws ValidateException { + Boolean aLaCarte, ServiceInstancesRequest sir) throws ApiException { RequestClientParameter requestClientParameter = null; + Action action = Action.valueOf(infraActiveRequest.getRequestAction()); + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + + Boolean isBaseVfModule = false; + if (requestHandlerUtils.getModelType(action, modelInfo).equals(ModelType.vfModule)) { + isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, infraActiveRequest.getVnfType(), + msoRequest.getSDCServiceModelVersion(sir), currentActiveRequest); + } + try { - requestClientParameter = new RequestClientParameter.Builder() - .setRequestId(currentActiveRequest.getRequestId()) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(infraActiveRequest.getRequestAction()) - .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) - .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) - .setVfModuleId(infraActiveRequest.getVfModuleId()) - .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) - .setNetworkId(infraActiveRequest.getNetworkId()).setServiceType(infraActiveRequest.getServiceType()) - .setVnfType(infraActiveRequest.getVnfType()).setNetworkType(infraActiveRequest.getNetworkType()) - .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, - aLaCarte, Action.valueOf(infraActiveRequest.getRequestAction()))) - .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(currentActiveRequest.getRequestUrl()) - .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); + requestClientParameter = + new RequestClientParameter.Builder().setRequestId(currentActiveRequest.getRequestId()) + .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(infraActiveRequest.getRequestAction()) + .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) + .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) + .setVfModuleId(infraActiveRequest.getVfModuleId()) + .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) + .setNetworkId(infraActiveRequest.getNetworkId()) + .setServiceType(infraActiveRequest.getServiceType()) + .setVnfType(infraActiveRequest.getVnfType()) + .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope(), + action, Integer.parseInt(version))) + .setNetworkType(infraActiveRequest.getNetworkType()) + .setRequestDetails(requestHandlerUtils + .mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, aLaCarte, action)) + .setApiVersion(version).setALaCarte(aLaCarte) + .setRequestUri(currentActiveRequest.getRequestUrl()) + .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); } catch (IOException e) { logger.error("IOException while generating requestClientParameter to send to BPMN", e); ErrorLoggerInfo errorLoggerInfo = diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 7c8d24742d..b290a796e2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -23,12 +23,24 @@ package org.onap.so.apihandlerinfra; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.CommonConstants; @@ -38,7 +50,7 @@ import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; -import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; +import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.db.catalog.beans.NetworkResource; import org.onap.so.db.catalog.beans.NetworkResourceCustomization; @@ -74,29 +86,18 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import javax.transaction.Transactional; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; @Component @Path("/onap/so/infra/serviceInstantiation") @Api(value = "/onap/so/infra/serviceInstantiation", description = "Infrastructure API Requests for Service Instances") -public class ServiceInstances { +public class ServiceInstances extends AbstractRestHandler { private static Logger logger = LoggerFactory.getLogger(MsoRequest.class); private static String NAME = "name"; @@ -108,6 +109,9 @@ public class ServiceInstances { private Environment env; @Autowired + private RestTemplate restTemplate; + + @Autowired private CatalogDbClient catalogDbClient; @Autowired @@ -203,7 +207,7 @@ public class ServiceInstances { @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestHandlerUtils.getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); @@ -759,13 +763,13 @@ public class ServiceInstances { public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { - String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId"); + String serviceInstanceId; Boolean aLaCarte = null; - long startTime = System.currentTimeMillis(); - ServiceInstancesRequest sir = null; + ServiceInstancesRequest sir; String apiVersion = version.substring(1); sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); + action = handleReplaceInstance(action, sir); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -813,64 +817,20 @@ public class ServiceInstances { referencesResponse.setRequestId(requestId); serviceResponse.setRequestReferences(referencesResponse); - Boolean isBaseVfModule = false; - RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag); - ModelType modelType; - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { - modelType = ModelType.vnf; - } else if (action == Action.addMembers || action == Action.removeMembers) { - modelType = ModelType.instanceGroup; - } else { - modelType = modelInfo.getModelType(); - } - - if (modelType.equals(ModelType.vfModule)) { + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + ModelType modelType = requestHandlerUtils.getModelType(action, modelInfo); - // Get VF Module-specific base module indicator - VfModule vfm = null; - - String modelVersionId = modelInfo.getModelVersionId(); - - if (modelVersionId != null) { - vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); - } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { - vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), - modelInfo.getModelVersion()); - } - - if (vfm != null) { - if (vfm.getIsBase()) { - isBaseVfModule = true; - } - } else if (action == Action.createInstance || action == Action.updateInstance) { - // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in - // Catalog DB. - // This request cannot proceed - - String serviceVersionText = ""; - if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { - serviceVersionText = " with version " + sdcServiceModelVersion; - } - - String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() - + serviceVersionText + " not found in MSO Catalog DB"; - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, - HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + Boolean isBaseVfModule = false; - throw vfModuleException; - } + if (modelType.equals(ModelType.vfModule)) { + isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveReq); } - serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); String vnfId = ""; String vfModuleId = ""; @@ -939,11 +899,24 @@ public class ServiceInstances { recipeLookupResult.getOrchestrationURI(), requestScope); } + /** + * @param action + * @param sir + * @return + */ + protected Actions handleReplaceInstance(Actions action, ServiceInstancesRequest sir) { + if (action != null && action.equals(Action.replaceInstance) + && sir.getRequestDetails().getRequestParameters().getRetainAssignments() != null + && sir.getRequestDetails().getRequestParameters().getRetainAssignments()) { + action = Action.replaceInstanceRetainAssignments; + } + return action; + } + public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID); Boolean aLaCarte = true; - long startTime = System.currentTimeMillis(); String apiVersion = version.substring(1); ServiceInstancesRequest sir = new ServiceInstancesRequest(); sir.setInstanceGroupId(instanceGroupId); @@ -1015,7 +988,7 @@ public class ServiceInstances { .orElse(""); } - private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, + protected RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException { RecipeLookupResult recipeLookupResult = null; // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action @@ -1260,8 +1233,7 @@ public class ServiceInstances { return mapFlatMapToNameValue(userParams); } - private Service serviceMapper(Map<String, Object> params) - throws JsonProcessingException, IOException, JsonParseException, JsonMappingException { + private Service serviceMapper(Map<String, Object> params) throws IOException { ObjectMapper obj = new ObjectMapper(); String input = obj.writeValueAsString(params.get("service")); return obj.readValue(input, Service.class); @@ -1298,7 +1270,7 @@ public class ServiceInstances { instanceList = servInstReq.getRequestDetails().getRelatedInstanceList(); } - Recipe recipe = null; + Recipe recipe; String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq); String modelCustomizationId = modelInfo.getModelCustomizationId(); String modelCustomizationName = modelInfo.getModelCustomizationName(); @@ -1588,13 +1560,11 @@ public class ServiceInstances { private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { - String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId"); + String serviceInstanceId; Boolean aLaCarte = null; String apiVersion = version.substring(1); boolean inProgress = false; - - long startTime = System.currentTimeMillis(); - ServiceInstancesRequest sir = null; + ServiceInstancesRequest sir; sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java index c480bdfbd3..bba8064f7c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java @@ -50,6 +50,8 @@ import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; @@ -69,7 +71,9 @@ public class WorkflowSpecificationsHandler { @Autowired private CatalogDbClient catalogDbClient; + private static Logger logger = LoggerFactory.getLogger(WorkflowSpecificationsHandler.class); private static final String ARTIFACT_TYPE_WORKFLOW = "workflow"; + private static final String NATIVE_WORKFLOW = "native"; @Path("/{version:[vV]1}/workflows") @GET @@ -85,6 +89,12 @@ public class WorkflowSpecificationsHandler { mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); List<Workflow> workflows = catalogDbClient.findWorkflowByModelUUID(vnfModelVersionId); + + List<Workflow> nativeWorkflows = catalogDbClient.findWorkflowBySource(NATIVE_WORKFLOW); + if (nativeWorkflows != null && nativeWorkflows.size() != 0) { + workflows.addAll(nativeWorkflows); + } + WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows); String jsonResponse = null; @@ -153,6 +163,7 @@ public class WorkflowSpecificationsHandler { if (activitySpec != null) { ActivitySequence activitySequence = new ActivitySequence(); activitySequence.setName(activitySpec.getName()); + logger.debug("Adding activity: " + activitySpec.getName()); activitySequence.setDescription(activitySpec.getDescription()); activitySequences.add(activitySequence); } @@ -164,7 +175,7 @@ public class WorkflowSpecificationsHandler { private List<WorkflowInputParameter> buildWorkflowInputParameters(Workflow workflow) { List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = workflow.getWorkflowActivitySpecSequence(); if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.size() == 0) { - return null; + return new ArrayList<WorkflowInputParameter>(); } Map<String, WorkflowInputParameter> workflowInputParameterMap = new HashMap<String, WorkflowInputParameter>(); for (WorkflowActivitySpecSequence workflowActivitySpecSequence : workflowActivitySpecSequences) { @@ -188,7 +199,7 @@ public class WorkflowSpecificationsHandler { } if (workflowInputParameterMap.size() == 0) { - return null; + return new ArrayList<WorkflowInputParameter>(); } List<WorkflowInputParameter> workflowInputParameterList = workflowInputParameterMap.values().stream().collect(Collectors.toList()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java index 4d81695e55..0db63e7493 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java @@ -23,8 +23,8 @@ package org.onap.so.apihandlerinfra.configuration; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; @@ -32,10 +32,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jmx.export.MBeanExporter; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; @Configuration @EnableTransactionManagement @@ -44,11 +47,23 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Profile({"!test"}) public class CatalogDBConfig { + @Autowired(required = false) + private MBeanExporter mBeanExporter; + + @Bean + @ConfigurationProperties(prefix = "spring.datasource.hikari") + public HikariConfig catalogDbConfig() { + return new HikariConfig(); + } + @Primary @Bean(name = "dataSource") - @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { - return DataSourceBuilder.create().build(); + if (mBeanExporter != null) { + mBeanExporter.addExcludedBean("dataSource"); + } + HikariConfig hikariConfig = this.catalogDbConfig(); + return new HikariDataSource(hikariConfig); } @Primary diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java index 1bc54ffe7b..02cbf2f3bf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java @@ -23,18 +23,21 @@ package org.onap.so.apihandlerinfra.configuration; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jmx.export.MBeanExporter; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; @Configuration @EnableTransactionManagement @@ -43,13 +46,24 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Profile({"!test"}) public class RequestDBConfig { + @Autowired(required = false) + private MBeanExporter mBeanExporter; + + @Bean + @ConfigurationProperties(prefix = "request.datasource.hikari") + public HikariConfig requestDbConfig() { + return new HikariConfig(); + } + @Bean(name = "requestDataSource") - @ConfigurationProperties(prefix = "request.datasource") public DataSource dataSource() { - return DataSourceBuilder.create().build(); + if (mBeanExporter != null) { + mBeanExporter.addExcludedBean("requestDataSource"); + } + HikariConfig hikariConfig = this.requestDbConfig(); + return new HikariDataSource(hikariConfig); } - @Bean(name = "requestEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("requestDataSource") DataSource dataSource) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java new file mode 100644 index 0000000000..5b51d85e41 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java @@ -0,0 +1,478 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; +import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +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.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.CloudConfiguration; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.RequestParameters; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class BpmnRequestBuilder { + + private static final String CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND = "Cloud Configuration could not be found"; + + private static final String CLOUD_REGION_ID = "cloud-region-id"; + + private static final String CLOUD_OWNER = "cloud-owner"; + + private static final String TENANT_ID = "tenant-id"; + + private static final String GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID = + "Generic Vnf Not Found In Inventory, VnfId: "; + + private static final String VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID = "VF Module Not Found In Inventory, VnfId: "; + + private static final Logger logger = LoggerFactory.getLogger(BpmnRequestBuilder.class); + + @Autowired + private RequestsDbClient infraActiveRequestsClient; + + private ObjectMapper mapper = new ObjectMapper(); + + private AAIResourcesClient aaiResourcesClient; + + public ServiceInstancesRequest buildVFModuleDeleteRequest(String vnfId, String vfModuleId, ModelType modelType) + throws AAIEntityNotFound { + GenericVnf vnf = getGenericVnf(vnfId); + if (vnf == null) { + throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); + } + VfModule vfModule = getAAIVfModule(vnfId, vfModuleId); + if (vfModule == null) { + throw new AAIEntityNotFound(VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " vfModuleId: " + vfModuleId); + } + return createServiceInstancesRequest(vnf, vfModule, modelType); + } + + public ServiceInstancesRequest buildVolumeGroupDeleteRequest(String vnfId, String volumeGroupId) + throws AAIEntityNotFound { + GenericVnf vnf = getGenericVnf(vnfId); + if (vnf == null) { + throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); + } + VolumeGroup volumeGroup = getVolumeGroup(vnfId, volumeGroupId); + if (volumeGroup == null) { + throw new AAIEntityNotFound( + VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); + } + return createServiceInstancesRequest(vnf, volumeGroup); + } + + public ServiceInstancesRequest buildServiceDeleteRequest(String serviceInstanceId) throws AAIEntityNotFound { + ServiceInstance serviceInstance = getServiceInstance(serviceInstanceId); + if (serviceInstance == null) { + throw new AAIEntityNotFound( + "ServiceInstance Not Found In Inventory, ServiceInstanceId: " + serviceInstanceId); + } + return createServiceInstancesRequest(serviceInstance); + } + + public ServiceInstancesRequest buildVnfDeleteRequest(String vnfId) throws AAIEntityNotFound { + GenericVnf vnf = getGenericVnf(vnfId); + if (vnf == null) { + throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); + } + return createServiceInstancesRequest(vnf); + } + + public ServiceInstancesRequest buildNetworkDeleteRequest(String networkId) throws AAIEntityNotFound { + L3Network network = getNetwork(networkId); + if (network == null) { + throw new AAIEntityNotFound("Network Not Found In Inventory, NetworkId: " + networkId); + } + return createServiceInstancesRequest(network); + } + + protected ServiceInstancesRequest createServiceInstancesRequest(ServiceInstance serviceInstance) { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = mapServiceRequestDetails(serviceInstance); + request.setRequestDetails(requestDetails); + return request; + } + + protected ServiceInstancesRequest createServiceInstancesRequest(GenericVnf vnf) { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = mapVnfRequestDetails(vnf); + request.setRequestDetails(requestDetails); + return request; + } + + protected ServiceInstancesRequest createServiceInstancesRequest(GenericVnf vnf, VfModule vfModule, + ModelType modelType) { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = mapRequestDetails(vnf, vfModule, modelType); + request.setRequestDetails(requestDetails); + return request; + } + + protected ServiceInstancesRequest createServiceInstancesRequest(GenericVnf vnf, VolumeGroup volumeGroup) { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = mapRequestDetails(vnf, volumeGroup); + request.setRequestDetails(requestDetails); + return request; + } + + protected ServiceInstancesRequest createServiceInstancesRequest(L3Network network) { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = mapNetworkRequestDetails(network); + request.setRequestDetails(requestDetails); + return request; + } + + protected RequestDetails mapRequestDetails(GenericVnf vnf, VfModule vfModule, ModelType modelType) { + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setRequestInfo(createRequestInfo()); + if (vfModule.getVfModuleName() != null) { + requestDetails.getRequestInfo().setInstanceName(vfModule.getVfModuleName()); + } + requestDetails.setModelInfo(mapVfModuleModelInformation(vfModule, modelType)); + + requestDetails.setCloudConfiguration(mapCloudConfiguration(vnf, vfModule)); + requestDetails.setRequestParameters(createRequestParameters()); + return requestDetails; + } + + protected RequestDetails mapRequestDetails(GenericVnf vnf, VolumeGroup volumeGroup) { + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setRequestInfo(createRequestInfo()); + if (volumeGroup.getVolumeGroupName() != null) { + requestDetails.getRequestInfo().setInstanceName(volumeGroup.getVolumeGroupName()); + } + requestDetails.setModelInfo(mapVolumeGroupModelInformation(volumeGroup)); + requestDetails.setCloudConfiguration(mapCloudConfigurationVolume(vnf, volumeGroup)); + requestDetails.setRequestParameters(createRequestParameters()); + return requestDetails; + } + + protected RequestDetails mapVnfRequestDetails(GenericVnf vnf) { + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setRequestInfo(createRequestInfo()); + if (vnf.getVnfName() != null) { + requestDetails.getRequestInfo().setInstanceName(vnf.getVnfName()); + } + requestDetails.setModelInfo(mapVnfModelInformation(vnf)); + requestDetails.setRequestParameters(createRequestParameters()); + return requestDetails; + } + + protected RequestDetails mapServiceRequestDetails(ServiceInstance serviceInstance) { + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setRequestInfo(createRequestInfo()); + if (serviceInstance.getServiceInstanceName() != null) { + requestDetails.getRequestInfo().setInstanceName(serviceInstance.getServiceInstanceName()); + } + requestDetails.setModelInfo(mapServiceModelInformation(serviceInstance)); + requestDetails.setRequestParameters(createRequestParameters()); + return requestDetails; + } + + protected RequestDetails mapNetworkRequestDetails(L3Network network) { + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setRequestInfo(createRequestInfo()); + if (network.getNetworkName() != null) { + requestDetails.getRequestInfo().setInstanceName(network.getNetworkName()); + } + requestDetails.setCloudConfiguration(mapCloudConfigurationNetwork(network)); + requestDetails.setModelInfo(mapNetworkModelInformation(network)); + requestDetails.setRequestParameters(createRequestParameters()); + return requestDetails; + } + + protected ModelInfo mapVfModuleModelInformation(VfModule vfModule, ModelType modelType) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelCustomizationId(vfModule.getModelCustomizationId()); + modelInfo.setModelCustomizationUuid(vfModule.getModelCustomizationId()); + modelInfo.setModelType(modelType); + return modelInfo; + } + + protected ModelInfo mapVolumeGroupModelInformation(VolumeGroup volumeGroup) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelCustomizationId(volumeGroup.getModelCustomizationId()); + modelInfo.setModelCustomizationUuid(volumeGroup.getModelCustomizationId()); + modelInfo.setModelType(ModelType.volumeGroup); + return modelInfo; + } + + protected ModelInfo mapServiceModelInformation(ServiceInstance serviceInstance) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(serviceInstance.getModelVersionId()); + modelInfo.setModelType(ModelType.service); + return modelInfo; + } + + protected ModelInfo mapVnfModelInformation(GenericVnf vnf) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelCustomizationId(vnf.getModelCustomizationId()); + modelInfo.setModelCustomizationUuid(vnf.getModelCustomizationId()); + modelInfo.setModelType(ModelType.vnf); + return modelInfo; + } + + protected ModelInfo mapNetworkModelInformation(L3Network network) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType(ModelType.network); + modelInfo.setModelCustomizationId(network.getModelCustomizationId()); + modelInfo.setModelCustomizationUuid(network.getModelCustomizationId()); + return modelInfo; + } + + public CloudConfiguration mapCloudConfiguration(GenericVnf vnf, VfModule vfModule) { + CloudConfiguration cloudConfig = new CloudConfiguration(); + AAIResultWrapper wrapper = new AAIResultWrapper(vnf); + Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); + String tenantId = null; + String cloudOwner = null; + String lcpRegionId = null; + if (relationshipsOpt.isPresent()) { + tenantId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() + .map(item -> item.getURIKeys().get(TENANT_ID)).orElse(null); + cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() + .map(item -> item.getURIKeys().get(CLOUD_OWNER)).orElse(null); + lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() + .map(item -> item.getURIKeys().get(CLOUD_REGION_ID)).orElse(null); + } + + if (tenantId == null || cloudOwner == null || lcpRegionId == null) { + Map<String, String[]> filters = createQueryRequest("vfModuleId", vfModule.getVfModuleId()); + Optional<ServiceInstancesRequest> request = findServiceInstanceRequest(filters); + if (request.isPresent()) { + if (request.get().getRequestDetails() != null + && request.get().getRequestDetails().getCloudConfiguration() != null) { + if (request.get().getRequestDetails().getCloudConfiguration().getTenantId() != null) { + tenantId = request.get().getRequestDetails().getCloudConfiguration().getTenantId(); + } + if (request.get().getRequestDetails().getCloudConfiguration().getCloudOwner() != null) { + cloudOwner = request.get().getRequestDetails().getCloudConfiguration().getCloudOwner(); + } + if (request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId() != null) { + lcpRegionId = request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId(); + } + } + } else { + throw new CloudConfigurationNotFoundException(CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND); + } + } + cloudConfig.setTenantId(tenantId); + cloudConfig.setCloudOwner(cloudOwner); + cloudConfig.setLcpCloudRegionId(lcpRegionId); + return cloudConfig; + } + + public CloudConfiguration mapCloudConfigurationVolume(GenericVnf vnf, VolumeGroup volumeGroup) { + CloudConfiguration cloudConfig = new CloudConfiguration(); + AAIResultWrapper wrapper = new AAIResultWrapper(vnf); + Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); + String tenantId = null; + String cloudOwner = null; + String lcpRegionId = null; + if (relationshipsOpt.isPresent()) { + tenantId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() + .map(item -> item.getURIKeys().get(TENANT_ID)).orElse(null); + cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() + .map(item -> item.getURIKeys().get(CLOUD_OWNER)).orElse(null); + lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() + .map(item -> item.getURIKeys().get(CLOUD_REGION_ID)).orElse(null); + } + + if (tenantId == null || cloudOwner == null || lcpRegionId == null) { + Map<String, String[]> filters = createQueryRequest("volumeGroupId", volumeGroup.getVolumeGroupId()); + Optional<ServiceInstancesRequest> request = findServiceInstanceRequest(filters); + if (request.isPresent()) { + tenantId = request.get().getRequestDetails().getCloudConfiguration().getTenantId(); + cloudOwner = request.get().getRequestDetails().getCloudConfiguration().getCloudOwner(); + lcpRegionId = request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId(); + } else { + throw new CloudConfigurationNotFoundException(CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND); + } + } + cloudConfig.setTenantId(tenantId); + cloudConfig.setCloudOwner(cloudOwner); + cloudConfig.setLcpCloudRegionId(lcpRegionId); + return cloudConfig; + } + + public CloudConfiguration mapCloudConfigurationNetwork(L3Network network) { + CloudConfiguration cloudConfig = new CloudConfiguration(); + String tenantId = null; + String cloudOwner = null; + String lcpRegionId = null; + + Map<String, String[]> filters = createQueryRequest("networkId", network.getNetworkId()); + Optional<ServiceInstancesRequest> request = findServiceInstanceRequest(filters); + if (request.isPresent()) { + if (request.get().getRequestDetails() != null + && request.get().getRequestDetails().getCloudConfiguration() != null) { + if (request.get().getRequestDetails().getCloudConfiguration().getTenantId() != null) { + tenantId = request.get().getRequestDetails().getCloudConfiguration().getTenantId(); + } + if (request.get().getRequestDetails().getCloudConfiguration().getCloudOwner() != null) { + cloudOwner = request.get().getRequestDetails().getCloudConfiguration().getCloudOwner(); + } + if (request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId() != null) { + lcpRegionId = request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId(); + } + } + } else { + throw new CloudConfigurationNotFoundException(CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND); + } + + cloudConfig.setTenantId(tenantId); + cloudConfig.setCloudOwner(cloudOwner); + cloudConfig.setLcpCloudRegionId(lcpRegionId); + return cloudConfig; + } + + public Optional<ServiceInstancesRequest> findServiceInstanceRequest(Map<String, String[]> filters) { + List<InfraActiveRequests> completeRequests = infraActiveRequestsClient.getRequest(filters); + InfraActiveRequests foundRequest = completeRequests.get(0); + ServiceInstancesRequest siRequest; + try { + siRequest = mapper.readValue(foundRequest.getRequestBody(), ServiceInstancesRequest.class); + return Optional.of(siRequest); + } catch (Exception e) { + logger.error("Could not read Create Instance Request", e); + } + return Optional.empty(); + } + + public Map<String, String[]> createQueryRequest(String name, String instanceId) { + Map<String, String[]> filters = new HashMap<>(); + filters.put(name, new String[] {"EQ", instanceId}); + filters.put("requestStatus", new String[] {"EQ", Status.COMPLETE.toString()}); + filters.put("action", new String[] {"EQ", "createInstance"}); + return filters; + } + + public RequestInfo createRequestInfo() { + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSuppressRollback(false); + requestInfo.setSource(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + requestInfo.setRequestorId(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + return requestInfo; + } + + public RequestParameters createRequestParameters() { + RequestParameters requestParams = new RequestParameters(); + requestParams.setaLaCarte(true); + requestParams.setTestApi("GR_API"); + return requestParams; + } + + public VfModule getAAIVfModule(String vnfId, String vfModuleId) { + return this.getAaiResourcesClient() + .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) + .orElseGet(() -> { + logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); + return null; + }); + } + + public GenericVnf getGenericVnf(String vnfId) { + return this.getAaiResourcesClient() + .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) + .orElseGet(() -> { + logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); + return null; + }); + } + + public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { + GenericVnf vnf = getGenericVnf(vnfId); + AAIResultWrapper wrapper = new AAIResultWrapper(vnf); + List<AAIResourceUri> listVserverWrapper; + Optional<AAIResourceUri> volumeGroupURI; + if (wrapper.getRelationships().isPresent()) { + listVserverWrapper = wrapper.getRelationships().get().getRelatedUris(AAIObjectType.VOLUME_GROUP); + volumeGroupURI = listVserverWrapper.stream() + .filter(resourceURI -> resourceURI.getURIKeys().get("volume-group-id").equals(volumeGroupId)) + .findFirst(); + } else { + throw new AAIEntityNotFound( + VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); + } + return this.getAaiResourcesClient().get(VolumeGroup.class, volumeGroupURI.get()).orElseGet(() -> { + logger.debug("No VolumeGroup in A&AI found: {}", vnfId); + return null; + }); + } + + public ServiceInstance getServiceInstance(String serviceInstanceId) { + return this.getAaiResourcesClient() + .get(ServiceInstance.class, + AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) + .orElseGet(() -> { + logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); + return null; + }); + } + + public L3Network getNetwork(String networkId) { + return this.getAaiResourcesClient() + .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) + .orElseGet(() -> { + logger.debug("No Network found in A&AI NetworkId: {}", networkId); + return null; + }); + } + + public AAIResourcesClient getAaiResourcesClient() { + if (aaiResourcesClient == null) { + aaiResourcesClient = new AAIResourcesClient(); + } + return aaiResourcesClient; + } + + public void setAaiResourcesClient(AAIResourcesClient aaiResourcesClient) { + this.aaiResourcesClient = aaiResourcesClient; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java new file mode 100644 index 0000000000..c44f1f0e0a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java @@ -0,0 +1,91 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.filters.ResponseUpdater; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.infra.rest.handler.NetworkRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import io.swagger.annotations.ApiOperation; + +@Component +@Path("/onap/so/infra/serviceInstantiation") +public class Network { + + private static Logger logger = LoggerFactory.getLogger(Network.class); + + @Autowired + private NetworkRestHandler networkRestHandler; + + @Autowired + private BpmnRequestBuilder requestBuilder; + + @DELETE + @ResponseUpdater + @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided Network instance", response = Response.class) + @Transactional + public Response deleteNetworkInstance(@PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) + throws Exception { + InfraActiveRequests currentRequest = null; + String requestId = networkRestHandler.getRequestId(requestContext); + String requestorId = "Unknown"; + String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME); + String requestURI = requestContext.getUriInfo().getAbsolutePath().toString(); + currentRequest = networkRestHandler.createInfraActiveRequestForDelete(requestId, serviceInstanceId, + networkInstanceId, requestorId, source, requestURI); + ServiceInstancesRequest request = requestBuilder.buildNetworkDeleteRequest(networkInstanceId); + networkRestHandler.saveInstanceName(request, currentRequest); + networkRestHandler.checkDuplicateRequest(serviceInstanceId, networkInstanceId, + request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId()); + Recipe recipe = networkRestHandler.findNetworkRecipe(Action.deleteInstance.toString()); + networkRestHandler.callWorkflowEngine(networkRestHandler.buildRequestParams(request, + networkRestHandler.getRequestUri(requestContext), requestId, serviceInstanceId, networkInstanceId), + recipe.getOrchestrationUri()); + ServiceInstancesResponse response = + networkRestHandler.createResponse(networkInstanceId, requestId, requestContext); + return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java new file mode 100644 index 0000000000..bf10fcc183 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java @@ -0,0 +1,91 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.filters.ResponseUpdater; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.infra.rest.handler.ServiceInstanceRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import io.swagger.annotations.ApiOperation; + +@Component +@Path("/onap/so/infra/serviceInstantiation") +public class ServiceInstance { + + private static Logger logger = LoggerFactory.getLogger(ServiceInstance.class); + + @Autowired + private ServiceInstanceRestHandler requestHandler; + + @Autowired + private BpmnRequestBuilder requestBuilder; + + @DELETE + @ResponseUpdater + @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete a Service instance", response = ServiceInstancesResponse.class) + @Transactional + public Response deleteServiceInstance(@PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws Exception { + InfraActiveRequests currentRequest = null; + String requestId = requestHandler.getRequestId(requestContext); + String requestorId = "Unknown"; + String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME); + String requestURI = requestContext.getUriInfo().getAbsolutePath().toString(); + currentRequest = requestHandler.createInfraActiveRequestForDelete(requestId, serviceInstanceId, requestorId, + source, requestURI); + ServiceInstancesRequest request = requestBuilder.buildServiceDeleteRequest(serviceInstanceId); + requestHandler.saveInstanceName(request, currentRequest); + requestHandler.checkDuplicateRequest(serviceInstanceId, + request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId()); + Recipe recipe = requestHandler.findServiceRecipe(request.getRequestDetails().getModelInfo().getModelUuid(), + Action.deleteInstance.toString()); + requestHandler.callWorkflowEngine(requestHandler.buildRequestParams(request, + requestHandler.getRequestUri(requestContext), requestId, serviceInstanceId), + recipe.getOrchestrationUri()); + ServiceInstancesResponse response = requestHandler.createResponse(serviceInstanceId, requestId, requestContext); + return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build(); + + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java new file mode 100644 index 0000000000..1a2688f0b3 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java @@ -0,0 +1,96 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.filters.ResponseUpdater; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.infra.rest.handler.VFModuleRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import io.swagger.annotations.ApiOperation; + +@Component +@Path("/onap/so/infra/serviceInstantiation") +public class VfModules { + + private static Logger logger = LoggerFactory.getLogger(VfModules.class); + + @Autowired + private VFModuleRestHandler restHandler; + + @Autowired + private BpmnRequestBuilder requestBuilder; + + @DELETE + @ResponseUpdater + @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete a VfModule instance", response = ServiceInstancesResponse.class) + @Transactional + public Response deleteVfModuleInstance(@PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) + throws Exception { + InfraActiveRequests currentRequest = null; + + String requestId = restHandler.getRequestId(requestContext); + String requestorId = "Unknown"; + String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME); + String requestURL = requestContext.getUriInfo().getAbsolutePath().toString(); + currentRequest = restHandler.createInfraActiveRequestForDelete(requestId, vfmoduleInstanceId, serviceInstanceId, + vnfInstanceId, requestorId, source, requestURL); + ServiceInstancesRequest request = + requestBuilder.buildVFModuleDeleteRequest(vnfInstanceId, vfmoduleInstanceId, ModelType.vfModule); + restHandler.saveInstanceName(request, currentRequest); + restHandler.checkDuplicateRequest(serviceInstanceId, vnfInstanceId, vfmoduleInstanceId, + request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId()); + Recipe recipe = + restHandler.findVfModuleRecipe(request.getRequestDetails().getModelInfo().getModelCustomizationId(), + ModelType.vfModule.toString(), Action.deleteInstance.toString()); + restHandler + .callWorkflowEngine(restHandler.buildRequestParams(request, restHandler.getRequestUri(requestContext), + requestId, serviceInstanceId, vnfInstanceId, vfmoduleInstanceId), recipe.getOrchestrationUri()); + ServiceInstancesResponse response = restHandler.createResponse(vfmoduleInstanceId, requestId, requestContext); + return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build(); + + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java new file mode 100644 index 0000000000..b161713a71 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java @@ -0,0 +1,89 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.filters.ResponseUpdater; +import org.onap.so.apihandlerinfra.infra.rest.handler.VnfRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import io.swagger.annotations.ApiOperation; + +@Component +@Path("/onap/so/infra/serviceInstantiation") +public class Vnf { + + private static Logger logger = LoggerFactory.getLogger(Vnf.class); + + @Autowired + private BpmnRequestBuilder requestBuilder; + + @Autowired + private VnfRestHandler vnfRestHandler; + + @DELETE + @ResponseUpdater + @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete a Vnf instance", response = ServiceInstancesResponse.class) + @Transactional + public Response deleteVnfInstance(@PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws Exception { + InfraActiveRequests currentRequest = null; + String requestId = vnfRestHandler.getRequestId(requestContext); + String requestorId = "Unknown"; + String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME); + String requestURL = requestContext.getUriInfo().getAbsolutePath().toString(); + currentRequest = vnfRestHandler.createInfraActiveRequestForDelete(requestId, serviceInstanceId, vnfInstanceId, + requestorId, source, requestURL); + ServiceInstancesRequest request = requestBuilder.buildVnfDeleteRequest(vnfInstanceId); + vnfRestHandler.saveInstanceName(request, currentRequest); + vnfRestHandler.checkDuplicateRequest(serviceInstanceId, vnfInstanceId, + request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId()); + Recipe recipe = vnfRestHandler.findVnfModuleRecipe( + request.getRequestDetails().getModelInfo().getModelCustomizationId(), "vnf", "deleteInstance"); + vnfRestHandler.callWorkflowEngine(vnfRestHandler.buildRequestParams(request, + vnfRestHandler.getRequestUri(requestContext), requestId, serviceInstanceId, vnfInstanceId), + recipe.getOrchestrationUri()); + ServiceInstancesResponse response = vnfRestHandler.createResponse(vnfInstanceId, requestId, requestContext); + return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java new file mode 100644 index 0000000000..afabdd9c60 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java @@ -0,0 +1,99 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.filters.ResponseUpdater; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.infra.rest.handler.VFModuleRestHandler; +import org.onap.so.apihandlerinfra.infra.rest.handler.VolumeRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import io.swagger.annotations.ApiOperation; + +@Component("VolumesV8") +@Path("/onap/so/infra/serviceInstantiation") +public class Volumes { + + private static Logger logger = LoggerFactory.getLogger(Volumes.class); + + @Autowired + private BpmnRequestBuilder requestBuilder; + + @Autowired + private VFModuleRestHandler vfModuleRestHandler; + + @Autowired + private VolumeRestHandler volumeRestHandler; + + @DELETE + @ResponseUpdater + @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete a VfModule instance", response = ServiceInstancesResponse.class) + @Transactional + public Response deleteVfModuleInstance(@PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("volumeGroupInstanceId") String volumeGroupId, @Context ContainerRequestContext requestContext) + throws Exception { + InfraActiveRequests currentRequest = null; + String requestId = volumeRestHandler.getRequestId(requestContext); + String requestorId = "Unknown"; + String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME); + String requestURL = requestContext.getUriInfo().getAbsolutePath().toString(); + currentRequest = volumeRestHandler.createInfraActiveRequestForDelete(requestId, volumeGroupId, + serviceInstanceId, vnfInstanceId, requestorId, source, requestURL); + ServiceInstancesRequest request = requestBuilder.buildVolumeGroupDeleteRequest(vnfInstanceId, volumeGroupId); + volumeRestHandler.saveInstanceName(request, currentRequest); + volumeRestHandler.checkDuplicateRequest(serviceInstanceId, vnfInstanceId, volumeGroupId, + request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId()); + Recipe recipe = vfModuleRestHandler.findVfModuleRecipe( + request.getRequestDetails().getModelInfo().getModelCustomizationId(), ModelType.volumeGroup.toString(), + Action.deleteInstance.toString()); + volumeRestHandler + .callWorkflowEngine( + volumeRestHandler.buildRequestParams(request, volumeRestHandler.getRequestUri(requestContext), + requestId, serviceInstanceId, vnfInstanceId, volumeGroupId), + recipe.getOrchestrationUri()); + ServiceInstancesResponse response = volumeRestHandler.createResponse(volumeGroupId, requestId, requestContext); + return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java new file mode 100644 index 0000000000..2153d9a628 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.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.apihandlerinfra.infra.rest.exception; + +public class AAIEntityNotFound extends Exception { + + public AAIEntityNotFound(String errorMessage) { + super(errorMessage); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/CloudConfigurationNotFoundException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/CloudConfigurationNotFoundException.java new file mode 100644 index 0000000000..5135478a3e --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/CloudConfigurationNotFoundException.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.apihandlerinfra.infra.rest.exception; + +public class CloudConfigurationNotFoundException extends RuntimeException { + + public CloudConfigurationNotFoundException(String errorMessage) { + super(errorMessage); + } + +} diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/NoRecipeException.java index 0c10599a52..db35b5c5cd 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/NoRecipeException.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -18,11 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.apihandlerinfra; +package org.onap.so.apihandlerinfra.infra.rest.exception; + +public class NoRecipeException extends Exception { + + public NoRecipeException(String error) { + super(error); + } + + -/* - * Enum for Status values returned by API Handler to Tail-F - */ -public enum ModelType { - service, vnf, vfModule, volumeGroup, network } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java new file mode 100644 index 0000000000..35cb21945c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java @@ -0,0 +1,30 @@ +/*- + * ============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.apihandlerinfra.infra.rest.exception; + +public class RequestConflictedException extends RuntimeException { + + public RequestConflictedException(String errorMessage) { + super(errorMessage); + } + + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.java new file mode 100644 index 0000000000..f9206628a4 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.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.apihandlerinfra.infra.rest.exception; + +public class WorkflowEngineConnectionException extends Exception { + + public WorkflowEngineConnectionException(String error, Throwable t) { + super(error, t); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java new file mode 100644 index 0000000000..519578ce6c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java @@ -0,0 +1,48 @@ +/*- + * ============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.apihandlerinfra.infra.rest.exception.mapper; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; +import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class AAIEntityNotFoundMapper implements ExceptionMapper<AAIEntityNotFound> { + + private static final Logger logger = LoggerFactory.getLogger(AAIEntityNotFoundMapper.class); + + @Override + public Response toResponse(AAIEntityNotFound e) { + logger.error("AAIEntity Not Found", e); + RequestError error = new RequestError(); + ServiceException value = new ServiceException(); + value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR); + value.setText(e.getMessage()); + error.setServiceException(value); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java new file mode 100644 index 0000000000..24bf7434ee --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java @@ -0,0 +1,48 @@ +/*- + * ============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.apihandlerinfra.infra.rest.exception.mapper; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; +import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class CloudConfigurationNotFoundMapper implements ExceptionMapper<CloudConfigurationNotFoundException> { + + private static final Logger logger = LoggerFactory.getLogger(CloudConfigurationNotFoundMapper.class); + + @Override + public Response toResponse(CloudConfigurationNotFoundException e) { + logger.error("Cloud Configuration Not Found", e); + RequestError error = new RequestError(); + ServiceException value = new ServiceException(); + value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR); + value.setText(e.getMessage()); + error.setServiceException(value); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java new file mode 100644 index 0000000000..c807aa2597 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java @@ -0,0 +1,48 @@ +/*- + * ============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.apihandlerinfra.infra.rest.exception.mapper; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class NoRecipeExceptionMapper implements ExceptionMapper<NoRecipeException> { + + private static final Logger logger = LoggerFactory.getLogger(NoRecipeExceptionMapper.class); + + @Override + public Response toResponse(NoRecipeException e) { + logger.error("No Recipe Found", e); + RequestError error = new RequestError(); + ServiceException value = new ServiceException(); + value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR); + value.setText(e.getMessage()); + error.setServiceException(value); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java new file mode 100644 index 0000000000..42d07c627b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java @@ -0,0 +1,48 @@ +/*- + * ============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.apihandlerinfra.infra.rest.exception.mapper; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException; +import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class RequestConflictMapper implements ExceptionMapper<RequestConflictedException> { + + private static final Logger logger = LoggerFactory.getLogger(RequestConflictMapper.class); + + @Override + public Response toResponse(RequestConflictedException e) { + logger.error("Request Conflict Error", e); + RequestError error = new RequestError(); + ServiceException value = new ServiceException(); + value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR); + value.setText(e.getMessage()); + error.setServiceException(value); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java new file mode 100644 index 0000000000..71e0dacd56 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java @@ -0,0 +1,48 @@ +/*- + * ============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.apihandlerinfra.infra.rest.exception.mapper; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.exception.WorkflowEngineConnectionException; +import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class WorkflowEngineConnectionMapper implements ExceptionMapper<WorkflowEngineConnectionException> { + + private static final Logger logger = LoggerFactory.getLogger(WorkflowEngineConnectionMapper.class); + + @Override + public Response toResponse(WorkflowEngineConnectionException e) { + logger.error("Workflow Engine Connection Error", e); + RequestError error = new RequestError(); + ServiceException value = new ServiceException(); + value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR); + value.setText(e.getMessage()); + error.setServiceException(value); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java new file mode 100644 index 0000000000..db84353cd4 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java @@ -0,0 +1,217 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import java.io.IOException; +import java.net.URL; +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.Optional; +import javax.ws.rs.container.ContainerRequestContext; +import org.apache.http.HttpStatus; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClient; +import org.onap.so.apihandler.common.RequestClientFactory; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Actions; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.MsoRequest; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException; +import org.onap.so.apihandlerinfra.infra.rest.exception.WorkflowEngineConnectionException; +import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LogConstants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestReferences; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.onap.so.utils.UUIDChecker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public abstract class AbstractRestHandler { + + private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class); + + public static final String conflictFailMessage = "Error: Locked instance - This %s (%s) " + + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding."; + + + @Autowired + protected CatalogDbClient catalogDbClient; + + @Autowired + protected RequestsDbClient infraActiveRequestsClient; + + @Autowired + protected RequestClientFactory reqClientFactory; + + public String getRequestUri(ContainerRequestContext context) { + String requestUri = context.getUriInfo().getPath(); + String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri); + MDC.put(LogConstants.HTTP_URL, httpUrl); + requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22); + return requestUri; + } + + public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { + String requestId = null; + if (requestContext.getProperty("requestId") != null) { + requestId = requestContext.getProperty("requestId").toString(); + } + if (UUIDChecker.isValidUUID(requestId)) { + return requestId; + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = + new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + } + + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, + MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) + throws ApiException { + return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq); + } + + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, + String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { + InfraActiveRequests dup = null; + try { + if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance + || action == Action.activateInstance || action == Action.assignInstance))) { + dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope); + } + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + RequestDbFailureException requestDbFailureException = + new RequestDbFailureException.Builder("check for duplicate instance", e.toString(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage()); + throw requestDbFailureException; + } + return dup; + } + + public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) + throws RequestDbFailureException { + if (aq != null) { + if ((status == Status.FAILED) || (status == Status.COMPLETE)) { + aq.setStatusMessage(errorMessage); + aq.setProgress(100L); + aq.setRequestStatus(status.toString()); + Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); + aq.setEndTime(endTimeStamp); + try { + infraActiveRequestsClient.updateInfraActiveRequests(aq); + } catch (Exception e) { + logger.error("Error updating status", e); + } + } + } + } + + + + public void callWorkflowEngine(RequestClientParameter requestClientParameter, String orchestrationUri) + throws WorkflowEngineConnectionException { + RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationUri); + try { + requestClient.post(requestClientParameter); + } catch (IOException e) { + logger.error("Error Calling Workflow Engine", e); + throw new WorkflowEngineConnectionException("Error Calling Workflow Engine", e); + } + } + + public Optional<URL> buildSelfLinkUrl(String url, String requestId) { + Optional<URL> selfLinkUrl = Optional.empty(); + String version = ""; + try { + URL aUrl = new URL(url); + String aPath = aUrl.getPath(); + if (aPath.indexOf("/v") == -1) { + version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4); + } else { + version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4); + } + String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId); + selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); + } catch (Exception e) { + selfLinkUrl = Optional.empty(); // ignore + logger.info(e.getMessage()); + } + return selfLinkUrl; + } + + /** + * @param vfmoduleInstanceId + * @param requestId + * @param response + */ + public ServiceInstancesResponse createResponse(String instanceId, String requestId, + ContainerRequestContext requestContext) { + ServiceInstancesResponse response = new ServiceInstancesResponse(); + RequestReferences requestReferences = new RequestReferences(); + requestReferences.setInstanceId(instanceId); + requestReferences.setRequestId(requestId); + Optional<URL> optionalUrl = buildSelfLinkUrl(getRequestUri(requestContext), requestId); + if (optionalUrl.isPresent()) { + requestReferences.setRequestSelfLink(optionalUrl.get()); + } + response.setRequestReferences(requestReferences); + return response; + } + + public void checkDuplicateRequest(HashMap<String, String> instanceIdMap, ModelType modelType, String instanceName, + String requestId) throws RequestConflictedException { + InfraActiveRequests conflictedRequest = + infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString()); + if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) { + throw new RequestConflictedException(String.format(conflictFailMessage, modelType.toString(), instanceName, + conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId())); + } + } + + + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java new file mode 100644 index 0000000000..ebb5d7e119 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.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.apihandlerinfra.infra.rest.handler; + +import java.sql.Timestamp; +import java.util.HashMap; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException; +import org.onap.so.db.catalog.beans.NetworkRecipe; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.LogConstants; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class NetworkRestHandler extends AbstractRestHandler { + + private static final Logger logger = LoggerFactory.getLogger(NetworkRestHandler.class); + + public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String serviceInstanceId, + String networkId, String requestorId, String source, String requestURL) { + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + InfraActiveRequests deleteRequest = new InfraActiveRequests(); + deleteRequest.setRequestAction(Action.deleteInstance.toString()); + deleteRequest.setAction(Action.deleteInstance.toString()); + deleteRequest.setStartTime(startTimeStamp); + deleteRequest.setServiceInstanceId(serviceInstanceId); + deleteRequest.setNetworkId(networkId); + deleteRequest.setRequestId(requestId); + deleteRequest.setRequestorId(requestorId); + deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + deleteRequest.setSource(source); + deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + deleteRequest.setRequestUrl(requestURL); + deleteRequest.setRequestScope(ModelType.network.toString()); + deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + return deleteRequest; + } + + public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String serviceInstanceId, + String networkId, String requestorId, String source, String requestURL) { + InfraActiveRequests request = mapInfraActiveRequestForDelete(requestId, serviceInstanceId, networkId, + requestorId, source, requestURL); + infraActiveRequestsClient.save(request); + return request; + } + + public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI, + String requestId, String serviceInstanceId, String networkId) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId) + .setNetworkId(networkId).setALaCarte(true).setRequestDetails(mapper.writeValueAsString(request)) + .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8") + .build(); + } + + public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) { + try { + currentRequest.setNetworkName(request.getRequestDetails().getRequestInfo().getInstanceName()); + infraActiveRequestsClient.updateInfraActiveRequests(currentRequest); + } catch (Exception e) { + logger.warn("Could not update instance name", e); + } + } + + public void checkDuplicateRequest(String serviceInstanceId, String networkInstanceId, String instanceName, + String requestId) throws RequestConflictedException { + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("networkInstanceId", networkInstanceId); + checkDuplicateRequest(instanceIdMap, ModelType.network, instanceName, requestId); + } + + public Recipe findNetworkRecipe(String action) throws NoRecipeException { + String modelName = "GR-API-DEFAULT"; + NetworkRecipe recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action); + + if (recipe == null) { + throw new NoRecipeException(String.format("Unable to locate default recipe for, Action: %s, Model Name: %s", + action, modelName)); + } + return recipe; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java new file mode 100644 index 0000000000..7d3091e950 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java @@ -0,0 +1,116 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + + +import java.sql.Timestamp; +import java.util.HashMap; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.ServiceRecipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.LogConstants; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class ServiceInstanceRestHandler extends AbstractRestHandler { + + private static final String DEFAULT_VF_MODULE_UUID = "d88da85c-d9e8-4f73-b837-3a72a431622b"; + + private static final Logger logger = LoggerFactory.getLogger(ServiceInstanceRestHandler.class); + + public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String serviceInstanceId, + String requestorId, String source, String requestURL) { + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + InfraActiveRequests deleteRequest = new InfraActiveRequests(); + deleteRequest.setRequestAction(Action.deleteInstance.toString()); + deleteRequest.setAction(Action.deleteInstance.toString()); + deleteRequest.setStartTime(startTimeStamp); + deleteRequest.setServiceInstanceId(serviceInstanceId); + deleteRequest.setRequestId(requestId); + deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + deleteRequest.setRequestorId(requestorId); + deleteRequest.setSource(source); + deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + deleteRequest.setRequestUrl(requestURL); + deleteRequest.setRequestScope(ModelType.service.toString()); + return deleteRequest; + } + + public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String serviceInstanceId, + String requestorId, String source, String requestURL) { + InfraActiveRequests request = + mapInfraActiveRequestForDelete(requestId, serviceInstanceId, requestorId, source, requestURL); + infraActiveRequestsClient.save(request); + return request; + } + + public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI, + String requestId, String serviceInstanceId) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId) + .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(request)) + .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8") + .build(); + } + + public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) { + try { + currentRequest.setServiceInstanceName(request.getRequestDetails().getRequestInfo().getInstanceName()); + infraActiveRequestsClient.updateInfraActiveRequests(currentRequest); + } catch (Exception e) { + logger.warn("Could not update instance name", e); + } + } + + public void checkDuplicateRequest(String serviceInstanceId, String instanceName, String requestId) + throws RequestConflictedException { + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + checkDuplicateRequest(instanceIdMap, ModelType.service, instanceName, requestId); + } + + public Recipe findServiceRecipe(String modelUUID, String action) throws NoRecipeException { + ServiceRecipe recipe = catalogDbClient.findServiceRecipeByActionAndServiceModelUUID(action, modelUUID); + if (recipe == null) { + recipe = catalogDbClient.findServiceRecipeByActionAndServiceModelUUID(action, DEFAULT_VF_MODULE_UUID); + } + if (recipe == null) { + throw new NoRecipeException(String.format( + "Unable to locate custom or default recipe for, Action: %s, Model UUID: %s", action, modelUUID)); + } + return recipe; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java new file mode 100644 index 0000000000..efd8b12b9a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java @@ -0,0 +1,125 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + + +import java.sql.Timestamp; +import java.util.HashMap; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.VnfComponentsRecipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.LogConstants; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class VFModuleRestHandler extends AbstractRestHandler { + + private static final Logger logger = LoggerFactory.getLogger(VFModuleRestHandler.class); + + public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String vfModuleId, + String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) { + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + InfraActiveRequests deleteRequest = new InfraActiveRequests(); + deleteRequest.setRequestAction(Action.deleteInstance.toString()); + deleteRequest.setAction(Action.deleteInstance.toString()); + deleteRequest.setStartTime(startTimeStamp); + deleteRequest.setServiceInstanceId(serviceInstanceId); + deleteRequest.setVnfId(vnfId); + deleteRequest.setVfModuleId(vfModuleId); + deleteRequest.setRequestId(requestId); + deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + deleteRequest.setRequestorId(requestorId); + deleteRequest.setSource(source); + deleteRequest.setVfModuleId(vfModuleId); + deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + deleteRequest.setRequestUrl(requestURL); + deleteRequest.setRequestScope(ModelType.vfModule.toString()); + deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + return deleteRequest; + } + + public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String vfModuleId, + String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) { + InfraActiveRequests request = mapInfraActiveRequestForDelete(requestId, vfModuleId, serviceInstanceId, vnfId, + requestorId, source, requestURL); + infraActiveRequestsClient.save(request); + return request; + } + + public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI, + String requestId, String serviceInstanceId, String vnfId, String vfModuleId) + throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId) + .setVnfId(vnfId).setVfModuleId(vfModuleId).setALaCarte(true) + .setRequestDetails(mapper.writeValueAsString(request)) + .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8") + .build(); + } + + public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) { + try { + currentRequest.setVfModuleName(request.getRequestDetails().getRequestInfo().getInstanceName()); + infraActiveRequestsClient.updateInfraActiveRequests(currentRequest); + } catch (Exception e) { + logger.warn("Could not update instance name", e); + } + } + + public void checkDuplicateRequest(String serviceInstanceId, String vnfInstanceId, String vfmoduleInstanceId, + String instanceName, String requestId) { + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); + checkDuplicateRequest(instanceIdMap, ModelType.vfModule, instanceName, requestId); + } + + public Recipe findVfModuleRecipe(String modelCustomizationId, String modelType, String action) + throws NoRecipeException { + VnfComponentsRecipe recipe = + catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + modelCustomizationId, modelType, action); + if (recipe == null) { + recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + "GR-API-DEFAULT", modelType, action); + } + if (recipe == null) { + throw new NoRecipeException(String.format( + "Unable to locate custom or default recipe for ModelType: %s , Action: %s, CustomizationId: %s", + modelType, action, modelCustomizationId)); + } + return recipe; + + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java new file mode 100644 index 0000000000..d98625fe50 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java @@ -0,0 +1,110 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + + +import java.sql.Timestamp; +import java.util.HashMap; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.VnfRecipe; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.LogConstants; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class VnfRestHandler extends AbstractRestHandler { + + private static final Logger logger = LoggerFactory.getLogger(VnfRestHandler.class); + + public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String serviceInstanceId, String vnfId, + String requestorId, String source, String requestURL) { + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + InfraActiveRequests deleteRequest = new InfraActiveRequests(); + deleteRequest.setRequestAction(Action.deleteInstance.toString()); + deleteRequest.setAction(Action.deleteInstance.toString()); + deleteRequest.setStartTime(startTimeStamp); + deleteRequest.setServiceInstanceId(serviceInstanceId); + deleteRequest.setVnfId(vnfId); + deleteRequest.setRequestId(requestId); + deleteRequest.setRequestorId(requestorId); + deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + deleteRequest.setSource(source); + deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + deleteRequest.setRequestScope(ModelType.vnf.toString()); + deleteRequest.setRequestUrl(requestURL); + return deleteRequest; + } + + public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String serviceInstanceId, + String vnfId, String requestorId, String source, String requestURL) { + InfraActiveRequests request = + mapInfraActiveRequestForDelete(requestId, serviceInstanceId, vnfId, requestorId, source, requestURL); + infraActiveRequestsClient.save(request); + return request; + } + + public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI, + String requestId, String serviceInstanceId, String vnfId) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId) + .setVnfId(vnfId).setALaCarte(true).setRequestDetails(mapper.writeValueAsString(request)) + .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8") + .build(); + } + + public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) { + try { + currentRequest.setVnfName(request.getRequestDetails().getRequestInfo().getInstanceName()); + infraActiveRequestsClient.updateInfraActiveRequests(currentRequest); + } catch (Exception e) { + logger.warn("Could not update instance name", e); + } + } + + public void checkDuplicateRequest(String serviceInstanceId, String vnfInstanceId, String instanceName, + String requestId) { + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + checkDuplicateRequest(instanceIdMap, ModelType.vnf, instanceName, requestId); + } + + public Recipe findVnfModuleRecipe(String modelCustomizationId, String modelType, String action) + throws NoRecipeException { + VnfRecipe recipe = new VnfRecipe(); + recipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + return recipe; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java new file mode 100644 index 0000000000..52f7ee9ac4 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java @@ -0,0 +1,104 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + + +import java.sql.Timestamp; +import java.util.HashMap; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.LogConstants; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Component +public class VolumeRestHandler extends AbstractRestHandler { + + private static final Logger logger = LoggerFactory.getLogger(VolumeRestHandler.class); + + public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String volumeGroupId, + String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) { + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + InfraActiveRequests deleteRequest = new InfraActiveRequests(); + deleteRequest.setRequestAction(Action.deleteInstance.toString()); + deleteRequest.setAction(Action.deleteInstance.toString()); + deleteRequest.setStartTime(startTimeStamp); + deleteRequest.setServiceInstanceId(serviceInstanceId); + deleteRequest.setVnfId(vnfId); + deleteRequest.setVolumeGroupId(volumeGroupId); + deleteRequest.setRequestId(requestId); + deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + deleteRequest.setRequestorId(requestorId); + deleteRequest.setSource(source); + deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + deleteRequest.setRequestScope(ModelType.volumeGroup.toString()); + deleteRequest.setRequestUrl(requestURL); + return deleteRequest; + } + + public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String volumeGroupId, + String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) { + InfraActiveRequests request = mapInfraActiveRequestForDelete(requestId, volumeGroupId, serviceInstanceId, vnfId, + requestorId, source, requestURL); + infraActiveRequestsClient.save(request); + return request; + } + + public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI, + String requestId, String serviceInstanceId, String vnfId, String volumeGroupId) + throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId) + .setVnfId(vnfId).setVolumeGroupId(volumeGroupId).setALaCarte(true) + .setRequestDetails(mapper.writeValueAsString(request)) + .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8") + .build(); + } + + public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) { + try { + currentRequest.setVolumeGroupName(request.getRequestDetails().getRequestInfo().getInstanceName()); + infraActiveRequestsClient.updateInfraActiveRequests(currentRequest); + } catch (Exception e) { + logger.warn("Could not update instance name", e); + } + } + + public void checkDuplicateRequest(String serviceInstanceId, String vnfInstanceId, String volumeGroupId, + String instanceName, String requestId) { + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("volumeGroupInstanceId", volumeGroupId); + checkDuplicateRequest(instanceIdMap, ModelType.volumeGroup, instanceName, requestId); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java index d79d73c036..e8d00ed52b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java @@ -38,6 +38,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.Constants; @@ -125,7 +126,7 @@ public class CloudOrchestration { private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId) throws ApiException { - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); long startTime = System.currentTimeMillis(); CloudOrchestrationRequest cor = null; tenantIsolationRequest.setRequestId(requestId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java index be6d5b06ca..20e8fed32d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java @@ -92,7 +92,7 @@ public class CloudResourcesOrchestration { CloudOrchestrationRequest cor = null; - logger.debug("requestId is: " + requestId); + logger.debug("requestId is: {}", requestId); try { ObjectMapper mapper = new ObjectMapper(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java index 696616099f..007ea938a2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java @@ -45,8 +45,6 @@ import org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -356,8 +354,7 @@ public class TenantIsolationRequest { request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), - ErrorCode.DataError.getValue(), "Exception when updating record in DB"); + logger.error("Exception when updating record in DB", e); logger.debug("Exception: ", e); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java index d9db5713a7..6942d441e6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java @@ -34,8 +34,6 @@ 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.graphinventory.entities.uri.Depth; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -63,7 +61,7 @@ public class AAIClientHelper { * Update managing ECOMP Environment Info from A&AI * * @param id = operationalEnvironmentId - * @param AAIOperationalEnvironment object + * @param aaiRequest object */ public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest) { @@ -75,7 +73,7 @@ public class AAIClientHelper { public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload) - throws Exception { + throws AAIClientCallFailed { try { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId); @@ -90,7 +88,7 @@ public class AAIClientHelper { /** * Create an Operational Environment object in A&AI * - * @param AAIOperationalEnvironment object + * @param operationalEnvironment object */ public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java index c80e89e21d..71405b0f63 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java @@ -23,9 +23,9 @@ package org.onap.so.apihandlerinfra.validation; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; -import org.onap.so.apihandlerinfra.ModelType; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.LineOfBusiness; +import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.Platform; public class PlatformLOBValidation implements ValidationRule { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java index 60e1274469..584269715a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java @@ -23,8 +23,8 @@ package org.onap.so.apihandlerinfra.validation; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; -import org.onap.so.apihandlerinfra.ModelType; import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.OwningEntity; import org.onap.so.serviceinstancebeans.Project; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java index b02bd95d97..3b87d91d3f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java @@ -119,12 +119,25 @@ public class RelatedInstancesValidation implements ValidationRule { isRelatedServiceInstancePresent = true; } + if (requestScope.equalsIgnoreCase(ModelType.service.name())) { + if (empty(relatedInstance.getInstanceName()) + && ModelType.vpnBinding.equals(relatedInstanceModelInfo.getModelType())) { + throw new ValidationException("instanceName in relatedInstance for vpnBinding modelType", true); + } + if (empty(relatedInstance.getInstanceName()) + && ModelType.network.equals(relatedInstanceModelInfo.getModelType())) { + throw new ValidationException("instanceName in relatedInstance for network modelType", true); + } + } + if (action != Action.deleteInstance && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) { if (!(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup) || relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint) || relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) - || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) { + || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup) + || relatedInstanceModelInfo.getModelType().equals(ModelType.network) + || relatedInstanceModelInfo.getModelType().equals(ModelType.vpnBinding))) { if (empty(relatedInstanceModelInfo.getModelInvariantId())) { throw new ValidationException("modelInvariantId in relatedInstance"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml index e709758223..136acfb9e1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml @@ -7,7 +7,7 @@ server: mso: infra: - auditInventory: true + auditInventory: false default: versions: apiMinorVersion: 0 @@ -29,10 +29,13 @@ mso: spring: datasource: - jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb - username: ${DB_USERNAME} - password: ${DB_PASSWORD} - driver-class-name: org.mariadb.jdbc.Driver + hikari: + jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + driver-class-name: org.mariadb.jdbc.Driver + pool-name: catdb-pool + registerMbeans: true jpa: show-sql: true hibernate: @@ -45,11 +48,13 @@ spring: request: datasource: - jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/requestdb - username: ${DB_USERNAME} - password: ${DB_PASSWORD} - driver-class-name: org.mariadb.jdbc.Driver - + hikari: + jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/requestdb + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + driver-class-name: org.mariadb.jdbc.Driver + pool-name: reqdb-pool + registerMbeans: true #Actuator management: endpoints: @@ -70,4 +75,4 @@ org: so: adapters: network: - encryptionKey: aa3871669d893c7fb8abbcda31b88b4f
\ No newline at end of file + encryptionKey: aa3871669d893c7fb8abbcda31b88b4f diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java index c30b9dedf2..86bf8060a7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java @@ -24,13 +24,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.StringReader; -import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; -import java.util.Optional; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; @@ -46,13 +44,13 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import junitparams.JUnitParamsRunner; import junitparams.Parameters; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; @RunWith(JUnitParamsRunner.class) public class MsoRequestTest extends BaseTest { @@ -83,6 +81,12 @@ public class MsoRequestTest extends BaseTest { return input; } + public String inputStreamVpnBonding(String JsonInput) throws IOException { + JsonInput = "src/test/resources/Validation" + JsonInput; + String input = new String(Files.readAllBytes(Paths.get(JsonInput))); + return input; + } + // Tests for successful validation of incoming JSON requests through the parse method @Test @Parameters(method = "successParameters") @@ -188,6 +192,8 @@ public class MsoRequestTest extends BaseTest { instanceIdMapTest, Action.addRelationships, "5"}, {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"}, + {mapper.readValue(inputStream("/RelatedInstances/ServiceInstanceVpnBondingService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "7"}, {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}}); } @@ -546,6 +552,22 @@ public class MsoRequestTest extends BaseTest { mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 6}, + {"No valid modelType in relatedInstance is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoModelType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid instanceId in relatedInstance is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid instanceName in relatedInstance for vpnBinding modelType is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceNameVpnBinding.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid instanceName in relatedInstance for network modelType is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceNameNetwork.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), ServiceInstancesRequest.class), @@ -1038,20 +1060,5 @@ public class MsoRequestTest extends BaseTest { assertNotNull(result); } - @Test - public void buildSelfLinkUrlTest() throws Exception { - // v - version - String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; - String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1"; - this.msoRequest = new MsoRequest(); - Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId); - assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); - // V - Version - String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; - String expectedSelfLinkV = - "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId); - assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString()); - } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java new file mode 100644 index 0000000000..a400caeae2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 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.apihandlerinfra; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response; +import org.apache.http.HttpStatus; +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.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.InstanceReferences; +import org.onap.so.serviceinstancebeans.Request; +import org.onap.so.serviceinstancebeans.RequestStatus; + +@RunWith(MockitoJUnitRunner.class) +public class OrchestrationRequestsUnitTest { + @Mock + private RequestsDbClient requestDbClient; + @Mock + private MsoRequest msoRequest; + @Mock + private ResponseBuilder builder; + @Mock + private Response response; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + @Spy + private OrchestrationRequests orchestrationRequests; + + private static final String REQUEST_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebba"; + private static final String SERVICE_INSTANCE_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebbb"; + private static final String ORIGINAL_REQUEST_ID = "8f2d38a6-7c20-465a-bd7e-075645f1394b"; + private static final String SERVICE = "service"; + private static final String EXT_SYSTEM_ERROR_SOURCE = "external system error source"; + private InfraActiveRequests iar; + boolean includeCloudRequest = false; + boolean extSystemErrorSource = false; + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String VERSION = "v7"; + List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = new ArrayList<>(); + + @Before + public void setup() { + iar = new InfraActiveRequests(); + iar.setRequestScope(SERVICE); + iar.setRequestId(REQUEST_ID); + iar.setServiceInstanceId(SERVICE_INSTANCE_ID); + when(requestDbClient.getInfraActiveRequestbyRequestId(Mockito.eq(REQUEST_ID))).thenReturn(iar); + when(requestDbClient.getRequestProcessingDataBySoRequestId(Mockito.eq(REQUEST_ID))) + .thenReturn(requestProcessingData); + + when(builder.buildResponse(Mockito.eq(HttpStatus.SC_OK), Mockito.eq(REQUEST_ID), any(Object.class), + any(String.class))).thenReturn(response); + } + + @Test + public void mapInfraActiveRequestToRequestWithOriginalRequestIdTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setOriginalRequestId(ORIGINAL_REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + iar.setOriginalRequestId(ORIGINAL_REQUEST_ID); + + Request result = + orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, extSystemErrorSource); + assertThat(result, sameBeanAs(expected)); + } + + @Test + public void mapInfraActiveRequestToRequestOriginalRequestIdNullTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + Request result = + orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, extSystemErrorSource); + assertThat(result, sameBeanAs(expected)); + } + + @Test + public void mapExtSystemErrorSourceToRequestFalseTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + extSystemErrorSource = false; + includeCloudRequest = false; + + Request actual = + orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, extSystemErrorSource); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void mapExtSystemErrorSourceToRequestTrueTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + requestStatus.setExtSystemErrorSource(EXT_SYSTEM_ERROR_SOURCE); + + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + extSystemErrorSource = true; + includeCloudRequest = false; + iar.setExtSystemErrorSource(EXT_SYSTEM_ERROR_SOURCE); + + Request actual = + orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, extSystemErrorSource); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void mapExtSystemErrorSourceToRequestMethodInvokedTest() throws ApiException, IOException { + extSystemErrorSource = true; + includeCloudRequest = false; + orchestrationRequests.getOrchestrationRequest(REQUEST_ID, VERSION, includeCloudRequest, extSystemErrorSource); + + verify(orchestrationRequests, times(1)).mapExtSystemErrorSourceToRequest(Mockito.eq(iar), Mockito.any(), + Mockito.eq(extSystemErrorSource)); + } + + @Test + public void requestStatusExtSystemErrorSourceTest() { + RequestStatus requestStatus = new RequestStatus(); + requestStatus.setExtSystemErrorSource(EXT_SYSTEM_ERROR_SOURCE); + assertThat(requestStatus.getExtSystemErrorSource(), is(equalTo(EXT_SYSTEM_ERROR_SOURCE))); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java index dc0cd473c2..62a6f44a63 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java @@ -38,7 +38,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; -import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.junit.Before; @@ -50,6 +49,7 @@ import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java index e80fd9e690..91ca756a51 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -21,32 +21,70 @@ package org.onap.so.apihandlerinfra; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Timestamp; 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.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; +import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; @RunWith(MockitoJUnitRunner.class) public class RequestHandlerUtilsUnitTest { + @Mock + private CatalogDbClient catDbClient; + + @InjectMocks @Spy private RequestHandlerUtils requestHandler; + @Rule + public ExpectedException thrown = ExpectedException.none(); + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String RESUMED_REQUEST_ID = "59c7247f-839f-4923-90c3-05faa3ab354d"; private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String MODEL_VERSION_ID = "883f4a7a-b5a5-44e0-8738-361c6413d24c"; + private static final String MODEL_VERSION = "1.0"; + private static final String MODEL_INVARIANT_ID = "d358b828-e7f8-4833-ac96-2782bed1a9a9"; + private static final String MODEL_NAME = "modelName"; private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); private String requestUri = "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); private InfraActiveRequests currentActiveRequestIARNull = new InfraActiveRequests(); + private Action action = Action.createInstance; + private String vnfType = "vnfType"; + private String sdcServiceModelVersion = "7"; public String getRequestBody(String request) throws IOException { request = "src/test/resources/ResumeOrchestrationRequest" + request; @@ -66,7 +104,7 @@ public class RequestHandlerUtilsUnitTest { infraActiveRequest.setAicCloudRegion("cloudRegion"); infraActiveRequest.setRequestScope("service"); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); - infraActiveRequest.setServiceInstanceName("serviceInstanceName"); + infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); infraActiveRequest.setRequestAction(Action.createInstance.toString()); infraActiveRequest.setServiceType("serviceType"); @@ -77,17 +115,16 @@ public class RequestHandlerUtilsUnitTest { currentActiveRequest.setSource("VID"); currentActiveRequest.setStartTime(startTimeStamp); currentActiveRequest.setTenantId("tenant-id"); - currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBodyNewRequestorId.json")); currentActiveRequest.setAicCloudRegion("cloudRegion"); currentActiveRequest.setRequestScope("service"); - currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); - currentActiveRequest.setServiceInstanceName("serviceInstanceName"); currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); currentActiveRequest.setRequestAction(Action.createInstance.toString()); currentActiveRequest.setRequestUrl(requestUri); - currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setRequestorId("yyyyyy"); currentActiveRequest.setProgress(new Long(5)); + currentActiveRequest.setOriginalRequestId(RESUMED_REQUEST_ID); } private void setCurrentActiveRequestNullInfraActive() throws IOException { @@ -99,20 +136,308 @@ public class RequestHandlerUtilsUnitTest { currentActiveRequestIARNull.setRequestUrl(requestUri); currentActiveRequestIARNull.setRequestorId("xxxxxx"); currentActiveRequestIARNull.setProgress(new Long(5)); + currentActiveRequestIARNull.setOriginalRequestId(RESUMED_REQUEST_ID); } @Test - public void createNewRecordCopyFromInfraActiveRequestTest() { + public void createNewRecordCopyFromInfraActiveRequestTest() throws IOException, ApiException { + doNothing().when(requestHandler).setInstanceIdAndName(infraActiveRequest, currentActiveRequest); + doReturn(getRequestBody("/RequestBodyNewRequestorId.json")).when(requestHandler) + .updateRequestorIdInRequestBody(infraActiveRequest, "yyyyyy"); InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest, - CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "xxxxxx"); + CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "yyyyyy", RESUMED_REQUEST_ID); assertThat(currentActiveRequest, sameBeanAs(result)); } @Test - public void createNewRecordCopyFromInfraActiveRequestNullIARTest() { + public void createNewRecordCopyFromInfraActiveRequestNullIARTest() throws ApiException { InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID, - startTimeStamp, "VID", requestUri, "xxxxxx"); + startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID); assertThat(currentActiveRequestIARNull, sameBeanAs(result)); } + + @Test + public void setInstanceIdAndNameServiceTest() throws ApiException { + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setServiceInstanceId(SERVICE_INSTANCE_ID); + expected.setServiceInstanceName(SERVICE_INSTANCE_NAME); + + requestHandler.setInstanceIdAndName(infraActiveRequest, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameServiceNullInstanceNameTest() throws ApiException { + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests request = new InfraActiveRequests(); + request.setServiceInstanceId(SERVICE_INSTANCE_ID); + request.setRequestScope(ModelType.service.toString()); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setServiceInstanceId(SERVICE_INSTANCE_ID); + + requestHandler.setInstanceIdAndName(request, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameServiceNullInstanceNameVfModuleTest() throws ApiException { + InfraActiveRequests vfModuleRequest = new InfraActiveRequests(); + String errorMessage = + "vfModule for requestId: 59c7247f-839f-4923-90c3-05faa3ab354d being resumed does not have an instanceName."; + doNothing().when(requestHandler).updateStatus(vfModuleRequest, Status.FAILED, errorMessage); + + InfraActiveRequests request = new InfraActiveRequests(); + request.setServiceInstanceId(VFMODULE_ID); + request.setRequestScope(ModelType.vfModule.toString()); + request.setRequestId(RESUMED_REQUEST_ID); + + thrown.expect(ValidateException.class); + thrown.expectMessage(errorMessage); + + requestHandler.setInstanceIdAndName(request, vfModuleRequest); + } + + @Test + public void setInstanceIdAndNameRequestScopeNotValidTest() throws ApiException { + InfraActiveRequests originalServiceRequest = new InfraActiveRequests(); + originalServiceRequest.setRequestScope("test"); + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + + requestHandler.setInstanceIdAndName(originalServiceRequest, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVnfTest() throws ApiException { + InfraActiveRequests vnfRequestOriginal = new InfraActiveRequests(); + vnfRequestOriginal.setRequestScope("vnf"); + vnfRequestOriginal.setVnfId(VNF_ID); + vnfRequestOriginal.setVnfName(VNF_NAME); + InfraActiveRequests vnfRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVnfId(VNF_ID); + expected.setVnfName(VNF_NAME); + + requestHandler.setInstanceIdAndName(vnfRequestOriginal, vnfRequest); + assertThat(vnfRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVfModuleTest() throws ApiException { + InfraActiveRequests vfModuleRequestOriginal = new InfraActiveRequests(); + vfModuleRequestOriginal.setRequestScope("vfModule"); + vfModuleRequestOriginal.setVfModuleId(VFMODULE_ID); + vfModuleRequestOriginal.setVfModuleName(VFMODULE_NAME); + InfraActiveRequests vfModuleRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVfModuleId(VFMODULE_ID); + expected.setVfModuleName(VFMODULE_NAME); + + requestHandler.setInstanceIdAndName(vfModuleRequestOriginal, vfModuleRequest); + assertThat(vfModuleRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameNetworkTest() throws ApiException { + InfraActiveRequests networkRequestOriginal = new InfraActiveRequests(); + networkRequestOriginal.setRequestScope("network"); + networkRequestOriginal.setNetworkId(NETWORK_ID); + networkRequestOriginal.setNetworkName(NETWORK_NAME); + InfraActiveRequests networkRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setNetworkId(NETWORK_ID); + expected.setNetworkName(NETWORK_NAME); + + requestHandler.setInstanceIdAndName(networkRequestOriginal, networkRequest); + assertThat(networkRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVolumeGroupTest() throws ApiException { + InfraActiveRequests volumeGroupRequestOriginal = new InfraActiveRequests(); + volumeGroupRequestOriginal.setRequestScope("volumeGroup"); + volumeGroupRequestOriginal.setVolumeGroupId(VOLUME_GROUP_ID); + volumeGroupRequestOriginal.setVolumeGroupName(VOLUME_GROUP_NAME); + InfraActiveRequests volumeGroupRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVolumeGroupId(VOLUME_GROUP_ID); + expected.setVolumeGroupName(VOLUME_GROUP_NAME); + + requestHandler.setInstanceIdAndName(volumeGroupRequestOriginal, volumeGroupRequest); + assertThat(volumeGroupRequest, sameBeanAs(expected)); + } + + @Test + public void getIsBaseVfModuleTrueTest() throws ApiException { + VfModule vfModule = new VfModule(); + vfModule.setIsBase(true); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + + doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + Boolean expected = true; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleFalseTest() throws ApiException { + VfModule vfModule = new VfModule(); + vfModule.setIsBase(false); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + + doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = + "VnfType vnfType and VF Module Model Name modelName with version 7 not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + doReturn(null).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, currentActiveRequest); + } + + @Test + public void getIsBaseVfModuleModelVersionIdNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelVersion(MODEL_VERSION); + modelInfo.setModelName(MODEL_NAME); + Boolean expected = false; + + doReturn(null).when(catDbClient).getVfModuleByModelInvariantUUIDAndModelVersion(MODEL_INVARIANT_ID, + MODEL_VERSION); + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelInfoNotSetTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelVersionNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelVersionNullUpdateTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, null, currentActiveRequest); + } + + @Test + public void getIsBaseVfModulesdcModelVersionEmptyTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, "", currentActiveRequest); + } + + @Test + public void getModelTypeApplyUpdatedConfigTest() throws ApiException { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.applyUpdatedConfig, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeInPlaceSoftwareUpdateTest() throws ApiException { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.inPlaceSoftwareUpdate, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeAddMembersTest() throws ApiException { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.addMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeRemoveMembersTest() throws ApiException { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.removeMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeTest() throws ApiException { + ModelType modelTypeExpected = ModelType.service; + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType(ModelType.service); + + ModelType modelTypeResult = requestHandler.getModelType(Action.createInstance, modelInfo); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void updateRequestorIdInRequestBodyTest() throws IOException { + String newRequestorId = "yyyyyy"; + String expected = getRequestBody("/RequestBodyNewRequestorId.json"); + String result = requestHandler.updateRequestorIdInRequestBody(infraActiveRequest, newRequestorId); + assertEquals(expected, result); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java index 92490a66b8..398966b0b3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -30,6 +30,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -53,9 +54,11 @@ import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.web.client.HttpClientErrorException; import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.so.serviceinstancebeans.ModelType; @RunWith(MockitoJUnitRunner.class) public class ResumeOrchestrationRequestTest { @@ -81,8 +84,20 @@ public class ResumeOrchestrationRequestTest { private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; private static final String REQUEST_ID = "00032ab7-na18-42e5-965d-8ea592502019"; private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; - private static final String REQUEST_SCOPE = "service"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String SERVICE = "service"; + private static final String VNF = "vnf"; + private static final String VFMODULE = "vfModule"; + private static final String NETWORK = "network"; + private static final String VOLUME_GROUP = "volumeGroup"; private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); private final Action action = Action.createInstance; private final Boolean aLaCarte = false; @@ -91,15 +106,18 @@ public class ResumeOrchestrationRequestTest { "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; private final RecipeLookupResult lookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 80); private RequestClientParameter requestClientParameter = null; + private RequestClientParameter requestClientParameterVfModule = null; private ObjectMapper mapper = new ObjectMapper(); private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests infraActiveRequestVfModule = new InfraActiveRequests(); private ServiceInstancesRequest sir = new ServiceInstancesRequest(); private ServiceInstancesRequest sirNullALaCarte = new ServiceInstancesRequest(); private String requestBody = null; private String requestBodyNullALaCarte = null; private ContainerRequestContext requestContext = null; private HashMap<String, String> instanceIdMap = new HashMap<>(); + ModelInfo modelInfo; @Before @@ -110,13 +128,16 @@ public class ResumeOrchestrationRequestTest { // Setup InfraActiveRequests setInfraActiveRequest(); setCurrentActiveRequest(); + setInfraActiveRequestVfModule(); requestBody = infraActiveRequest.getRequestBody(); sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json"); - sirNullALaCarte = sir = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); + sirNullALaCarte = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); setRequestClientParameter(); + setRequestClientParameterVfModule(); instanceIdMap.put("serviceInstanceId", SERVICE_INSTANCE_ID); + modelInfo = sir.getRequestDetails().getModelInfo(); } public String getRequestBody(String request) throws IOException { @@ -128,12 +149,21 @@ public class ResumeOrchestrationRequestTest { infraActiveRequest.setTenantId("tenant-id"); infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); infraActiveRequest.setAicCloudRegion("cloudRegion"); - infraActiveRequest.setRequestScope(REQUEST_SCOPE); + infraActiveRequest.setRequestScope(SERVICE); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); infraActiveRequest.setRequestAction(Action.createInstance.toString()); infraActiveRequest.setServiceType("serviceType"); + infraActiveRequest.setVnfId(VNF_ID); + infraActiveRequest.setVfModuleId(VFMODULE_ID); + infraActiveRequest.setNetworkId(NETWORK_ID); + infraActiveRequest.setVolumeGroupId(VOLUME_GROUP_ID); + infraActiveRequest.setVnfName(VNF_NAME); + infraActiveRequest.setVfModuleName(VFMODULE_NAME); + infraActiveRequest.setNetworkName(NETWORK_NAME); + infraActiveRequest.setVolumeGroupName(VOLUME_GROUP_NAME); + infraActiveRequest.setRequestId(REQUEST_ID); } private void setCurrentActiveRequest() throws IOException { @@ -143,7 +173,7 @@ public class ResumeOrchestrationRequestTest { currentActiveRequest.setTenantId("tenant-id"); currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); currentActiveRequest.setAicCloudRegion("cloudRegion"); - currentActiveRequest.setRequestScope(REQUEST_SCOPE); + currentActiveRequest.setRequestScope(SERVICE); currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); @@ -154,13 +184,33 @@ public class ResumeOrchestrationRequestTest { currentActiveRequest.setProgress(new Long(5)); } + private void setInfraActiveRequestVfModule() throws IOException { + infraActiveRequestVfModule.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequestVfModule.setRequestScope(VFMODULE); + infraActiveRequestVfModule.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequestVfModule.setRequestAction(Action.createInstance.toString()); + infraActiveRequestVfModule.setVnfId(VNF_ID); + infraActiveRequestVfModule.setVfModuleId(VFMODULE_ID); + infraActiveRequestVfModule.setVnfName(VNF_NAME); + infraActiveRequestVfModule.setVfModuleName(VFMODULE_NAME); + } + private void setRequestClientParameter() { - requestClientParameter = new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID) - .setRecipeTimeout(80).setRequestAction(Action.createInstance.toString()) - .setServiceInstanceId(SERVICE_INSTANCE_ID).setPnfCorrelationId("pnfCorrelationId").setVnfId(null) - .setVfModuleId(null).setVolumeGroupId(null).setNetworkId(null).setServiceType("serviceType") - .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version) - .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build(); + requestClientParameter = + new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80) + .setRequestAction(Action.createInstance.toString()).setServiceInstanceId(SERVICE_INSTANCE_ID) + .setPnfCorrelationId("pnfCorrelationId").setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID) + .setVolumeGroupId(VOLUME_GROUP_ID).setNetworkId(NETWORK_ID).setServiceType("serviceType") + .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version) + .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build(); + } + + private void setRequestClientParameterVfModule() { + requestClientParameterVfModule = + new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80) + .setRequestAction(Action.createInstance.toString()).setPnfCorrelationId("pnfCorrelationId") + .setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID).setRequestDetails(requestBody) + .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(requestUri).build(); } @Test @@ -169,7 +219,7 @@ public class ResumeOrchestrationRequestTest { when(requestDbClient.getInfraActiveRequestbyRequestId(REQUEST_ID)).thenReturn(infraActiveRequest); doReturn(currentActiveRequest).when(requestHandler).createNewRecordCopyFromInfraActiveRequest( any(InfraActiveRequests.class), nullable(String.class), any(Timestamp.class), nullable(String.class), - nullable(String.class), nullable(String.class)); + nullable(String.class), nullable(String.class), anyString()); doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class), anyString(), nullable(String.class)); @@ -201,16 +251,20 @@ public class ResumeOrchestrationRequestTest { @Test public void resumeRequestTest() throws ApiException, IOException { Response response = null; + doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString()); + doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest, + ModelType.service.toString(), currentActiveRequest); when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), anyString())).thenReturn(sir); when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); - doReturn(lookupResult).when(resumeReq).serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sir, action, aLaCarte, + currentActiveRequest); doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); doNothing().when(resumeReq).requestDbSave(currentActiveRequest); when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), anyString(), anyString())).thenReturn(response); - doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, action); resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, @@ -220,15 +274,8 @@ public class ResumeOrchestrationRequestTest { } @Test - public void serviceRecipeLookupTest() throws ApiException, IOException { - when(serviceInstances.getServiceURI(any(ServiceInstancesRequest.class), any(Action.class), anyBoolean())) - .thenReturn(lookupResult); - RecipeLookupResult result = resumeReq.serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); - assertThat(result, sameBeanAs(lookupResult)); - } - - @Test public void setRequestClientParameterTest() throws ApiException, IOException { + doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo); when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), any(Action.class))).thenReturn(requestBody); RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, @@ -237,6 +284,16 @@ public class ResumeOrchestrationRequestTest { } @Test + public void setRequestClientParameterVfModuleTest() throws ApiException, IOException { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenReturn(requestBody); + doReturn(ModelType.vfModule).when(requestHandler).getModelType(action, modelInfo); + RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, + infraActiveRequestVfModule, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameterVfModule, sameBeanAs(result)); + } + + @Test public void requestDbSaveTest() throws RequestDbFailureException { doNothing().when(requestDbClient).save(currentActiveRequest); resumeReq.requestDbSave(currentActiveRequest); @@ -246,17 +303,22 @@ public class ResumeOrchestrationRequestTest { @Test public void resumeRequestTestALaCarteNull() throws ApiException, IOException { Response response = null; - + doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString()); + doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest, + ModelType.service.toString(), currentActiveRequest); when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), anyString())).thenReturn(sirNullALaCarte); when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); - doReturn(lookupResult).when(resumeReq).serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + doReturn(false).when(msoRequest).getAlacarteFlag(sirNullALaCarte); + doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sirNullALaCarte, action, false, + currentActiveRequest); doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, - infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sirNullALaCarte); + doReturn(false).when(resumeReq).setALaCarteFlagIfNull(SERVICE, action); doNothing().when(resumeReq).requestDbSave(currentActiveRequest); when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), anyString(), anyString())).thenReturn(response); - doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, action); resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, @@ -266,18 +328,8 @@ public class ResumeOrchestrationRequestTest { } @Test - public void serviceRecipeLookupErrorTest() throws IOException, ApiException { - when(serviceInstances.getServiceURI(sir, action, aLaCarte)) - .thenThrow(new IOException("Error occurred on recipe lookup")); - doNothing().when(requestHandler).updateStatus(any(InfraActiveRequests.class), any(Status.class), anyString()); - - thrown.expect(ValidateException.class); - thrown.expectMessage("Error occurred on recipe lookup"); - resumeReq.serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); - } - - @Test public void setRequestClientParameterErrorTest() throws ApiException, IOException { + doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo); when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), any(Action.class))).thenThrow(new IOException("IOException")); @@ -290,39 +342,141 @@ public class ResumeOrchestrationRequestTest { @Test public void checkForInProgressRequest() throws ApiException { doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, - REQUEST_SCOPE, currentActiveRequest); + SERVICE, currentActiveRequest); doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest, - action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, infraActiveRequest); + action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, infraActiveRequest); thrown.expect(DuplicateRequestException.class); - resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, - SERVICE_INSTANCE_NAME, action); + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); } @Test public void checkForInProgressRequestNoInProgressRequests() throws ApiException { - doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, currentActiveRequest); - resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, - SERVICE_INSTANCE_NAME, action); - verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, currentActiveRequest); } @Test public void checkForInProgressRequestCamundaHistoryCheckReturnsNoInProgress() throws ApiException { doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, - REQUEST_SCOPE, currentActiveRequest); + SERVICE, currentActiveRequest); doReturn(false).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); - resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, - SERVICE_INSTANCE_NAME, action); - verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, currentActiveRequest); verify(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); } + @Test + public void setInstanceIdMapServiceTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("serviceInstanceId", SERVICE_INSTANCE_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, SERVICE); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapRequestScopeNotValidTest() { + HashMap<String, String> expected = new HashMap<>(); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, "test"); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVnfTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("vnfInstanceId", VNF_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VNF); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVfModuleTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("vfModuleInstanceId", VFMODULE_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VFMODULE); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapNetworkTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("networkInstanceId", NETWORK_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, NETWORK); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVolumeGroupTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("volumeGroupInstanceId", VOLUME_GROUP_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VOLUME_GROUP); + assertEquals(result, expected); + } + + @Test + public void setInstanceNameServiceTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, SERVICE, currentActiveRequest); + assertEquals(result, SERVICE_INSTANCE_NAME); + } + + @Test + public void setInstanceNameRequestScopeNotValidTest() throws ValidateException, RequestDbFailureException { + thrown.expect(ValidateException.class); + thrown.expectMessage( + "requestScope: \"test\" from request: 00032ab7-na18-42e5-965d-8ea592502019 does not match a ModelType enum."); + + resumeReq.getInstanceName(infraActiveRequest, "test", currentActiveRequest); + } + + @Test + public void setInstanceNameVnfTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VNF, currentActiveRequest); + assertEquals(result, VNF_NAME); + } + @Test + public void setInstanceNameVfModuleTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VFMODULE, currentActiveRequest); + assertEquals(result, VFMODULE_NAME); + } + + @Test + public void setInstanceNameNetworkTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, NETWORK, currentActiveRequest); + assertEquals(result, NETWORK_NAME); + } + + @Test + public void setInstanceNameVolumeGroupTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VOLUME_GROUP, currentActiveRequest); + assertEquals(result, VOLUME_GROUP_NAME); + } + + @Test + public void setALaCarteFlagIfNullTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(SERVICE, action); + assertEquals(aLaCarteFlag, false); + } + + @Test + public void setALaCarteFlagIfNullVnfTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, action); + assertEquals(aLaCarteFlag, true); + } + + @Test + public void setALaCarteFlagIfNullRecreateTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, Action.recreateInstance); + assertEquals(aLaCarteFlag, false); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index db6273dc4a..b72e5124d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -28,11 +28,14 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; import static org.onap.so.logger.MdcConstants.CLIENT_ID; import static org.onap.so.logger.MdcConstants.ENDTIME; import static org.onap.so.logger.MdcConstants.INVOCATION_ID; @@ -41,7 +44,6 @@ import static org.onap.so.logger.MdcConstants.RESPONSECODE; import static org.onap.so.logger.MdcConstants.RESPONSEDESC; import static org.onap.so.logger.MdcConstants.SERVICE_NAME; import static org.onap.so.logger.MdcConstants.STATUSCODE; -import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -57,12 +59,18 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.ServiceRecipe; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.serviceinstancebeans.CloudConfiguration; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.RequestReferences; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; @@ -75,7 +83,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.ResourceUtils; import org.springframework.web.util.UriComponentsBuilder; -import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -84,7 +91,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; import ch.qos.logback.classic.spi.ILoggingEvent; - public class ServiceInstancesTest extends BaseTest { private final ObjectMapper mapper = new ObjectMapper(); @@ -93,6 +99,9 @@ public class ServiceInstancesTest extends BaseTest { @Autowired private ServiceInstances servInstances; + @Autowired + private RequestHandlerUtils requestHandlerUtils; + @Value("${wiremock.server.port}") private String wiremockPort; @@ -2748,5 +2757,205 @@ public class ServiceInstancesTest extends BaseTest { "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); } + @Test + public void setServiceTypeTestALaCarte() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = true; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSource("VID"); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceTypeALaCarte"); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceTypeALaCarte"); + } + + @Test + public void setServiceTypeTest() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + + @Test + public void setServiceTypeTestDefault() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + + @Test + public void setServiceTypeTestNetwork() throws JsonProcessingException { + String requestScope = ModelType.network.toString(); + Boolean aLaCarteFlag = null; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelName("networkModelName"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "networkModelName"); + } + + @Test + public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException { + String requestScope = "instanceGroup"; + ServiceInstancesRequest sir = + mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); + assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void setServiceInstanceIdTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void setServiceInstanceIdReturnNullTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertTrue(inProgress); + } + + @Test + public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + + @Test + public void camundaHistoryCheckNotInProgressTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponseCompleted.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + + @Test + public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key); + List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); + String expectedAcceptedType = "application/json"; + assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); + String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); + String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; + assertEquals(expectedBasicAuth, basicAuth); + } + + @Test + public void handleReplaceInstance_Test() throws JsonParseException, JsonMappingException, IOException { + String replaceVfModule = inputStream("/ReplaceVfModule.json"); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(replaceVfModule, ServiceInstancesRequest.class); + Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); + assertEquals(Action.replaceInstance, action); + } + + @Test + public void handleReplaceInstance_retainAssignments_Test() + throws JsonParseException, JsonMappingException, IOException { + String replaceVfModule = inputStream("/ReplaceVfModuleRetainAssignments.json"); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(replaceVfModule, ServiceInstancesRequest.class); + Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); + assertEquals(Action.replaceInstanceRetainAssignments, action); + } + /* + * @Test public void buildSelfLinkUrlTest() throws Exception { // v - version String incomingUrl = + * "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; String expectedSelfLink = + * "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; String requestId = + * "efce3167-5e45-4666-9d4d-22e23648e5d1"; Optional<URL> actualSelfLinkUrl = buildSelfLinkUrl(incomingUrl, + * requestId); assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); // V - Version String + * incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; String + * expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; + * Optional<URL> actualSelfLinkUrlV = buildSelfLinkUrl(incomingUrlV, requestId); assertEquals(expectedSelfLinkV, + * actualSelfLinkUrlV.get().toString()); } + */ } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java index 48abeacbc5..0beab1bd13 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java @@ -87,6 +87,66 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { .withBody(getWiremockResponseForCatalogdb("WorkflowActivitySpecSequence_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching("/workflowActivitySpecSequence/1/activitySpec")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecSequence1_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflowActivitySpecSequence/2/activitySpec")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecSequence2_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflowActivitySpecSequence/3/activitySpec")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecSequence3_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpec/1/activitySpecUserParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecUserParameters1_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpec/2/activitySpecUserParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecUserParameters2_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpec/3/activitySpecUserParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecUserParameters3_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/1/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters1_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/2/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters2_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/3/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters3_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/4/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters4_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/5/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters5_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/6/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters6_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); @@ -237,6 +297,17 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { workflow.setWorkflowActivitySpecSequence(workflowActivitySpecSequences); workflows.add(workflow); + Workflow workflowNative = new Workflow(); + workflowNative.setArtifactUUID("da6478e4-ea33-3346-ac12-ab121284a333"); + workflowNative.setArtifactName("VnfInPlaceUpdate.bpmn"); + workflowNative.setVersion(1.0); + workflowNative.setDescription("native workflow"); + workflowNative.setName("VnfInPlaceUpdate"); + workflowNative.setOperationName("inPlaceSoftwareUpdate"); + workflowNative.setSource("native"); + workflowNative.setResourceTarget("vnf"); + workflows.add(workflowNative); + WorkflowSpecifications workflowSpecifications = workflowSpecificationsHandler.mapWorkflowsToWorkflowSpecifications(workflows); ObjectMapper mapper = new ObjectMapper(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java new file mode 100644 index 0000000000..3644dd8e7f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java @@ -0,0 +1,140 @@ +/*- + * ============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.apihandlerinfra.infra.rest; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.Mockito.doReturn; +import java.io.File; +import java.util.Optional; +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.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class BpmnRequestBuilderTest { + + private static final String RESOURCE_PATH = "src/test/resources/__files/infra/"; + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @InjectMocks + @Spy + BpmnRequestBuilder reqBuilder; + + @Mock + private RequestsDbClient requestDBClient; + + @Mock + private AAIResourcesClient aaiResourcesClient; + + private ObjectMapper mapper = new ObjectMapper(); + + private GraphInventoryCommonObjectMapperProvider provider = new GraphInventoryCommonObjectMapperProvider(); + + @Before + public void setup() { + reqBuilder.setAaiResourcesClient(aaiResourcesClient); + + } + + @Test + public void test_buildServiceInstanceDeleteRequest() throws Exception { + ServiceInstance service = + provider.getMapper().readValue(new File(RESOURCE_PATH + "ServiceInstance.json"), ServiceInstance.class); + + doReturn(service).when(reqBuilder).getServiceInstance("serviceId"); + ServiceInstancesRequest expectedRequest = mapper + .readValue(new File(RESOURCE_PATH + "ExpectedServiceRequest.json"), ServiceInstancesRequest.class); + expectedRequest.getRequestDetails().getModelInfo().setModelId(null); + // bad getter/setter setting multiple fields + ServiceInstancesRequest actualRequest = reqBuilder.buildServiceDeleteRequest("serviceId"); + assertThat(actualRequest, sameBeanAs(expectedRequest)); + } + + @Test + public void test_buildVnfDeleteRequest() throws Exception { + GenericVnf vnf = provider.getMapper().readValue(new File(RESOURCE_PATH + "Vnf.json"), GenericVnf.class); + + doReturn(Optional.of(vnf)).when(aaiResourcesClient).get(GenericVnf.class, + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")); + + ServiceInstancesRequest expectedRequest = + mapper.readValue(new File(RESOURCE_PATH + "ExpectedVnfRequest.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest actualRequest = reqBuilder.buildVnfDeleteRequest("vnfId"); + assertThat(actualRequest, sameBeanAs(expectedRequest)); + } + + @Test + public void test_buildVFModuleDeleteRequest() throws Exception { + GenericVnf vnf = provider.getMapper().readValue(new File(RESOURCE_PATH + "Vnf.json"), GenericVnf.class); + + doReturn(Optional.of(vnf)).when(aaiResourcesClient).get(GenericVnf.class, + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")); + VfModule vfModule = provider.getMapper().readValue(new File(RESOURCE_PATH + "VfModule.json"), VfModule.class); + + doReturn(Optional.of(vfModule)).when(aaiResourcesClient).get(VfModule.class, + AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "vnfId", "vfModuleId")); + + ServiceInstancesRequest expectedRequest = mapper + .readValue(new File(RESOURCE_PATH + "ExpectedVfModuleRequest.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest actualRequest = + reqBuilder.buildVFModuleDeleteRequest("vnfId", "vfModuleId", ModelType.vfModule); + assertThat(actualRequest, sameBeanAs(expectedRequest)); + } + + @Test + public void test_buildVolumeGroupDeleteRequest() throws Exception { + GenericVnf vnf = provider.getMapper().readValue(new File(RESOURCE_PATH + "Vnf.json"), GenericVnf.class); + + doReturn(Optional.of(vnf)).when(aaiResourcesClient).get(GenericVnf.class, + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")); + VolumeGroup volumeGroup = + provider.getMapper().readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class); + + doReturn(Optional.of(volumeGroup)).when(aaiResourcesClient).get(VolumeGroup.class, AAIUriFactory + .createResourceUri(AAIObjectType.VOLUME_GROUP, "cloudOwner", "regionOne", "volumeGroupId")); + + ServiceInstancesRequest expectedRequest = mapper + .readValue(new File(RESOURCE_PATH + "ExpectedVolumeGroupRequest.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest actualRequest = reqBuilder.buildVolumeGroupDeleteRequest("vnfId", "volumeGroupId"); + assertThat(actualRequest, sameBeanAs(expectedRequest)); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java new file mode 100644 index 0000000000..d39192cdf0 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java @@ -0,0 +1,64 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.Mockito.doReturn; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Optional; +import javax.ws.rs.container.ContainerRequestContext; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; +import org.onap.so.serviceinstancebeans.RequestReferences; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; + +@RunWith(MockitoJUnitRunner.class) +public class AbstractRestHandlerTest { + + @Spy + AbstractRestHandler restHandler; + + @Mock + ContainerRequestContext mockRequestContext; + + @Test + public void test_createResponse() throws MalformedURLException { + ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); + RequestReferences requestReferences = new RequestReferences(); + URL selfLinkURL = new URL("http://localhost:8080/v1"); + requestReferences.setInstanceId("instanceId"); + requestReferences.setRequestId("requestId"); + requestReferences.setRequestSelfLink(selfLinkURL); + expectedResponse.setRequestReferences(requestReferences); + + doReturn("http://localhost:8080/v1").when(restHandler).getRequestUri(mockRequestContext); + doReturn(Optional.of(selfLinkURL)).when(restHandler).buildSelfLinkUrl("http://localhost:8080/v1", "requestId"); + ServiceInstancesResponse actualResponse = + restHandler.createResponse("instanceId", "requestId", mockRequestContext); + assertThat(actualResponse, sameBeanAs(expectedResponse)); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java new file mode 100644 index 0000000000..8ff7517da8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java @@ -0,0 +1,143 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.container.ContainerRequestContext; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.handler.NetworkRestHandler; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class NetworkRestHandlerTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @InjectMocks + NetworkRestHandler restHandler; + + @Mock + ContainerRequestContext mockRequestContext; + + @Mock + private CatalogDbClient catalogDbClient; + + @Mock + private RequestsDbClient infraActiveRequestsClient; + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException { + ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class); + restHandler.checkDuplicateRequest("serviceInstanceId", "networkId", "instanceName", "requestId"); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate( + instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.network.toString())); + Map actualMap = instanceIdCaptor.getValue(); + assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId")); + assertEquals("NetworkId should exit in map", "networkId", actualMap.get("networkInstanceId")); + } + + @Test + public void test_saveInstanceName() throws MalformedURLException, NoRecipeException { + ServiceInstancesRequest request = createTestRequest(); + InfraActiveRequests dbRequest = createDatabaseRecord(); + restHandler.saveInstanceName(request, dbRequest); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest); + assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getNetworkName()); + } + + @Test + public void test_buildRequestParams() throws Exception { + RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId") + .setServiceInstanceId("serviceInstanceId").setNetworkId("networkId").setALaCarte(true) + .setRequestDetails(mapper.writeValueAsString(createTestRequest())) + .setRequestAction(Action.deleteInstance.toString()) + .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build(); + RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(), + "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "networkId"); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void test_createInfraActiveRequestForDelete() throws Exception { + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setRequestAction(Action.deleteInstance.toString()); + expected.setAction(Action.deleteInstance.toString()); + expected.setServiceInstanceId("serviceInstanceId"); + expected.setNetworkId("networkId"); + expected.setRequestId("requestId"); + expected.setRequestorId("userId"); + expected.setSource("VID"); + expected.setRequestStatus(Status.IN_PROGRESS.toString()); + expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + expected.setRequestScope(ModelType.network.toString()); + expected.setRequestUrl("http://localhost:9090"); + InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "serviceInstanceId", + "networkId", "userId", "VID", "http://localhost:9090"); + assertThat(actual, sameBeanAs(expected).ignoring("startTime")); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual); + } + + private ServiceInstancesRequest createTestRequest() { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setInstanceName("instanceName"); + requestDetails.setRequestInfo(requestInfo); + request.setRequestDetails(requestDetails); + return request; + } + + private InfraActiveRequests createDatabaseRecord() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + return request; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java new file mode 100644 index 0000000000..56d57aa2d5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java @@ -0,0 +1,189 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.container.ContainerRequestContext; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException; +import org.onap.so.apihandlerinfra.infra.rest.handler.ServiceInstanceRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.ServiceRecipe; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class ServiceInstanceRestHandlerTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @InjectMocks + ServiceInstanceRestHandler restHandler; + + @Mock + ContainerRequestContext mockRequestContext; + + @Mock + private CatalogDbClient catalogDbClient; + + @Mock + private RequestsDbClient infraActiveRequestsClient; + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void test_find_service_recipe() throws MalformedURLException, NoRecipeException { + ServiceRecipe expected = new ServiceRecipe(); + expected.setAction("createInstance"); + doReturn(expected).when(catalogDbClient) + .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId"); + Recipe actual = restHandler.findServiceRecipe("testModelId", Action.createInstance.toString()); + assertThat(actual, sameBeanAs(expected)); + Mockito.verify(catalogDbClient, Mockito.times(1)) + .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId"); + } + + @Test + public void test_find_service_recipe_default_recipe() throws MalformedURLException, NoRecipeException { + ServiceRecipe expected = new ServiceRecipe(); + expected.setAction("createInstance"); + doReturn(null).when(catalogDbClient) + .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId"); + doReturn(expected).when(catalogDbClient).findServiceRecipeByActionAndServiceModelUUID( + Action.createInstance.toString(), "d88da85c-d9e8-4f73-b837-3a72a431622b"); + Recipe actual = restHandler.findServiceRecipe("testModelId", Action.createInstance.toString()); + assertThat(actual, sameBeanAs(expected)); + Mockito.verify(catalogDbClient, Mockito.times(1)) + .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId"); + Mockito.verify(catalogDbClient, Mockito.times(1)).findServiceRecipeByActionAndServiceModelUUID( + Action.createInstance.toString(), "d88da85c-d9e8-4f73-b837-3a72a431622b"); + } + + @Test + public void test_find_service_recipe_not_found() throws MalformedURLException, NoRecipeException { + ServiceRecipe expected = new ServiceRecipe(); + expected.setAction("createInstance"); + doReturn(null).when(catalogDbClient) + .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId"); + doReturn(null).when(catalogDbClient).findServiceRecipeByActionAndServiceModelUUID( + Action.createInstance.toString(), "d88da85c-d9e8-4f73-b837-3a72a431622b"); + exceptionRule.expect(NoRecipeException.class); + exceptionRule.expectMessage( + "Unable to locate custom or default recipe for, Action: createInstance, Model UUID: testModelId"); + restHandler.findServiceRecipe("testModelId", Action.createInstance.toString()); + } + + @Test + public void test_checkDuplicateRequest() + throws MalformedURLException, NoRecipeException, RequestConflictedException { + ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class); + restHandler.checkDuplicateRequest("serviceInstanceId", "instanceName", "requestId"); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate( + instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.service.toString())); + Map actualMap = instanceIdCaptor.getValue(); + assertEquals("serviceInstanceId", actualMap.get("serviceInstanceId")); + } + + @Test + public void test_saveInstanceName() throws MalformedURLException, NoRecipeException { + ServiceInstancesRequest request = createTestRequest(); + InfraActiveRequests dbRequest = createDatabaseRecord(); + restHandler.saveInstanceName(request, dbRequest); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest); + assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getServiceInstanceName()); + } + + @Test + public void test_buildRequestParams() throws Exception { + RequestClientParameter expected = + new RequestClientParameter.Builder().setRequestId("requestId").setServiceInstanceId("serviceInstanceId") + .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(createTestRequest())) + .setRequestAction(Action.deleteInstance.toString()) + .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build(); + RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(), + "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId"); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void test_createInfraActiveRequestForDelete() throws Exception { + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setRequestAction(Action.deleteInstance.toString()); + expected.setAction(Action.deleteInstance.toString()); + expected.setServiceInstanceId("serviceInstanceId"); + expected.setRequestId("requestId"); + expected.setRequestorId("userId"); + expected.setSource("VID"); + expected.setRequestStatus(Status.IN_PROGRESS.toString()); + expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + expected.setRequestUrl("http://localhost:9090"); + expected.setRequestScope(ModelType.service.toString()); + InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "serviceInstanceId", + "userId", "VID", "http://localhost:9090"); + assertThat(actual, sameBeanAs(expected).ignoring("startTime")); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual); + } + + private ServiceInstancesRequest createTestRequest() { + + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setInstanceName("instanceName"); + requestDetails.setRequestInfo(requestInfo); + request.setRequestDetails(requestDetails); + return request; + } + + private InfraActiveRequests createDatabaseRecord() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + return request; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java new file mode 100644 index 0000000000..280ae9c071 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java @@ -0,0 +1,190 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.container.ContainerRequestContext; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.handler.VFModuleRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.VnfComponentsRecipe; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class VfModuleRestHandlerTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @InjectMocks + VFModuleRestHandler restHandler; + + @Mock + ContainerRequestContext mockRequestContext; + + @Mock + private CatalogDbClient catalogDbClient; + + @Mock + private RequestsDbClient infraActiveRequestsClient; + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void test_find_vf_module_recipe() throws MalformedURLException, NoRecipeException { + VnfComponentsRecipe expected = new VnfComponentsRecipe(); + expected.setAction("createInstance"); + doReturn(expected).when(catalogDbClient) + .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("testModelId", + ModelType.vfModule.toString(), Action.createInstance.toString()); + Recipe actual = restHandler.findVfModuleRecipe("testModelId", ModelType.vfModule.toString(), + Action.createInstance.toString()); + assertThat(actual, sameBeanAs(expected)); + Mockito.verify(catalogDbClient, Mockito.times(1)) + .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("testModelId", + ModelType.vfModule.toString(), Action.createInstance.toString()); + } + + @Test + public void test_find_vf_module_recipe_default_recipe() throws MalformedURLException, NoRecipeException { + VnfComponentsRecipe expected = new VnfComponentsRecipe(); + expected.setAction("createInstance"); + doReturn(null).when(catalogDbClient).getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + "testModelId", ModelType.vfModule.toString(), Action.createInstance.toString()); + doReturn(expected).when(catalogDbClient) + .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("GR-API-DEFAULT", + ModelType.vfModule.toString(), Action.createInstance.toString()); + Recipe actual = restHandler.findVfModuleRecipe("testModelId", ModelType.vfModule.toString(), + Action.createInstance.toString()); + assertThat(actual, sameBeanAs(expected)); + Mockito.verify(catalogDbClient, Mockito.times(1)) + .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("testModelId", + ModelType.vfModule.toString(), Action.createInstance.toString()); + } + + @Test + public void test_find_vf_module_recipe_not_found() throws MalformedURLException, NoRecipeException { + VnfComponentsRecipe expected = new VnfComponentsRecipe(); + expected.setAction("createInstance"); + exceptionRule.expect(NoRecipeException.class); + exceptionRule.expectMessage( + "Unable to locate custom or default recipe for ModelType: vfModule , Action: createInstance, CustomizationId: testModelId"); + restHandler.findVfModuleRecipe("testModelId", ModelType.vfModule.toString(), Action.createInstance.toString()); + } + + @Test + public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException { + ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class); + restHandler.checkDuplicateRequest("serviceInstanceId", "vnfId", "vfModuleId", "instanceName", "requestId"); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate( + instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.vfModule.toString())); + Map actualMap = instanceIdCaptor.getValue(); + assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId")); + assertEquals("VnfId should exit in map", "vnfId", actualMap.get("vnfInstanceId")); + assertEquals("VFModuleId should exit in map", "vfModuleId", actualMap.get("vfModuleInstanceId")); + } + + @Test + public void test_saveInstanceName() throws MalformedURLException, NoRecipeException { + ServiceInstancesRequest request = createTestRequest(); + InfraActiveRequests dbRequest = createDatabaseRecord(); + restHandler.saveInstanceName(request, dbRequest); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest); + assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getVfModuleName()); + } + + @Test + public void test_buildRequestParams() throws Exception { + RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId") + .setServiceInstanceId("serviceInstanceId").setVnfId("vnfId").setVfModuleId("vfModuleId") + .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(createTestRequest())) + .setRequestAction(Action.deleteInstance.toString()) + .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build(); + RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(), + "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "vnfId", "vfModuleId"); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void test_createInfraActiveRequestForDelete() throws Exception { + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setRequestAction(Action.deleteInstance.toString()); + expected.setAction(Action.deleteInstance.toString()); + expected.setServiceInstanceId("serviceInstanceId"); + expected.setVnfId("vnfId"); + expected.setVfModuleId("vfModuleId"); + expected.setRequestId("requestId"); + expected.setRequestorId("userId"); + expected.setSource("VID"); + expected.setRequestStatus(Status.IN_PROGRESS.toString()); + expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + expected.setRequestUrl("http://localhost:9090"); + expected.setRequestScope(ModelType.vfModule.toString()); + InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "vfModuleId", + "serviceInstanceId", "vnfId", "userId", "VID", "http://localhost:9090"); + assertThat(actual, sameBeanAs(expected).ignoring("startTime")); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual); + } + + private ServiceInstancesRequest createTestRequest() { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setInstanceName("instanceName"); + requestDetails.setRequestInfo(requestInfo); + request.setRequestDetails(requestDetails); + return request; + } + + private InfraActiveRequests createDatabaseRecord() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + return request; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java new file mode 100644 index 0000000000..2ea537b6ad --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java @@ -0,0 +1,154 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.container.ContainerRequestContext; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.handler.VnfRestHandler; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.ServiceRecipe; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class VnfRestHandlerTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @InjectMocks + VnfRestHandler restHandler; + + @Mock + ContainerRequestContext mockRequestContext; + + @Mock + private CatalogDbClient catalogDbClient; + + @Mock + private RequestsDbClient infraActiveRequestsClient; + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void test_find_vnf_recipe() throws MalformedURLException, NoRecipeException { + ServiceRecipe expected = new ServiceRecipe(); + expected.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + Recipe actual = restHandler.findVnfModuleRecipe("testModelId", ModelType.vnf.toString(), + Action.createInstance.toString()); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException { + ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class); + restHandler.checkDuplicateRequest("serviceInstanceId", "vnfId", "instanceName", "requestId"); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate( + instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.vnf.toString())); + Map actualMap = instanceIdCaptor.getValue(); + assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId")); + assertEquals("VnfId should exit in map", "vnfId", actualMap.get("vnfInstanceId")); + } + + @Test + public void test_saveInstanceName() throws MalformedURLException, NoRecipeException { + ServiceInstancesRequest request = createTestRequest(); + InfraActiveRequests dbRequest = createDatabaseRecord(); + restHandler.saveInstanceName(request, dbRequest); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest); + assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getVnfName()); + } + + @Test + public void test_buildRequestParams() throws Exception { + RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId") + .setServiceInstanceId("serviceInstanceId").setVnfId("vnfId").setALaCarte(true) + .setRequestDetails(mapper.writeValueAsString(createTestRequest())) + .setRequestAction(Action.deleteInstance.toString()) + .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build(); + RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(), + "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "vnfId"); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void test_createInfraActiveRequestForDelete() throws Exception { + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setRequestAction(Action.deleteInstance.toString()); + expected.setAction(Action.deleteInstance.toString()); + expected.setServiceInstanceId("serviceInstanceId"); + expected.setVnfId("vnfId"); + expected.setRequestId("requestId"); + expected.setRequestorId("userId"); + expected.setSource("VID"); + expected.setRequestStatus(Status.IN_PROGRESS.toString()); + expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + expected.setRequestUrl("http://localhost:9090"); + expected.setRequestScope(ModelType.vnf.toString()); + InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "serviceInstanceId", + "vnfId", "userId", "VID", "http://localhost:9090"); + assertThat(actual, sameBeanAs(expected).ignoring("startTime")); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual); + } + + private ServiceInstancesRequest createTestRequest() { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setInstanceName("instanceName"); + requestDetails.setRequestInfo(requestInfo); + request.setRequestDetails(requestDetails); + return request; + } + + private InfraActiveRequests createDatabaseRecord() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + return request; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java new file mode 100644 index 0000000000..2721f8a14a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java @@ -0,0 +1,145 @@ +/*- + * ============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.apihandlerinfra.infra.rest.handler; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.container.ContainerRequestContext; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.Constants; +import org.onap.so.apihandlerinfra.Status; +import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; +import org.onap.so.apihandlerinfra.infra.rest.handler.VolumeRestHandler; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class VolumeRestHandlerTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @InjectMocks + VolumeRestHandler restHandler; + + @Mock + ContainerRequestContext mockRequestContext; + + @Mock + private CatalogDbClient catalogDbClient; + + @Mock + private RequestsDbClient infraActiveRequestsClient; + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException { + ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class); + restHandler.checkDuplicateRequest("serviceInstanceId", "vnfId", "volumeGroupId", "instanceName", "requestId"); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate( + instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.volumeGroup.toString())); + Map actualMap = instanceIdCaptor.getValue(); + assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId")); + assertEquals("VnfId should exit in map", "vnfId", actualMap.get("vnfInstanceId")); + assertEquals("VolumeGroupId should exit in map", "volumeGroupId", actualMap.get("volumeGroupInstanceId")); + } + + @Test + public void test_saveInstanceName() throws MalformedURLException, NoRecipeException { + ServiceInstancesRequest request = createTestRequest(); + InfraActiveRequests dbRequest = createDatabaseRecord(); + restHandler.saveInstanceName(request, dbRequest); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest); + assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getVolumeGroupName()); + } + + @Test + public void test_buildRequestParams() throws Exception { + RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId") + .setServiceInstanceId("serviceInstanceId").setVnfId("vnfId").setVolumeGroupId("volumeGroupId") + .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(createTestRequest())) + .setRequestAction(Action.deleteInstance.toString()) + .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build(); + RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(), + "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "vnfId", "volumeGroupId"); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void test_createInfraActiveRequestForDelete() throws Exception { + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setRequestAction(Action.deleteInstance.toString()); + expected.setAction(Action.deleteInstance.toString()); + expected.setServiceInstanceId("serviceInstanceId"); + expected.setVnfId("vnfId"); + expected.setVolumeGroupId("volumeGroupId"); + expected.setRequestId("requestId"); + expected.setRequestorId("userId"); + expected.setSource("VID"); + expected.setRequestStatus(Status.IN_PROGRESS.toString()); + expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + expected.setRequestScope(ModelType.volumeGroup.toString()); + expected.setRequestUrl("http://localhost:9090"); + InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "volumeGroupId", + "serviceInstanceId", "vnfId", "userId", "VID", "http://localhost:9090"); + assertThat(actual, sameBeanAs(expected).ignoring("startTime")); + Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual); + } + + private ServiceInstancesRequest createTestRequest() { + ServiceInstancesRequest request = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setInstanceName("instanceName"); + requestDetails.setRequestInfo(requestInfo); + request.setRequestDetails(requestDetails); + return request; + } + + private InfraActiveRequests createDatabaseRecord() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + return request; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java index 54da0baa92..93a19a9531 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java @@ -25,15 +25,38 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.RelatedInstanceList; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import com.fasterxml.jackson.databind.ObjectMapper; public class RelatedInstancesValidationTest extends BaseTest { + RelatedInstancesValidation validation = new RelatedInstancesValidation(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public ValidationInformation setupValidationInformation(String path) throws IOException { + String jsonInput = new String(Files.readAllBytes(Paths.get(path))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, + sir.getRequestDetails().getRequestParameters()); + + info.setRequestScope("service"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); + + info.setRequestInfo(sir.getRequestDetails().getRequestInfo()); + return info; + } + @Test public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException { String requestJson = new String(Files.readAllBytes( @@ -50,4 +73,64 @@ public class RelatedInstancesValidationTest extends BaseTest { assertEquals(info.getVnfType(), "Test/name"); } + + @Test + public void testCreateSIVpnBonding() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 7, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("service"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); + RelatedInstancesValidation validation = new RelatedInstancesValidation(); + validation.validate(info); + RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList(); + + assertEquals(info.getRequestScope(), "service"); + assertEquals(instanceList[0].getRelatedInstance().getModelInfo().getModelType().toString(), "vpnBinding"); + assertEquals(instanceList[1].getRelatedInstance().getModelInfo().getModelType().toString(), "network"); + } + + @Test + public void validateModelTypeExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid modelType in relatedInstance is specified"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/VpnBondingValidation/NoModelType.json")); + } + + @Test + public void validateInstanceNameVpnBindingExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid instanceName in relatedInstance for vpnBinding modelType is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json")); + } + + @Test + public void validateInstanceNameNetworkExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid instanceName in relatedInstance for network modelType is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json")); + } + + @Test + public void validateInstanceIdExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid instanceId in relatedInstance is specified"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json")); + } + + @Test + public void validatemodelInvariantIdExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid modelInvariantId in relatedInstance is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json new file mode 100644 index 0000000000..573b7a3ebb --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json @@ -0,0 +1,57 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json index 5cd31427a0..d6406338a0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json @@ -1,5 +1,11 @@ { "requestDetails":{ + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion": "1.0", + "modelType":"service", + "modelName":"serviceModel" + }, "requestInfo":{ "source":"VID", "requestorId":"xxxxxx", diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json new file mode 100644 index 0000000000..740d4e2ec2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json @@ -0,0 +1,19 @@ +{ + "requestDetails":{ + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion": "1.0", + "modelType":"service", + "modelName":"serviceModel" + }, + "requestInfo":{ + "source":"VID", + "requestorId":"yyyyyy", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "aLaCarte":"false" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json new file mode 100644 index 0000000000..166f7ccce8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json @@ -0,0 +1,33 @@ +{ + "requestDetails": { + "requestInfo": { + "source": "VID", + "requestorId": "xxxxxx", + "instanceName": "testService60" + }, + "requestParameters": { + "aLaCarte": true, + "autoBuildVfModules": false, + "retainAssignments": true, + "subscriptionServiceType": "test" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7968", + "modelVersion":"2", + "modelVersionId":"78ca26d0-246d-11e7-93ae-92361f002671", + "modelType":"vfModule", + "modelName":"serviceModel", + "modelCustomizationId": "a7f1d08e-b02d-11e6-80f5-76304dec7eb7" + }, + "subscriberInfo": { + "globalSubscriberId": "MSO_1610_dev", + "subscriberName": "MSO_1610_dev" + } + } +} + +
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json new file mode 100644 index 0000000000..573b7a3ebb --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json @@ -0,0 +1,57 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json new file mode 100644 index 0000000000..97e480c8d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json new file mode 100644 index 0000000000..f7ba4761b6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json new file mode 100644 index 0000000000..ac570b3830 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json new file mode 100644 index 0000000000..ca02c5371a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json @@ -0,0 +1,57 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vnf" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "service" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json new file mode 100644 index 0000000000..1d46ce2ccd --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence1_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence1_Response.json new file mode 100644 index 0000000000..37e32631fb --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence1_Response.json @@ -0,0 +1,20 @@ +{ + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF", + "version": null, + "created": null, + "activitySpecActivitySpecCategories": null, + "activitySpecActivitySpecParameters": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpec/1" + }, + "activitySpec": { + "href": "http://localhost:8090/activitySpec/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpec/1/activitySpecUserParameters" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence2_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence2_Response.json new file mode 100644 index 0000000000..ee2a02ba33 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence2_Response.json @@ -0,0 +1,20 @@ +{ + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF", + "version": null, + "created": null, + "activitySpecActivitySpecCategories": null, + "activitySpecActivitySpecParameters": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpec/2" + }, + "activitySpec": { + "href": "http://localhost:8090/activitySpec/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpec/2/activitySpecUserParameters" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence3_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence3_Response.json new file mode 100644 index 0000000000..69390eea6b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence3_Response.json @@ -0,0 +1,20 @@ +{ + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow", + "version": null, + "created": null, + "activitySpecActivitySpecCategories": null, + "activitySpecActivitySpecParameters": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpec/3" + }, + "activitySpec": { + "href": "http://localhost:8090/activitySpec/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpec/3/activitySpecUserParameters" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters1_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters1_Response.json new file mode 100644 index 0000000000..e88691b4d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters1_Response.json @@ -0,0 +1,103 @@ +{ + "_embedded": { + "activitySpecUserParameters": [ + { + "activitySpecId": 1, + "userParametersId": 1, + "activitySpec": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 2, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 3, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 4, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 5, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 6, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6/userParameters" + } + } + } + ] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters2_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters2_Response.json new file mode 100644 index 0000000000..e88691b4d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters2_Response.json @@ -0,0 +1,103 @@ +{ + "_embedded": { + "activitySpecUserParameters": [ + { + "activitySpecId": 1, + "userParametersId": 1, + "activitySpec": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 2, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 3, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 4, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 5, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 6, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6/userParameters" + } + } + } + ] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters3_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters3_Response.json new file mode 100644 index 0000000000..e88691b4d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters3_Response.json @@ -0,0 +1,103 @@ +{ + "_embedded": { + "activitySpecUserParameters": [ + { + "activitySpecId": 1, + "userParametersId": 1, + "activitySpec": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 2, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 3, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 4, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 5, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 6, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6/userParameters" + } + } + } + ] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters1_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters1_Response.json new file mode 100644 index 0000000000..017add4cd5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters1_Response.json @@ -0,0 +1,13 @@ +{ + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters2_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters2_Response.json new file mode 100644 index 0000000000..655d659c16 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters2_Response.json @@ -0,0 +1,13 @@ +{ + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters3_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters3_Response.json new file mode 100644 index 0000000000..13e02e7dd6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters3_Response.json @@ -0,0 +1,13 @@ +{ + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters4_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters4_Response.json new file mode 100644 index 0000000000..e30ec0da88 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters4_Response.json @@ -0,0 +1,13 @@ +{ + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters5_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters5_Response.json new file mode 100644 index 0000000000..98b18522da --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters5_Response.json @@ -0,0 +1,13 @@ +{ + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters6_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters6_Response.json new file mode 100644 index 0000000000..4d8d03b6a7 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters6_Response.json @@ -0,0 +1,13 @@ +{ + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json index 3192865b52..3df17380d6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json @@ -1,432 +1,54 @@ { "_embedded": { - - "workflowActivitySpecSequence": [ - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFQuiesceTrafficActivity", - "description": "Activity to QuiesceTraffic on VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFHealthCheckActivity", - "description": "Activity to HealthCheck VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "FlowCompleteActivity", - "description": "Activity to Complete the BPMN Flow", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - } - ] - -} + "workflowActivitySpecSequence": [ + { + "activitySpecId": 1, + "workflowId": 1, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflowActivitySpecSequence//1/workflowActivitySpecSequence" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflowActivitySpecSequence/1/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflowActivitySpecSequence/1/activitySpec" + } + } + }, + { + "activitySpecId": 2, + "workflowId": 1, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflowActivitySpecSequence/2/workflowActivitySpecSequence" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflowActivitySpecSequence/2/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflowActivitySpecSequence/2/activitySpec" + } + } + }, + { + "activitySpecId": 3, + "workflowId": 1, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflowActivitySpecSequence/3" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflowActivitySpecSequence/3/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflowActivitySpecSequence/3/activitySpec" + } + } + } + ] + } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json index 5556c602be..59bc12d92d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json @@ -108,6 +108,23 @@ } ] } + }, + { + "workflowSpecification": { + + "artifactInfo": { + "artifactType": "workflow", + "artifactUuid": "da6478e4-ea33-3346-ac12-ab121284a333", + "artifactName": "VnfInPlaceUpdate.bpmn", + "artifactVersion": "1.0", + "artifactDescription": "native workflow", + "workflowName": "VnfInPlaceUpdate", + "operationName": "inPlaceSoftwareUpdate", + "workflowSource": "native", + "workflowResourceTarget": "vnf" + }, + "workflowInputParameters": [] + } } ] } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json index c12365649e..8919dbbf2c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json @@ -1,468 +1,504 @@ { "_embedded": { - "workflows" :[ - { - "artifactUUID": "ab6478e4-ea33-3346-ac12-ab121484a333", - "artifactName": "inPlaceSoftwareUpdate-1_0.bpmn", - "name": "inPlaceSoftwareUpdate", - "operationName": "inPlaceSoftwareUpdate", - "version": 1, - "description": "xyz xyz", - "body": null, - "resourceTarget": "vnf", - "source": "sdc", - "timeoutMinutes": null, - "artifactChecksum": null, - "created": null, - "vnfResourceWorkflow": null, - "workflowActivitySpecSequence": [ - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFQuiesceTrafficActivity", - "description": "Activity to QuiesceTraffic on VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFHealthCheckActivity", - "description": "Activity to HealthCheck VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "FlowCompleteActivity", - "description": "Activity to Complete the BPMN Flow", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - } - ], - "id": null, - - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/1/workflowActivitySpecSequence" - } - - } - - } -] -}, -"_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } + "workflows": [ + { + "artifactUUID": "ab6478e4-ea33-3346-ac12-ab121484a333", + "artifactName": "inPlaceSoftwareUpdate-1_0.bpmn", + "name": "inPlaceSoftwareUpdate", + "operationName": "inPlaceSoftwareUpdate", + "version": 1, + "description": "xyz xyz", + "body": null, + "resourceTarget": "vnf", + "source": "sdc", + "timeoutMinutes": null, + "artifactChecksum": null, + "created": null, + "vnfResourceWorkflow": null, + "workflowActivitySpecSequence": [ + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + } + ], + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/1/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + }, + { + "artifactUUID": "da6478e4-ea33-3346-ac12-ab121284a333", + "artifactName": "VnfInPlaceUpdate.bpmn", + "name": "VnfInPlaceUpdate", + "operationName": "inPlaceSoftwareUpdate", + "version": 1, + "description": "native workflow", + "body": null, + "resourceTarget": "vnf", + "source": "native", + "timeoutMinutes": null, + "artifactChecksum": null, + "created": null, + "vnfResourceWorkflow": null, + "workflowActivitySpecSequence": [], + "id": null, + "workflow": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflows/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + } + ] + }, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json index 6e358f7e17..d6ed585537 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json @@ -1,4 +1,5 @@ { "artifactUUID": "71526781-e55c-4cb7-adb3-97e09d9c76be", - "artifactName": "testingWorkflow" + "artifactName": "testingWorkflow.bpmn", + "name": "testingWorkflow" }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json new file mode 100644 index 0000000000..3ad3d1efec --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json @@ -0,0 +1,20 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelVersionId": "bad955c3-29b2-4a27-932e-28e942cc6480", + "modelUuid": "bad955c3-29b2-4a27-932e-28e942cc6480" + }, + "requestInfo": { + "instanceName": "Robot_SI_For_VolumeGroup", + "suppressRollback": false + }, + "requestParameters": { + "userParams": [], + "aLaCarte": true, + "testApi": "GR_API" + }, + "instanceName": [], + "configurationParameters": [] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json new file mode 100644 index 0000000000..9670c3b645 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json @@ -0,0 +1,25 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "vfModule", + "modelCustomizationUuid": "074c64d0-7e13-4bcc-8bdb-ea922331102d", + "modelCustomizationId": "074c64d0-7e13-4bcc-8bdb-ea922331102d" + }, + "requestInfo": { + "instanceName": "dummy_id", + "suppressRollback": false + }, + "cloudConfiguration": { + "tenantId": "0422ffb57ba042c0800a29dc85ca70f8", + "cloudOwner": "cloudOwner", + "lcpCloudRegionId": "regionOne" + }, + "requestParameters": { + "userParams": [], + "aLaCarte": true, + "testApi": "GR_API" + }, + "instanceName": [], + "configurationParameters": [] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json new file mode 100644 index 0000000000..59602f7ac2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json @@ -0,0 +1,20 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "vnf", + "modelCustomizationUuid": "96c23a4a-6887-4b2c-9cce-1e4ea35eaade", + "modelCustomizationId": "96c23a4a-6887-4b2c-9cce-1e4ea35eaade" + }, + "requestInfo": { + "instanceName": "Robot_VNF_For_Volume_Group", + "suppressRollback": false + }, + "requestParameters": { + "userParams": [], + "aLaCarte": true, + "testApi": "GR_API" + }, + "instanceName": [], + "configurationParameters": [] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json new file mode 100644 index 0000000000..ec7acf1e41 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json @@ -0,0 +1,25 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "volumeGroup", + "modelCustomizationUuid": "e38906fa-717c-49b0-b391-e6ec12b50c4a", + "modelCustomizationId": "e38906fa-717c-49b0-b391-e6ec12b50c4a" + }, + "requestInfo": { + "instanceName": "VolumeGroup", + "suppressRollback": false + }, + "cloudConfiguration": { + "tenantId": "0422ffb57ba042c0800a29dc85ca70f8", + "cloudOwner": "cloudOwner", + "lcpCloudRegionId": "regionOne" + }, + "requestParameters": { + "userParams": [], + "aLaCarte": true, + "testApi": "GR_API" + }, + "instanceName": [], + "configurationParameters": [] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json new file mode 100644 index 0000000000..7d7a103123 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json @@ -0,0 +1,35 @@ +{ + "service-instance-id": "e9fbfab4-d91c-4508-a429-2046c8751371", + "service-instance-name": "Robot_SI_For_VolumeGroup", + "environment-context": "General_Revenue-Bearing", + "model-invariant-id": "b16a9398-ffa3-4041-b78c-2956b8ad9c7b", + "model-version-id": "bad955c3-29b2-4a27-932e-28e942cc6480", + "resource-version": "1560538276937", + "orchestration-status": "Active", + "relationship-list": { + "relationship": [ + { + "related-to": "project", + "relationship-label": "org.onap.relationships.inventory.Uses", + "related-link": "/aai/v15/business/projects/project/GR_API_OE_MSO_Test200", + "relationship-data": [ + { + "relationship-key": "project.project-name", + "relationship-value": "GR_API_OE_MSO_Test200" + } + ] + }, + { + "related-to": "owning-entity", + "relationship-label": "org.onap.relationships.inventory.BelongsTo", + "related-link": "/aai/v15/business/owning-entities/owning-entity/c3f57fa8-ac7d-11e8-98d0-529269fb1459", + "relationship-data": [ + { + "relationship-key": "owning-entity.owning-entity-id", + "relationship-value": "c3f57fa8-ac7d-11e8-98d0-529269fb1459" + } + ] + } + ] + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json new file mode 100644 index 0000000000..cfd9eb3e3c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json @@ -0,0 +1,37 @@ +{ + "vf-module-id": "b70060b7-0031-4065-9462-3cd5b753d2db", + "vf-module-name": "dummy_id", + "heat-stack-id": "dummy_id/stackId", + "orchestration-status": "Active", + "is-base-vf-module": true, + "automated-assignment": false, + "resource-version": "1560538368229", + "model-invariant-id": "f7a867f2-596b-4f4a-a128-421e825a6190", + "model-version-id": "eb5de6fb-9ecf-4009-b922-fae3a9ae7d46", + "model-customization-id": "074c64d0-7e13-4bcc-8bdb-ea922331102d", + "module-index": 0, + "selflink": "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/e9fbfab4-d91c-4508-a429-2046c8751371/service-data/vnfs/vnf/829924cc-8932-4875-b0af-d7a02799da9a/vnf-data//vf-modules/vf-module/dummy_id/vf-module-data/vf-module-topology/", + "relationship-list": { + "relationship": [ + { + "related-to": "volume-group", + "relationship-label": "org.onap.relationships.inventory.Uses", + "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/volume-groups/volume-group/18b220c8-af84-4b82-a8c0-41bbea6328a6", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "cloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "regionOne" + }, + { + "relationship-key": "volume-group.volume-group-id", + "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6" + } + ] + } + ] + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json new file mode 100644 index 0000000000..09f6d81da3 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json @@ -0,0 +1,131 @@ +{ + "vnf-id": "829924cc-8932-4875-b0af-d7a02799da9a", + "vnf-name": "Robot_VNF_For_Volume_Group", + "vnf-type": "Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0", + "service-id": "06f76284-8710-11e6-ae22-56b6b6499611", + "prov-status": "PREPROV", + "orchestration-status": "Active", + "in-maint": false, + "is-closed-loop-disabled": false, + "resource-version": "1560538316260", + "model-invariant-id": "23122c9b-dd7f-483f-bf0a-e069303db2f7", + "model-version-id": "d326f424-2312-4dd6-b7fe-364fadbd1ef5", + "model-customization-id": "96c23a4a-6887-4b2c-9cce-1e4ea35eaade", + "selflink": "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/e9fbfab4-d91c-4508-a429-2046c8751371/service-data/vnfs/vnf/829924cc-8932-4875-b0af-d7a02799da9a/vnf-data/vnf-topology/", + "relationship-list": { + "relationship": [ + { + "related-to": "service-instance", + "relationship-label": "org.onap.relationships.inventory.ComposedOf", + "related-link": "/aai/v15/business/customers/customer/Robot_Test_Subscriber_ID/service-subscriptions/service-subscription/Robot_Test_Service_Type/service-instances/service-instance/e9fbfab4-d91c-4508-a429-2046c8751371", + "relationship-data": [ + { + "relationship-key": "customer.global-customer-id", + "relationship-value": "Robot_Test_Subscriber_ID" + }, + { + "relationship-key": "service-subscription.service-type", + "relationship-value": "Robot_Test_Service_Type" + }, + { + "relationship-key": "service-instance.service-instance-id", + "relationship-value": "e9fbfab4-d91c-4508-a429-2046c8751371" + } + ], + "related-to-property": [ + { + "property-key": "service-instance.service-instance-name", + "property-value": "Robot_SI_For_VolumeGroup" + } + ] + }, + { + "related-to": "platform", + "relationship-label": "org.onap.relationships.inventory.Uses", + "related-link": "/aai/v15/business/platforms/platform/vSAMP12_14-2XXX-Aug18-9001%20-%20Platform", + "relationship-data": [ + { + "relationship-key": "platform.platform-name", + "relationship-value": "vSAMP12_14-2XXX-Aug18-9001 - Platform" + } + ] + }, + { + "related-to": "line-of-business", + "relationship-label": "org.onap.relationships.inventory.Uses", + "related-link": "/aai/v15/business/lines-of-business/line-of-business/vSAMP12_14-2XXX-Aug18-9001%20-%20LOB", + "relationship-data": [ + { + "relationship-key": "line-of-business.line-of-business-name", + "relationship-value": "vSAMP12_14-2XXX-Aug18-9001 - LOB" + } + ] + }, + { + "related-to": "tenant", + "relationship-label": "org.onap.relationships.inventory.BelongsTo", + "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/tenants/tenant/0422ffb57ba042c0800a29dc85ca70f8", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "cloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "regionOne" + }, + { + "relationship-key": "tenant.tenant-id", + "relationship-value": "0422ffb57ba042c0800a29dc85ca70f8" + } + ], + "related-to-property": [ + { + "property-key": "tenant.tenant-name", + "property-value": "tenantName" + } + ] + }, + { + "related-to": "volume-group", + "relationship-label": "org.onap.relationships.inventory.DependsOn", + "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/volume-groups/volume-group/volumeGroupId", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "cloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "regionOne" + }, + { + "relationship-key": "volume-group.volume-group-id", + "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6" + } + ] + }, + { + "related-to": "cloud-region", + "relationship-label": "org.onap.relationships.inventory.LocatedIn", + "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "cloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "regionOne" + } + ], + "related-to-property": [ + { + "property-key": "cloud-region.owner-defined-type", + "property-value": "LCP" + } + ] + } + ] + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json new file mode 100644 index 0000000000..328b82ed55 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json @@ -0,0 +1,56 @@ +{ + "volume-group-id": "5e6bca5b-8e14-4bdd-a419-820f68019b19", + "volume-group-name": "VolumeGroup", + "heat-stack-id": "VolumeGroup/stackId", + "vnf-type": "Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0", + "orchestration-status": "Active", + "model-customization-id": "e38906fa-717c-49b0-b391-e6ec12b50c4a", + "vf-module-model-customization-id": "e38906fa-717c-49b0-b391-e6ec12b50c4a", + "resource-version": "1560526466219", + "relationship-list": { + "relationship": [ + { + "related-to": "tenant", + "relationship-label": "org.onap.relationships.inventory.DependsOn", + "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/tenants/tenant/0422ffb57ba042c0800a29dc85ca70f8", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "cloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "regionOne" + }, + { + "relationship-key": "tenant.tenant-id", + "relationship-value": "0422ffb57ba042c0800a29dc85ca70f8" + } + ], + "related-to-property": [ + { + "property-key": "tenant.tenant-name", + "property-value": "tenantName" + } + ] + }, + { + "related-to": "generic-vnf", + "relationship-label": "org.onap.relationships.inventory.DependsOn", + "related-link": "/aai/v15/network/generic-vnfs/generic-vnf/82035634-1878-4fd9-ab14-04b819bea24b", + "relationship-data": [ + { + "relationship-key": "generic-vnf.vnf-id", + "relationship-value": "82035634-1878-4fd9-ab14-04b819bea24b" + } + ], + "related-to-property": [ + { + "property-key": "generic-vnf.vnf-name", + "property-value": "Robot_VNF_For_Volume_Group" + } + ] + } + ] + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index c2eb21b18e..948283453b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -806,6 +806,9 @@ CREATE TABLE `service` ( `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, `RESOURCE_ORDER` varchar(200) default NULL, + `OVERALL_DISTRIBUTION_STATUS` varchar(45), + `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, + `NAMING_POLICY` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java index 8657892c34..8566afe9e1 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java @@ -20,12 +20,16 @@ package org.onap.so.db.request.data.repository; +import java.util.List; import org.onap.so.db.request.beans.ArchivedInfraRequests; +import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.stereotype.Repository; @RepositoryRestResource(collectionResourceRel = "archivedInfraRequests", path = "archivedInfraRequests") public interface ArchivedInfraRequestsRepository extends JpaRepository<ArchivedInfraRequests, String> { + List<InfraActiveRequests> findByActionAndRequestStatusAndVfModuleId(String action, String requestStatus, + String vfModuleId); + } diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java index 29be0ddc00..a14699827d 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java @@ -37,6 +37,9 @@ public interface InfraActiveRequestsRepository InfraActiveRequests findOneByRequestIdOrClientRequestIdAndRequestType(String requestId, String clientRequestId, String requestType); + List<InfraActiveRequests> findByActionAndRequestStatusAndVfModuleId(String action, String requestStatus, + String vfModuleId); + InfraActiveRequests findOneByRequestId(String string); InfraActiveRequests findOneByRequestBody(String requestBody); diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java index 3c4b1fa66b..d8c7c8f971 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java @@ -92,7 +92,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep protected static final String OPENV = "operationalEnvironment"; private static final List<String> VALID_COLUMNS = - Arrays.asList(REQUEST_ID, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, ACTION, REQUEST_STATUS); + Arrays.asList(REQUEST_ID, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, ACTION, REQUEST_STATUS, + VFMODULE_INSTANCE_ID, VNF_INSTANCE_ID, NETWORK_INSTANCE_ID, VOLUME_GROUP_INSTANCE_ID); /* diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java index b1abda3b6f..1abc21dfc8 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java @@ -31,5 +31,8 @@ public interface RequestProcessingDataRepository extends JpaRepository<RequestPr RequestProcessingData findOneBySoRequestIdAndGroupingIdAndNameAndTag(@Param("SO_REQUEST_ID") String soRequestId, @Param("GROUPING_ID") String groupingId, @Param("NAME") String name, @Param("TAG") String tag); + RequestProcessingData findOneBySoRequestIdAndGroupingIdAndName(@Param("SO_REQUEST_ID") String soRequestId, + @Param("GROUPING_ID") String groupingId, @Param("NAME") String name); + List<RequestProcessingData> findBySoRequestIdOrderByGroupingIdDesc(@Param("SO_REQUEST_ID") String soRequestId); } diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql index 65372b7b48..a47e1c44af 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql @@ -96,7 +96,9 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( OPERATIONAL_ENV_NAME VARCHAR SELECTIVITY 1, INSTANCE_GROUP_ID VARCHAR SELECTIVITY 1, INSTANCE_GROUP_NAME VARCHAR SELECTIVITY 1, - REQUEST_URL VARCHAR SELECTIVITY 1 + REQUEST_URL VARCHAR SELECTIVITY 1, + ORIGINAL_REQUEST_ID VARCHAR SELECTIVITY 1, + EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1 ); INSERT INTO PUBLIC.INFRA_ACTIVE_REQUESTS(REQUEST_ID, CLIENT_REQUEST_ID, ACTION, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, AIC_NODE_CLLI, TENANT_ID, PROV_STATUS, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, REQUEST_TYPE, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, AAI_SERVICE_ID, AIC_CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 37fbfd023c..9da6ff21ac 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -87,6 +87,8 @@ public class InfraActiveRequests extends InfraRequests { .append("networkName", getNetworkName()).append("networkType", getNetworkType()) .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId()) .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId()) - .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()).toString(); + .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()) + .append("originalRequestId", getOriginalRequestId()) + .append("extSystemErrorSource", getExtSystemErrorSource()).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java index 7c58c6171e..ecc4f46149 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java @@ -22,6 +22,7 @@ package org.onap.so.db.request.beans; import java.net.URI; import java.sql.Timestamp; +import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; @@ -152,10 +153,14 @@ public abstract class InfraRequests implements java.io.Serializable { private String instanceGroupName; @Column(name = "REQUEST_URL", length = 500) private String requestUrl; + @Column(name = "ORIGINAL_REQUEST_ID", length = 45) + private String originalRequestId; + @Column(name = "EXT_SYSTEM_ERROR_SOURCE", length = 80) + private String extSystemErrorSource; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID") - private List<CloudApiRequests> cloudApiRequests; + private List<CloudApiRequests> cloudApiRequests = new ArrayList<>(); @ResourceId public URI getRequestURI() { @@ -569,6 +574,22 @@ public abstract class InfraRequests implements java.io.Serializable { this.requestUrl = requestUrl; } + public String getOriginalRequestId() { + return this.originalRequestId; + } + + public void setOriginalRequestId(String originalRequestId) { + this.originalRequestId = originalRequestId; + } + + public String getExtSystemErrorSource() { + return this.extSystemErrorSource; + } + + public void setExtSystemErrorSource(String extSystemErrorSource) { + this.extSystemErrorSource = extSystemErrorSource; + } + @PrePersist protected void onCreate() { if (requestScope == null) @@ -630,6 +651,8 @@ public abstract class InfraRequests implements java.io.Serializable { .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId()) .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId()) .append("operationalEnvName", getOperationalEnvName()).append("instanceGroupId", getInstanceGroupId()) - .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()).toString(); + .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()) + .append("originalRequestId", originalRequestId).append("extSystemErrorSource", extSystemErrorSource) + .toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java index 2a75c24c46..3c81555b99 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java @@ -86,6 +86,9 @@ public class RequestProcessingData implements Serializable { @Temporal(TemporalType.TIMESTAMP) private Date created = null; + @Column(name = "IS_DATA_INTERNAL") + private Boolean isDataInternal = true; + @Override public boolean equals(final Object other) { if (!(other instanceof RequestProcessingData)) { @@ -105,7 +108,7 @@ public class RequestProcessingData implements Serializable { public String toString() { return new ToStringBuilder(this).append("id", id).append("soRequestId", soRequestId) .append("groupingId", groupingId).append("name", name).append("value", value).append("tag", tag) - .toString(); + .append("isDataInternal", isDataInternal).toString(); } @PrePersist @@ -164,4 +167,12 @@ public class RequestProcessingData implements Serializable { public Date getCreated() { return created; } + + public Boolean getIsDataInternal() { + return isDataInternal; + } + + public void setIsDataInternal(Boolean isDataInternal) { + this.isDataInternal = isDataInternal; + } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java index 103410701c..9ab0f3b680 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java @@ -67,11 +67,12 @@ public class RequestsDbClient { private static final String SERVICE_ID = "SERVICE_ID"; private static final String OPERATION_ID = "OPERATION_ID"; private static final String SO_REQUEST_ID = "SO_REQUEST_ID"; + private static final String NAME = "NAME"; + private static final String GROUPING_ID = "GROUPING_ID"; private static final String REQUEST_ID = "REQUEST_ID"; private static final String OPERATIONAL_ENVIRONMENT_ID = "OPERATIONAL_ENV_ID"; private static final String SERVICE_MODEL_VERSION_ID = "SERVICE_MODEL_VERSION_ID"; - @Value("${mso.adapters.requestDb.endpoint:#{null}}") protected String endpoint; @@ -104,7 +105,12 @@ public class RequestsDbClient { private String requestProcessingDataURI = "/requestProcessingData"; - private final String findBySoRequestIdOrderByGroupingIdDesc = + private String getInfraActiveRequests = "/infraActiveRequests/v1/getInfraActiveRequests"; + + private static final String findBySoRequestIdAndGroupIdAndName = + "/requestProcessingData/search/findOneBySoRequestIdAndGroupingIdAndName"; + + private static final String findBySoRequestIdOrderByGroupingIdDesc = "/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc"; @@ -123,6 +129,7 @@ public class RequestsDbClient { cloudOrchestrationFiltersFromInfraActive = endpoint + cloudOrchestrationFiltersFromInfraActive; findOneByServiceIdAndOperationIdURI = endpoint + OPERATION_STATUS_SEARCH + findOneByServiceIdAndOperationIdURI; requestProcessingDataURI = endpoint + requestProcessingDataURI; + getInfraActiveRequests = endpoint + getInfraActiveRequests; operationalEnvDistributionStatusURI = endpoint + operationalEnvDistributionStatusURI; findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI = endpoint + OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH @@ -333,12 +340,27 @@ public class RequestsDbClient { restTemplate.postForLocation(uri, entity); } + public void updateRequestProcessingData(RequestProcessingData requestProcessingData) { + HttpHeaders headers = getHttpHeaders(); + URI uri = getUri(requestProcessingDataURI); + HttpEntity<RequestProcessingData> entity = new HttpEntity<>(requestProcessingData, headers); + restTemplate.put(uri, entity); + } + public List<RequestProcessingData> getRequestProcessingDataBySoRequestId(String soRequestId) { return this .getRequestProcessingData(getUri(UriBuilder.fromUri(endpoint + findBySoRequestIdOrderByGroupingIdDesc) .queryParam(SO_REQUEST_ID, soRequestId).build().toString())); } + public RequestProcessingData getRequestProcessingDataBySoRequestIdAndNameAndGrouping(String soRequestId, + String name, String groupingId) { + return getClientFactory().create(RequestProcessingData.class) + .get(getUri(UriBuilder.fromUri(endpoint + findBySoRequestIdAndGroupIdAndName) + .queryParam(SO_REQUEST_ID, soRequestId).queryParam(NAME, name) + .queryParam(GROUPING_ID, groupingId).build().toString())); + } + private List<RequestProcessingData> getRequestProcessingData(URI uri) { Iterable<RequestProcessingData> requestProcessingDataIterator = getClientFactory().create(RequestProcessingData.class).getAll(uri); @@ -348,6 +370,17 @@ public class RequestsDbClient { return requestProcessingDataList; } + // From and To are defaulted to ignore start/endtime on query to database + public List<InfraActiveRequests> getRequest(final Map<String, String[]> filters) { + String url = UriBuilder.fromUri(getUri(getInfraActiveRequests)).queryParam("from", "0") + .queryParam("to", "10000000000000").build().toString(); + HttpHeaders headers = getHttpHeaders(); + HttpEntity<Map> entity = new HttpEntity<>(filters, headers); + return restTemplate + .exchange(url, HttpMethod.POST, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {}) + .getBody(); + } + @Component static class ClassURLMapper { private static final Map<Class, String> classURLMap = new HashMap<>(); |