diff options
Diffstat (limited to 'mso-api-handlers')
54 files changed, 2476 insertions, 502 deletions
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java index 8977f11e36..7fb5df7af6 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java @@ -40,6 +40,8 @@ public class CamundaResponse { @JsonProperty("variables") private String variables; + public CamundaResponse() {} + public String getProcessInstanceID() { return processInstanceID; } @@ -56,8 +58,6 @@ public class CamundaResponse { this.variables = variables; } - public CamundaResponse() {} - public String getResponse() { return response; } 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 d11f1706e9..eb4ba76530 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 @@ -27,9 +27,9 @@ package org.onap.so.apihandler.common; import java.io.IOException; import java.util.UUID; import javax.xml.bind.DatatypeConverter; +import com.google.common.base.Strings; 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; @@ -49,6 +49,9 @@ import com.fasterxml.jackson.databind.SerializationFeature; public class CamundaClient extends RequestClient { private static Logger logger = LoggerFactory.getLogger(CamundaClient.class); private static final String CAMUNDA_URL_MESAGE = "Camunda url is: "; + private static final String CAMUNDA_RESPONSE = "Response is: {}"; + private static final String AUTHORIZATION = "Authorization"; + private static final String BASIC = "Basic "; public CamundaClient() { super(CommonConstants.CAMUNDA); @@ -57,7 +60,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); @@ -71,7 +74,7 @@ public class CamundaClient extends RequestClient { setupHeaders(post); HttpResponse response = client.execute(post); - logger.debug("Response is: {}", response); + logger.debug(CAMUNDA_RESPONSE, response); return response; } @@ -80,52 +83,26 @@ 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("Response is: {}", response); + logger.debug(CAMUNDA_RESPONSE, response); 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(), @@ -140,26 +117,11 @@ 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("Response is: {}", response); + logger.debug(CAMUNDA_RESPONSE, response); return response; } @@ -200,7 +162,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", + logger.error(Strings.repeat("{} ", 5), MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapRequest", ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); } return jsonReq; @@ -239,7 +201,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); @@ -292,8 +253,8 @@ 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(Strings.repeat("{} ", 5), MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", + "wrapVIDRequest", ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); } return jsonReq; } @@ -309,4 +270,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/ErrorNumbers.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java index 468fe61562..7400c0aaae 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java @@ -22,8 +22,6 @@ package org.onap.so.apihandler.common; public final class ErrorNumbers { - private ErrorNumbers() {} - public static final String REQUEST_FAILED_SCHEMA_VALIDATION = "1000"; public static final String RECIPE_DOES_NOT_EXIST = "1010"; public static final String VFMODULE_TYPE_DOES_NOT_EXIST = "1011"; @@ -73,4 +71,6 @@ public final class ErrorNumbers { public static final String SVC_NO_SERVER_RESOURCES = "SVC1000"; public static final String SVC_DETAILED_SERVICE_ERROR = "SVC2000"; + private ErrorNumbers() {} + } 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 0aac35d5a9..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,33 +69,18 @@ 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 { - String result = CryptoUtils.decrypt(prop, encryptionKey); - return result; - } catch (GeneralSecurityException e) { - logger.debug("Security exception", e); - } - return defaultValue; - } - protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) { try { - String result = CryptoUtils.decrypt(prop, encryptionKey); - return result; + return CryptoUtils.decrypt(prop, encryptionKey); } catch (GeneralSecurityException e) { logger.debug("Security exception", e); } return defaultValue; } - - - } 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/ResponseHandler.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java index fff4c1d508..095182fe98 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java @@ -80,12 +80,8 @@ public class ResponseHandler { new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - ValidateException validateException = - new ValidateException.Builder("IOException getting Camunda response body", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw new ValidateException.Builder("IOException getting Camunda response body", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); } ObjectMapper mapper = new ObjectMapper(); @@ -96,11 +92,8 @@ public class ResponseHandler { new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - ValidateException validateException = - new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - throw validateException; + throw new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); } if (response != null) { responseBody = response.getResponse(); @@ -125,22 +118,16 @@ public class ResponseHandler { } catch (IOException e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException validateException = - new ValidateException.Builder("Could not convert BPEL response to string", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; + + throw new ValidateException.Builder("Could not convert BPEL response to string", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); } if (status != HttpStatus.SC_ACCEPTED) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError).targetEntity("BPEL").targetServiceName("parseBpel").build(); - - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) + .errorInfo(errorLoggerInfo).build(); } } @@ -157,24 +144,17 @@ public class ResponseHandler { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - - ValidateException validateException = - new ValidateException.Builder("Could not convert CamundaTask response to string", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw new ValidateException.Builder("Could not convert CamundaTask response to string", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) + .build(); } if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_ACCEPTED) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError).targetEntity("CAMUNDATASK").targetServiceName("parseCamundaTask") .build(); - - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) + .errorInfo(errorLoggerInfo).build(); } } 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..b9a06ac1d9 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 @@ -31,6 +31,7 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; +import com.google.common.base.Strings; import org.apache.commons.io.IOUtils; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -94,8 +95,8 @@ 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(Strings.repeat("{} ", 3), MessageEnum.APIH_CANNOT_READ_SCHEMA.toString(), + ErrorCode.SchemaError.getValue(), "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/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/Constants.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java index 0bbc3e336f..ec583645ae 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java @@ -23,8 +23,6 @@ package org.onap.so.apihandlerinfra; public class Constants { - private Constants() {} - public static final String REQUEST_ID_PATH = "/{request-id}"; public static final String STATUS_SUCCESS = "SUCCESS"; @@ -43,11 +41,13 @@ public class Constants { public static final String A_LA_CARTE = "aLaCarte"; - public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; + public static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; - public final static String VNF_REQUEST_SCOPE = "vnf"; - public final static String SERVICE_INSTANCE_PATH = "/serviceInstances"; - public final static String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation"; - public final static String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests"; + public static final String VNF_REQUEST_SCOPE = "vnf"; + public static final String SERVICE_INSTANCE_PATH = "/serviceInstances"; + public static final String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation"; + public static final String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests"; + + private Constants() {} } 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..12379f9c1a 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 @@ -36,6 +36,7 @@ import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; +import com.google.common.base.Strings; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -134,8 +135,8 @@ 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(Strings.repeat("{} ", 4), MessageEnum.GENERAL_EXCEPTION.toString(), + "BuildServiceErrorResponse", ErrorCode.DataError.getValue(), errorMsg, e); return errorMsg; } 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-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/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index 449aa4ba3f..7ed1f9d5d0 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 com.google.common.base.Strings; 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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(Strings.repeat("{} ", 4), 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; @@ -928,21 +933,14 @@ public class E2EServiceInstances { // subscriptionServiceType requestParameters.setSubscriptionServiceType("MOG"); - // Userparams - // List<E2EUserParam> userParams; - // userParams = - // e2eSir.getService().getParameters().getRequestParameters().getUserParams(); + List<Map<String, Object>> userParamList = new ArrayList<>(); Map<String, Object> userParamMap = new HashMap<>(); // complete json request updated in the camunda userParamMap.put("UUIRequest", requestJSON); userParamMap.put("ServiceInstanceName", e2eSir.getService().getName()); - // Map<String, String> userParamMap3 = null; - // for (E2EUserParam userp : userParams) { - // userParamMap.put(userp.getName(), userp.getValue()); - // - // } + userParamList.add(userParamMap); requestParameters.setUserParams(userParamList); 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..e3b297b5db 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 com.google.common.base.Strings; 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(Strings.repeat("{} ", 2), 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 dd6050bf60..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 @@ -115,8 +115,7 @@ public class InstanceManagement { String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -149,16 +148,15 @@ public class InstanceManagement { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, - currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); 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 67d6a0d1fc..7c0d327db7 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 @@ -24,8 +24,8 @@ import javax.annotation.PostConstruct; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletProperties; -import org.onap.so.apihandler.filters.RequestUriFilter; 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.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; @@ -41,8 +41,6 @@ import io.swagger.jaxrs.listing.SwaggerSerializers; @ApplicationPath("/") public class JerseyConfiguration extends ResourceConfig { - - @PostConstruct public void setUp() { register(GlobalHealthcheckHandler.class); @@ -64,6 +62,7 @@ public class JerseyConfiguration extends ResourceConfig { register(E2EServiceInstances.class); register(WorkflowSpecificationsHandler.class); register(InstanceManagement.class); + register(ResumeOrchestrationRequest.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..169ec50a74 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 com.google.common.base.Strings; 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(Strings.repeat("{} ", 2), 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 277675f310..49572630ed 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 @@ -42,6 +42,7 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import com.google.common.base.Strings; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; import org.onap.so.apihandlerinfra.validation.MembersValidation; @@ -151,7 +152,8 @@ 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(), + logger.error(Strings.repeat("{} ", 3), MessageEnum.APIH_VALIDATION_ERROR.toString(), + ErrorCode.DataError.getValue(), "Exception in buildServiceErrorResponse writing exceptionType to string ", e); } @@ -396,8 +398,8 @@ 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(Strings.repeat("{} ", 3), MessageEnum.APIH_DB_INSERT_EXC.toString(), + ErrorCode.DataError.getValue(), "Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -437,8 +439,8 @@ 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(Strings.repeat("{} ", 3), MessageEnum.APIH_DB_INSERT_EXC.toString(), + ErrorCode.DataError.getValue(), "Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -465,7 +467,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(), + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), ErrorCode.DataError.getValue(), "Exception when updating record in DB"); logger.debug("Exception: ", e); } @@ -547,8 +549,8 @@ public class MsoRequest { return null; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in domToStr", e); + logger.error(Strings.repeat("{} ", 3), MessageEnum.APIH_DOM2STR_ERROR.toString(), + ErrorCode.DataError.getValue(), "Exception in domToStr", e); } return null; } @@ -574,7 +576,7 @@ public class MsoRequest { throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - // mapper.configure(Feature.WRAP_ROOT_VALUE, true); + logger.debug("building sir from object {}", sir); String requestJSON = mapper.writeValueAsString(sir); @@ -636,7 +638,7 @@ public class MsoRequest { public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { String serviceInstanceType = null; - String networkType = null; + String vnfType = null; String vfModuleType = null; String vfModuleModelName = null; @@ -800,6 +802,7 @@ public class MsoRequest { 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..07a0161e8f 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 com.google.common.base.Strings; 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(Strings.repeat("{} ", 2), 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 34dcd4b0c4..e14b01792a 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 @@ -35,6 +35,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -53,6 +54,7 @@ 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.serviceinstancebeans.CloudRequestData; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.InstanceReferences; @@ -61,6 +63,7 @@ import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestList; import org.onap.so.serviceinstancebeans.RequestStatus; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -76,7 +79,6 @@ public class OrchestrationRequests { private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class); - @Autowired private RequestsDbClient requestsDbClient; @@ -92,14 +94,23 @@ public class OrchestrationRequests { @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@PathParam("requestId") String requestId, - @PathParam("version") String version) throws ApiException { + @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest) + throws ApiException { String apiVersion = version.substring(1); GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); - InfraActiveRequests infraActiveRequest = null; List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null; + + if (!UUIDChecker.isValidUUID(requestId)) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MODIFIED_BY_APIHANDLER).build(); + throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + } try { infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId); @@ -109,14 +120,11 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); - - ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup", HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) .errorInfo(errorLoggerInfo).build(); - throw validateException; } @@ -126,7 +134,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) @@ -135,7 +142,7 @@ public class OrchestrationRequests { throw validateException; } - Request request = mapInfraActiveRequestToRequest(infraActiveRequest); + Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest); if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -150,8 +157,8 @@ public class OrchestrationRequests { @ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class) @Produces(MediaType.APPLICATION_JSON) @Transactional - public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) - throws ApiException { + public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version, + @QueryParam("includeCloudRequest") boolean includeCloudRequest) throws ApiException { long startTime = System.currentTimeMillis(); @@ -188,7 +195,7 @@ public class OrchestrationRequests { List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); RequestList requestList = new RequestList(); - Request request = mapInfraActiveRequestToRequest(infraActive); + Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest); if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -200,7 +207,6 @@ public class OrchestrationRequests { return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); } - @POST @Path("/{version: [vV][4-7]}/{requestId}/unlock") @Consumes(MediaType.APPLICATION_JSON) @@ -251,7 +257,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) @@ -273,7 +278,6 @@ public class OrchestrationRequests { new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) .build(); - ValidateException validateException = new ValidateException.Builder( "Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked", @@ -286,8 +290,8 @@ public class OrchestrationRequests { return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); } - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException { - + protected Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest) + throws ApiException { String requestBody = iar.getRequestBody(); Request request = new Request(); @@ -300,6 +304,10 @@ 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) @@ -329,8 +337,6 @@ public class OrchestrationRequests { if (iar.getInstanceGroupName() != null) ir.setInstanceGroupName(iar.getInstanceGroupName()); - - request.setInstanceReferences(ir); RequestDetails requestDetails = null; @@ -401,7 +407,6 @@ public class OrchestrationRequests { status.setTimeStamp(timeStamp); } - if (iar.getRequestStatus() != null) { status.setRequestState(iar.getRequestStatus()); } @@ -410,8 +415,19 @@ public class OrchestrationRequests { status.setPercentProgress(iar.getProgress().intValue()); } - request.setRequestStatus(status); + if (iar.getCloudApiRequests() != null && !iar.getCloudApiRequests().isEmpty() && includeCloudRequest) { + iar.getCloudApiRequests().stream().forEach(cloudRequest -> { + try { + request.getCloudRequestData() + .add(new CloudRequestData(mapper.readValue(cloudRequest.getRequestBody(), Object.class), + cloudRequest.getCloudIdentifier())); + } catch (Exception e) { + logger.error("Error reading Cloud Request", e); + } + }); + } + request.setRequestStatus(status); return request; } 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 bbcc120ab6..4e910e5382 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 @@ -24,8 +24,20 @@ package org.onap.so.apihandlerinfra; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -47,7 +59,9 @@ 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.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; @@ -55,6 +69,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; @@ -76,20 +91,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import java.io.IOException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; @Component public class RequestHandlerUtils { @@ -293,9 +296,8 @@ public class RequestHandlerUtils { return requestUri; } - public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, - MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) - throws ApiException { + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, + String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance @@ -369,8 +371,7 @@ public class RequestHandlerUtils { } public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, - long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) - throws ApiException { + String requestId, String requestUri) throws ApiException { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(requestJSON, ServiceInstancesRequest.class); @@ -415,8 +416,8 @@ public class RequestHandlerUtils { } public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, - HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName, - String requestScope, InfraActiveRequests dup) throws ApiException { + HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup) + throws ApiException { String instance = null; if (instanceName != null) { @@ -622,4 +623,88 @@ public class RequestHandlerUtils { return requestScope; } + protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest, + String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId, + String originalRequestId) { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId(requestId); + request.setStartTime(startTimeStamp); + request.setSource(source); + request.setRequestUrl(requestUri); + 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.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); + request.setRequestScope(infraActiveRequest.getRequestScope()); + request.setRequestAction(infraActiveRequest.getRequestAction()); + setInstanceIdAndName(infraActiveRequest, request); + } + return request; + } + + protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest, + InfraActiveRequests currentActiveRequest) { + String requestScope = infraActiveRequest.getRequestScope(); + try { + ModelType type = ModelType.valueOf(requestScope); + type.setName(currentActiveRequest, type.getName(infraActiveRequest)); + 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(); + } + } + } 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 new file mode 100644 index 0000000000..32d2c50978 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -0,0 +1,276 @@ +/*- + * ============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 java.io.IOException; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +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.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClientParameter; +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.logging.ErrorLoggerInfo; +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.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; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("onap/so/infra/orchestrationRequests") +@Api(value = "onap/so/infra/orchestrationRequests") +@Component +public class ResumeOrchestrationRequest { + private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class); + private static final String SAVE_TO_DB = "save instance to db"; + private static String uriPrefix = "/orchestrationRequests/"; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @Autowired + private ServiceInstances serviceInstances; + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private MsoRequest msoRequest; + + @POST + @Path("/{version:[vV][7]}/requests/{requestId}/resume") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Resume request for a given requestId", response = Response.class) + @Transactional + public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId, + @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { + + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + String currentRequestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + logger.info("Beginning resume operation for new request: {}", currentRequestId); + InfraActiveRequests infraActiveRequest = null; + String source = MDC.get(MdcConstants.ORIGINAL_PARTNER_NAME); + String requestorId = MDC.get(HttpHeadersConstants.REQUESTOR_ID); + requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + String requestUri = MDC.get(LogConstants.HTTP_URL); + version = version.substring(1); + + try { + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (HttpClientErrorException e) { + logger.error("Error occurred while performing requestDb lookup by requestId: " + requestId, e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + throw new ValidateException.Builder("Exception while performing requestDb lookup by requestId", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + + InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest( + infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId, requestId); + + if (infraActiveRequest == null) { + logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, + ErrorCode.BusinessProcesssError).build(); + ValidateException validateException = new ValidateException.Builder( + "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + + } + + return resumeRequest(infraActiveRequest, currentActiveRequest, version, requestUri); + } + + protected Response resumeRequest(InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, + String version, String requestUri) throws ApiException { + String requestBody = infraActiveRequest.getRequestBody(); + Action action = Action.valueOf(infraActiveRequest.getRequestAction()); + String requestId = currentActiveRequest.getRequestId(); + String requestScope = infraActiveRequest.getRequestScope(); + String instanceName = getInstanceName(infraActiveRequest, requestScope, currentActiveRequest); + HashMap<String, String> instanceIdMap = setInstanceIdMap(infraActiveRequest, requestScope); + + checkForInProgressRequest(currentActiveRequest, instanceIdMap, requestScope, instanceName, action); + + ServiceInstancesRequest sir = null; + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri); + Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); + + String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir); + 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); + + return requestHandlerUtils.postBPELRequest(currentActiveRequest, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + + protected Boolean setALaCarteFlagIfNull(String requestScope, Action action) { + Boolean aLaCarteFlag; + if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) { + aLaCarteFlag = true; + } else { + aLaCarteFlag = false; + } + 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 String getInstanceName(InfraActiveRequests infraActiveRequest, String requestScope, + InfraActiveRequests currentActiveRequest) throws ValidateException, RequestDbFailureException { + ModelType type; + String instanceName = ""; + try { + 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 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 { + try { + requestsDbClient.save(currentActiveRequest); + } catch (Exception e) { + logger.error("Exception while saving request to requestDb", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + } + + protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version, + InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId, + 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()) + .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 = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder( + "IOException while generating requestClientParameter to send to BPMN: " + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestClientParameter; + } +} 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 931a1eb52b..68fa6e4f56 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; @@ -74,24 +86,12 @@ 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 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") @@ -765,8 +765,8 @@ public class ServiceInstances { ServiceInstancesRequest sir = null; String apiVersion = version.substring(1); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + 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); @@ -797,16 +797,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -815,64 +814,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)) { - - - // 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; - } + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + ModelType modelType = requestHandlerUtils.getModelType(action, modelInfo); - 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 = ""; @@ -941,6 +896,20 @@ 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); @@ -968,8 +937,8 @@ public class ServiceInstances { throw validateException; } - InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, - requestScope, currentActiveReq); + InfraActiveRequests dup = + requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); boolean inProgress = false; if (dup != null) { @@ -977,8 +946,8 @@ public class ServiceInstances { } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -1011,13 +980,13 @@ public class ServiceInstances { recipeLookupResult.getOrchestrationURI(), requestScope); } - private String getPnfCorrelationId(ServiceInstancesRequest sir) { + protected String getPnfCorrelationId(ServiceInstancesRequest sir) { return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails) .map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId")) .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 @@ -1103,8 +1072,8 @@ public class ServiceInstances { return recipeLookupResult; } - private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag) - throws IOException { + protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, + boolean alaCarteFlag) throws IOException { // SERVICE REQUEST // Construct the default service name // TODO need to make this a configurable property @@ -1598,8 +1567,7 @@ public class ServiceInstances { long startTime = System.currentTimeMillis(); ServiceInstancesRequest sir = null; - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -1613,16 +1581,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (instanceIdMap != null && dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java index 77abbbfa9a..6e77ce84a6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java @@ -21,7 +21,7 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; -import java.sql.Timestamp; + import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java index f7fa01aeb0..4fc6181bf8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java @@ -29,13 +29,7 @@ public class GetE2EServiceInstanceResponse { protected OperationStatus operation; - // public OperationStatus getOperationStatus() { - // return operation; - // } - // - // public void setOperationStatus(OperationStatus requestDB) { - // this.operation = requestDB; - // } + public OperationStatus getOperation() { return operation; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java index 44592ce2e4..ae462ebffa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java @@ -39,6 +39,9 @@ public class ResourceRequest { @JsonProperty("resourceCustomizationUuid") private String resourceCustomizationUuid; + @JsonProperty("resourceIndex") + private String resourceIndex; + @JsonProperty("parameters") private E2EParameters parameters; @@ -98,4 +101,12 @@ public class ResourceRequest { public void setParameters(E2EParameters parameters) { this.parameters = parameters; } + + public String getResourceIndex() { + return resourceIndex; + } + + public void setResourceIndex(String resourceIndex) { + this.resourceIndex = resourceIndex; + } } 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..6f24bd4c4d 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 com.google.common.base.Strings; 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(Strings.repeat("{} ", 2), 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/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java index 696616099f..98c3f1f37f 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 @@ -28,6 +28,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.core.MultivaluedMap; +import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.onap.so.apihandlerinfra.Constants; import org.onap.so.apihandlerinfra.Status; @@ -356,7 +357,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(), + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), ErrorCode.DataError.getValue(), "Exception when updating record in DB"); 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 8b3b91ae1a..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,15 +34,13 @@ 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; @Component public class AAIClientHelper { - private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class); + /** * Get managing ECOMP Environment Info from A&AI @@ -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/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java index 98b49d39d7..1e5958c540 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java @@ -31,7 +31,7 @@ import org.springframework.stereotype.Component; @Component public class ActivateVnfDBHelper { - private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class); + /** * Insert record to OperationalEnvServiceModelStatus table diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java index 4c66a3118e..c50f18c594 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java @@ -34,7 +34,7 @@ public class Manifest implements Serializable { private static final long serialVersionUID = -3460949513229380541L; @JsonProperty("serviceModelList") - private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>(); + private List<ServiceModelList> serviceModelList = new ArrayList<>(); public List<ServiceModelList> getServiceModelList() { return serviceModelList; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java index 907bc942eb..2cf01f9390 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java @@ -29,51 +29,59 @@ import org.onap.so.utils.UUIDChecker; public class InstanceIdMapValidation implements ValidationRule { + private static final String Service_InstanceId = "serviceInstanceId"; + private static final String Vnf_InstanceId = "vnfInstanceId"; + private static final String vfModule_InstanceId = "vfModuleInstanceId"; + + private static final String volume_Group_InstanceId = "volumeGroupInstanceId"; + private static final String Network_Instance_Id = "networkInstanceId"; + private static final String Configuration_Instance_Id = "configurationInstanceId"; + @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException { HashMap<String, String> instanceIdMap = info.getInstanceIdMap(); ServiceInstancesRequest sir = info.getSir(); if (instanceIdMap != null) { - if (instanceIdMap.get("serviceInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("serviceInstanceId"))) { - throw new ValidationException("serviceInstanceId"); + if (instanceIdMap.get(Service_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Service_InstanceId))) { + throw new ValidationException(Service_InstanceId); } - sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); + sir.setServiceInstanceId(instanceIdMap.get(Service_InstanceId)); } - if (instanceIdMap.get("vnfInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("vnfInstanceId"))) { - throw new ValidationException("vnfInstanceId"); + if (instanceIdMap.get(Vnf_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Vnf_InstanceId))) { + throw new ValidationException(Vnf_InstanceId); } - sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId")); + sir.setVnfInstanceId(instanceIdMap.get(Vnf_InstanceId)); } - if (instanceIdMap.get("vfModuleInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("vfModuleInstanceId"))) { - throw new ValidationException("vfModuleInstanceId"); + if (instanceIdMap.get(vfModule_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(vfModule_InstanceId))) { + throw new ValidationException(vfModule_InstanceId); } - sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId")); + sir.setVfModuleInstanceId(instanceIdMap.get(vfModule_InstanceId)); } - if (instanceIdMap.get("volumeGroupInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("volumeGroupInstanceId"))) { - throw new ValidationException("volumeGroupInstanceId"); + if (instanceIdMap.get(volume_Group_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(volume_Group_InstanceId))) { + throw new ValidationException(volume_Group_InstanceId); } - sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId")); + sir.setVolumeGroupInstanceId(instanceIdMap.get(volume_Group_InstanceId)); } - if (instanceIdMap.get("networkInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("networkInstanceId"))) { - throw new ValidationException("networkInstanceId"); + if (instanceIdMap.get(Network_Instance_Id) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Network_Instance_Id))) { + throw new ValidationException(Network_Instance_Id); } - sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId")); + sir.setNetworkInstanceId(instanceIdMap.get(Network_Instance_Id)); } - if (instanceIdMap.get("configurationInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("configurationInstanceId"))) { - throw new ValidationException("configurationInstanceId"); + if (instanceIdMap.get(Configuration_Instance_Id) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Configuration_Instance_Id))) { + throw new ValidationException(Configuration_Instance_Id); } - sir.setConfigurationId(instanceIdMap.get("configurationInstanceId")); + sir.setConfigurationId(instanceIdMap.get(Configuration_Instance_Id)); } if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java index 2236b09f2a..7a0a6fe633 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java @@ -49,8 +49,7 @@ import javax.xml.namespace.QName; public class ObjectFactory { private final static QName _VnfParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "vnf-params"); - private final static QName _NetworkParams_QNAME = - new QName("http://org.onap/so/infra/vnf-request/v1", "network-params"); + /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index 321ea3ac7d..f82f5ac746 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -42,12 +42,12 @@ import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; -import org.junit.Ignore; import org.junit.Test; import org.onap.so.apihandler.common.ErrorNumbers; 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.serviceinstancebeans.CloudRequestData; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.Request; @@ -119,7 +119,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } @@ -149,12 +149,22 @@ public class OrchestrationRequestsTest extends BaseTest { } @Test - public void testGetOrchestrationRequestRequestDetails() throws Exception { - setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); + public void testGetOrchestrationRequestWithOpenstackDetails() throws Exception { + setupTestGetOrchestrationRequestOpenstackDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); // Test request with modelInfo request body GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest(); + List<CloudRequestData> cloudRequestData = new ArrayList<>(); + CloudRequestData cloudData = new CloudRequestData(); + cloudData.setCloudIdentifier("heatstackName/123123"); + ObjectMapper mapper = new ObjectMapper(); + Object reqData = mapper.readValue( + "{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}", + Object.class); + cloudData.setCloudRequest(reqData); + cloudRequestData.add(cloudData); + request.setCloudRequestData(cloudRequestData); testResponse.setRequest(request); String testRequestId = request.getRequestId(); @@ -163,13 +173,14 @@ public class OrchestrationRequestsTest extends BaseTest { headers.set("Content-Type", MediaType.APPLICATION_JSON); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/onap/so/infra/orchestrationRequests/v7/" + testRequestId + "?includeCloudRequest=true")); ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - + System.out.println("Response :" + response.getBody().toString()); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -194,6 +205,29 @@ public class OrchestrationRequestsTest extends BaseTest { } @Test + public void testGetOrchestrationRequestInvalidRequestID() throws Exception { + setupTestGetOrchestrationRequest(); + // TEST INVALID REQUESTID + GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); + + Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); + testResponse.setRequest(request); + String testRequestId = "00032ab7-pfb3-42e5-965d-8ea592502016"; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); + + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test public void testGetOrchestrationRequestFilter() throws Exception { setupTestGetOrchestrationRequestFilter(); List<String> values = new ArrayList<>(); @@ -319,75 +353,11 @@ public class OrchestrationRequestsTest extends BaseTest { "/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); - // Cannot assert anything further here, already have a wiremock in place which ensures that the post was + // Cannot assert anything further here, already have a wiremock in place + // which ensures that the post was // properly called to update. } - @Ignore // What is this testing? - @Test - public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception { - InfraActiveRequests requests = new InfraActiveRequests(); - requests.setAction("create"); - requests.setRequestBody(" "); - requests.setRequestId("requestId"); - requests.setRequestScope("service"); - requests.setRequestType("createInstance"); - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(requests); - - requestsDbClient.save(requests); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - - ResponseEntity<GetOrchestrationResponse> response = - restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); - } - - @Ignore // What is this testing? - @Test - public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException { - InfraActiveRequests requests = new InfraActiveRequests(); - - String requestJSON = new String( - Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); - - requests.setAction("create"); - requests.setRequestBody(requestJSON); - requests.setRequestId("requestId"); - requests.setRequestScope("service"); - requests.setRequestType("createInstance"); - // iar.save(requests); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - - ResponseEntity<GetOrchestrationResponse> response = - restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); - } - @Test public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException { RequestProcessingData entry = new RequestProcessingData(); @@ -423,14 +393,14 @@ public class OrchestrationRequestsTest extends BaseTest { public void setupTestGetOrchestrationRequest() throws Exception { // For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes( Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) .withStatus(HttpStatus.SC_OK))); wireMockServer .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) @@ -439,14 +409,14 @@ public class OrchestrationRequestsTest extends BaseTest { public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception { // For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths.get( "src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) .withStatus(HttpStatus.SC_OK))); wireMockServer .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) @@ -461,15 +431,20 @@ public class OrchestrationRequestsTest extends BaseTest { .withStatus(HttpStatus.SC_OK))); } + private void setupTestGetOrchestrationRequestOpenstackDetails(String requestId, String status) throws Exception { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json")))) + .withStatus(HttpStatus.SC_OK))); + } + private void setupTestUnlockOrchestrationRequest(String requestId, String status) { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK))); - } - - private void setupTestUnlockOrchestrationRequest_invalid_Json() { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); 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..19b9d7ea1e --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -0,0 +1,90 @@ +/*- + * ============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.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.InstanceReferences; +import org.onap.so.serviceinstancebeans.Request; +import org.onap.so.serviceinstancebeans.RequestStatus; + +@RunWith(MockitoJUnitRunner.class) +public class OrchestrationRequestsUnitTest { + + @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 InfraActiveRequests iar; + boolean includeCloudRequest = false; + + @Before + public void setup() { + iar = new InfraActiveRequests(); + iar.setRequestScope(SERVICE); + iar.setRequestId(REQUEST_ID); + iar.setServiceInstanceId(SERVICE_INSTANCE_ID); + } + + @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); + 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); + assertThat(result, sameBeanAs(expected)); + } + +} 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 new file mode 100644 index 0000000000..e92417728c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -0,0 +1,399 @@ +/*- + * ============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.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.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; + return new String(Files.readAllBytes(Paths.get(request))); + } + + @Before + public void setup() throws IOException { + setInfraActiveRequest(); + setCurrentActiveRequest(); + setCurrentActiveRequestNullInfraActive(); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + 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"); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope("service"); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setProgress(new Long(5)); + currentActiveRequest.setOriginalRequestId(RESUMED_REQUEST_ID); + } + + private void setCurrentActiveRequestNullInfraActive() throws IOException { + currentActiveRequestIARNull.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequestIARNull.setSource("VID"); + currentActiveRequestIARNull.setStartTime(startTimeStamp); + currentActiveRequestIARNull.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequestIARNull.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequestIARNull.setRequestUrl(requestUri); + currentActiveRequestIARNull.setRequestorId("xxxxxx"); + currentActiveRequestIARNull.setProgress(new Long(5)); + currentActiveRequestIARNull.setOriginalRequestId(RESUMED_REQUEST_ID); + } + + + @Test + public void createNewRecordCopyFromInfraActiveRequestTest() { + doNothing().when(requestHandler).setInstanceIdAndName(infraActiveRequest, currentActiveRequest); + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest, + CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID); + assertThat(currentActiveRequest, sameBeanAs(result)); + } + + @Test + public void createNewRecordCopyFromInfraActiveRequestNullIARTest() { + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID, + startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID); + assertThat(currentActiveRequestIARNull, sameBeanAs(result)); + } + + @Test + public void setInstanceIdAndNameServiceTest() { + 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 setInstanceIdAndNameRequestScopeNotValidTest() { + 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() { + 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() { + 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() { + 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() { + 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() { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.applyUpdatedConfig, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeInPlaceSoftwareUpdateTest() { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.inPlaceSoftwareUpdate, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeAddMembersTest() { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.addMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeRemoveMembersTest() { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.removeMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeTest() { + ModelType modelTypeExpected = ModelType.service; + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType(ModelType.service); + + ModelType modelTypeResult = requestHandler.getModelType(Action.createInstance, modelInfo); + assertEquals(modelTypeResult, modelTypeExpected); + } + +} 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 new file mode 100644 index 0000000000..398966b0b3 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -0,0 +1,482 @@ +/*- + * ============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.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doNothing; +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; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +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.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +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.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 { + @Mock + private RequestHandlerUtils requestHandler; + + @Mock + private MsoRequest msoRequest; + + @Mock + private ServiceInstances serviceInstances; + + @Mock + private RequestsDbClient requestDbClient; + + @InjectMocks + @Spy + private ResumeOrchestrationRequest resumeReq; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + 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 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; + private final String version = "7"; + private final String requestUri = + "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 + public void setup() throws ValidateException, IOException { + // Setup general requestHandler mocks + when(requestHandler.getRequestUri(any(), anyString())).thenReturn(requestUri); + + // Setup InfraActiveRequests + setInfraActiveRequest(); + setCurrentActiveRequest(); + setInfraActiveRequestVfModule(); + + requestBody = infraActiveRequest.getRequestBody(); + sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); + requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json"); + 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 { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + 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 { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope(SERVICE); + currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + 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(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 + public void resumeOrchestationRequestTest() throws Exception { + Response response = null; + 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), anyString()); + doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class), + anyString(), nullable(String.class)); + + resumeReq.resumeOrchestrationRequest(REQUEST_ID, "v7", requestContext); + + verify(resumeReq).resumeRequest(infraActiveRequest, currentActiveRequest, version, null); + } + + @Test + public void resumeOrchestationRequestDbNullResultTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")).thenReturn(null); + + thrown.expect(ValidateException.class); + thrown.expectMessage( + "Null response from requestDB when searching by requestId: 00032ab7-na18-42e5-965d-8ea592502018"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeOrchestationRequestDbErrorTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")) + .thenThrow(HttpClientErrorException.class); + + thrown.expect(ValidateException.class); + thrown.expectMessage("Exception while performing requestDb lookup by requestId"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @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(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, instanceIdMap, SERVICE, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @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, + currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameter, sameBeanAs(result)); + } + + @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); + verify(requestDbClient).save(currentActiveRequest); + } + + @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(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, 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, instanceIdMap, SERVICE, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @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")); + + thrown.expect(ValidateException.class); + thrown.expectMessage("IOException while generating requestClientParameter to send to BPMN: IOException"); + resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, + "pnfCorrelationId", aLaCarte, sir); + } + + @Test + public void checkForInProgressRequest() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + SERVICE, currentActiveRequest); + doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest, + action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, infraActiveRequest); + + thrown.expect(DuplicateRequestException.class); + 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, SERVICE, + currentActiveRequest); + + 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, + SERVICE, currentActiveRequest); + doReturn(false).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + + 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..ea43a54e69 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,17 @@ 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.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 +82,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; @@ -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,194 @@ 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); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json index 90089c0c7e..baddb21617 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json @@ -34,7 +34,7 @@ }, { "request":{ - "requestId":"00032ab7-na18-42e5-965d-8ea592502018", + "requestId":"00032ab7-1a18-42e5-965d-8ea592502018", "requestScope":"vfModule", "requestType":"deleteInstance", "requestDetails":{ @@ -298,7 +298,7 @@ }, { "request":{ - "requestId":"00032ab7-na18-42e5-965d-8ea592502018", + "requestId":"00032ab7-1a18-42e5-965d-8ea592502018", "requestScope":"instanceGroup", "requestType":"addMembers", "requestDetails":{ diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json new file mode 100644 index 0000000000..41d7e4d706 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json @@ -0,0 +1,62 @@ +{ + "clientRequestId": "00032ab7-3fb3-42e5-965d-8ea592502016", + "action": "deleteInstance", + "requestStatus": "COMPLETE", + "statusMessage": "Vf Module has been deleted successfully.", + "progress": 100, + "startTime": "2016-12-22T13:29:54.000+0000", + "endTime": "2016-12-22T13:30:28.000+0000", + "source": "VID", + "vnfId": "b92f60c8-8de3-46c1-8dc1-e4390ac2b005", + "vnfName": null, + "vnfType": null, + "serviceType": null, + "aicNodeClli": null, + "tenantId": "6accefef3cb442ff9e644d589fb04107", + "provStatus": null, + "vnfParams": null, + "vnfOutputs": null, + "requestBody": "{\"modelInfo\":{\"modelType\":\"vfModule\",\"modelName\":\"test::base::module-0\"},\"requestInfo\":{\"source\":\"VID\"},\"cloudConfiguration\":{\"tenantId\":\"6accefef3cb442ff9e644d589fb04107\",\"lcpCloudRegionId\":\"n6\"}}", + "responseBody": null, + "lastModifiedBy": "BPMN", + "modifyTime": "2016-12-22T13:30:28.000+0000", + "requestType": null, + "volumeGroupId": null, + "volumeGroupName": null, + "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992", + "vfModuleName": null, + "vfModuleModelName": "test::base::module-0", + "aaiServiceId": null, + "aicCloudRegion": "n6", + "callBackUrl": null, + "correlator": null, + "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc", + "serviceInstanceName": null, + "requestScope": "vfModule", + "requestAction": "deleteInstance", + "networkId": null, + "networkName": null, + "networkType": null, + "requestorId": null, + "configurationId": null, + "configurationName": null, + "operationalEnvId": null, + "operationalEnvName": null, + "cloudApiRequests":[ + { + "id": 1, + "cloudIdentifier": "heatstackName/123123", + "requestBody":"{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}", + "created": "2016-12-22T13:29:54.000+0000" + } + ], + "requestURI": "00032ab7-3fb3-42e5-965d-8ea592502017", + "_links": { + "self": { + "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017" + }, + "infraActiveRequests": { + "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json new file mode 100644 index 0000000000..5da139e711 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json @@ -0,0 +1,13 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "usePreload": "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 new file mode 100644 index 0000000000..7e8ed4dee1 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json @@ -0,0 +1,19 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "aLaCarte":"false" + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion": "1.0", + "modelType":"service", + "modelName":"serviceModel" + } + } +}
\ 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/application-test.yaml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml index 712fbf54ca..2e1c6a9bdc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml @@ -83,6 +83,8 @@ mso: spring: + jersey: + type: filter datasource: jdbcUrl: jdbc:mariadb://localhost:3307/catalogdb username: root @@ -97,11 +99,10 @@ spring: naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy enable-lazy-load-no-trans: true database-platform: org.hibernate.dialect.MySQL5InnoDBDialect - jersey: - type: filter + security: usercredentials: - - + - username: test password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu' role: InfraPortal-Client 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 bc9003f5d0..c2eb21b18e 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 @@ -1108,6 +1108,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1134,6 +1135,8 @@ CREATE TABLE `vnfc_customization` ( `MODEL_NAME` varchar(200) NOT NULL, `TOSCA_NODE_TYPE` varchar(200) NOT NULL, `DESCRIPTION` varchar(1200) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL, `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; @@ -1460,6 +1463,16 @@ create table if not exists model ( FOREIGN KEY (`RECIPE`) REFERENCES `model_recipe` (`MODEL_ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `requestdb`.`cloud_api_requests` ( +`ID` INT(13) NOT NULL AUTO_INCREMENT, +`REQUEST_BODY` LONGTEXT NOT NULL, +`CLOUD_IDENTIFIER` VARCHAR(200) NULL, +`SO_REQUEST_ID` VARCHAR(45) NOT NULL, +`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +PRIMARY KEY (`ID`), +INDEX `fk_cloud_api_requests__so_request_id_idx` (`SO_REQUEST_ID` ASC)) +ENGINE = InnoDB DEFAULT CHARSET=latin1; + CREATE TABLE IF NOT EXISTS `workflow` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ARTIFACT_UUID` varchar(200) NOT NULL, @@ -1477,8 +1490,3 @@ CREATE TABLE IF NOT EXISTS `workflow` ( PRIMARY KEY (`ID`), UNIQUE KEY `UK_workflow` (`ARTIFACT_UUID`,`NAME`,`VERSION`,`SOURCE`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; - - - - - 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 b3d57b0137..3c4b1fa66b 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 @@ -89,6 +89,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep protected static final String REQUEST_ID = "requestId"; protected static final String REQUESTOR_ID = "requestorId"; protected static final String ACTION = "action"; + 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); @@ -173,13 +174,13 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep predicates.add(cb.equal(tableRoot.get(NETWORK_INSTANCE_NAME), instanceName)); } else if (requestScope.equals("configuration")) { predicates.add(cb.equal(tableRoot.get(CONFIGURATION_INSTANCE_NAME), instanceName)); - } else if (requestScope.equals("operationalEnvironment")) { + } else if (requestScope.equals(OPENV)) { predicates.add(cb.equal(tableRoot.get(OPERATIONAL_ENV_NAME), instanceName)); } } else { if (instanceIdMap != null) { - if ("service".equals(requestScope) && instanceIdMap.get("serviceInstanceId") != null) { + if ("service".equals(requestScope) && instanceIdMap.get(SERVICE_INSTANCE_ID) != null) { predicates .add(cb.equal(tableRoot.get(SERVICE_INSTANCE_ID), instanceIdMap.get("serviceInstanceId"))); } @@ -208,8 +209,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep instanceIdMap.get("configurationInstanceId"))); } - if (requestScope.equals("operationalEnvironment") - && instanceIdMap.get("operationalEnvironmentId") != null) { + if (requestScope.equals(OPENV) && instanceIdMap.get("operationalEnvironmentId") != null) { predicates.add( cb.equal(tableRoot.get(OPERATIONAL_ENV_ID), instanceIdMap.get("operationalEnvironmentId"))); } @@ -336,7 +336,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep // as the same requestorId can also match on different API methods final String resourceType = orchestrationMap.get("resourceType"); if (resourceType == null) { - predicates.add(cb.equal(tableRoot.get("requestScope"), "operationalEnvironment")); + predicates.add(cb.equal(tableRoot.get("requestScope"), OPENV)); } for (final Map.Entry<String, String> entry : orchestrationMap.entrySet()) { 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 2bd9936b3a..ef13df5cbd 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 @@ -1,5 +1,5 @@ -create table ACTIVATE_OPERATIONAL_ENV_SERVICE_MODEL_DISTRIBUTION_STATUS ( +create table IF NOT EXISTS ACTIVATE_OPERATIONAL_ENV_SERVICE_MODEL_DISTRIBUTION_STATUS ( REQUEST_ID varchar(255) not null, OPERATIONAL_ENV_ID varchar(255) not null, SERVICE_MODEL_VERSION_ID varchar(255) not null, @@ -13,7 +13,7 @@ create table ACTIVATE_OPERATIONAL_ENV_SERVICE_MODEL_DISTRIBUTION_STATUS ( primary key (REQUEST_ID,OPERATIONAL_ENV_ID, SERVICE_MODEL_VERSION_ID) ); -create table OPERATION_STATUS ( +create table IF NOT EXISTS OPERATION_STATUS ( SERVICE_ID varchar(255) not null, OPERATION_ID varchar(255) not null, SERVICE_NAME varchar(255), @@ -46,7 +46,7 @@ INSERT INTO PUBLIC.OPERATION_STATUS(SERVICE_ID, OPERATION_ID, OPERATION_TYPE, US primary key (SERVICE_ID,OPERATION_ID,RESOURCE_TEMPLATE_UUID) ); -CREATE CACHED TABLE PUBLIC.INFRA_ACTIVE_REQUESTS( +CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( REQUEST_ID VARCHAR NOT NULL SELECTIVITY 100, CLIENT_REQUEST_ID VARCHAR SELECTIVITY 6, ACTION VARCHAR SELECTIVITY 1, @@ -96,7 +96,8 @@ CREATE CACHED TABLE 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 ); 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 @@ -168,6 +169,17 @@ CREATE CACHED TABLE PUBLIC.ARCHIVED_INFRA_REQUESTS( REQUEST_URL VARCHAR SELECTIVITY 1 ); +CREATE TABLE IF NOT EXISTS cloud_api_requests( +`ID` INT(13) NOT NULL AUTO_INCREMENT, +`REQUEST_BODY` LONGTEXT NOT NULL, +`CLOUD_IDENTIFIER` VARCHAR(200) NULL, +`SO_REQUEST_ID` VARCHAR(45) NOT NULL, +`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +PRIMARY KEY (`ID`), +CONSTRAINT fk_cloud_api_req_infra_requests + FOREIGN KEY (SO_REQUEST_ID) + REFERENCES infra_active_requests (REQUEST_ID)); + CREATE CACHED TABLE PUBLIC.SITE_STATUS( SITE_NAME VARCHAR NOT NULL, STATUS VARCHAR, diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/CloudApiRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/CloudApiRequests.java new file mode 100644 index 0000000000..690d0ffbaf --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/CloudApiRequests.java @@ -0,0 +1,138 @@ +/*- + * ============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.db.request.beans; + +import java.io.Serializable; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrePersist; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.openpojo.business.annotation.BusinessKey; + + +@Entity +@JsonInclude(Include.NON_NULL) +@Table(name = "cloud_api_requests") +public class CloudApiRequests implements Serializable { + + + /** + * + */ + private static final long serialVersionUID = 4686890103198488984L; + + @JsonIgnore + @Id + @BusinessKey + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Integer id; + + + @Column(name = "SO_REQUEST_ID") + private String requestId; + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Column(name = "CLOUD_IDENTIFIER") + private String cloudIdentifier; + + @Column(name = "REQUEST_BODY", columnDefinition = "LONGTEXT") + private String requestBody; + + @Column(name = "CREATE_TIME", insertable = false, updatable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date created = null; + + + @Override + public boolean equals(final Object other) { + if (!(other instanceof CloudApiRequests)) { + return false; + } + CloudApiRequests castOther = (CloudApiRequests) other; + return new EqualsBuilder().append(id, castOther.id).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(id).toHashCode(); + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("id", id).append("cloudIdentifier", cloudIdentifier) + .append("requestBody", requestBody).append("created", created).toString(); + } + + @PrePersist + protected void createdAt() { + this.created = new Date(); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getCloudIdentifier() { + return cloudIdentifier; + } + + public void setCloudIdentifier(String cloudIdentifier) { + this.cloudIdentifier = cloudIdentifier; + } + + + public String getRequestBody() { + return requestBody; + } + + public void setRequestBody(String requestBody) { + this.requestBody = requestBody; + } + + public Date getCreated() { + return created; + } +} 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..9aa04ea8b2 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,7 @@ 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()).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 a1010a349c..5b40e40eb9 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,11 +22,17 @@ 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; +import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.FetchType; import javax.persistence.Id; +import javax.persistence.JoinColumn; import javax.persistence.MappedSuperclass; +import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Temporal; @@ -34,6 +40,7 @@ import javax.persistence.TemporalType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.lang3.builder.ToStringBuilder; import org.onap.so.requestsdb.TimestampXMLAdapter; +import uk.co.blackpepper.bowman.annotation.LinkedResource; import uk.co.blackpepper.bowman.annotation.ResourceId; @MappedSuperclass @@ -146,6 +153,12 @@ 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; + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID") + private List<CloudApiRequests> cloudApiRequests = new ArrayList<>(); @ResourceId public URI getRequestURI() { @@ -458,6 +471,15 @@ public abstract class InfraRequests implements java.io.Serializable { return requestAction; } + @LinkedResource + public List<CloudApiRequests> getCloudApiRequests() { + return cloudApiRequests; + } + + public void setCloudApiRequests(List<CloudApiRequests> cloudApiRequests) { + this.cloudApiRequests = cloudApiRequests; + } + public void setRequestAction(String requestAction) { this.requestAction = requestAction; } @@ -550,6 +572,14 @@ 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; + } + @PrePersist protected void onCreate() { if (requestScope == null) @@ -611,6 +641,7 @@ 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).toString(); } } 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 f2ff6fac00..1867b85de6 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,15 +67,17 @@ 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}") + @Value("${mso.adapters.requestDb.endpoint:#{null}}") protected String endpoint; - @Value("${mso.adapters.requestDb.auth}") + @Value("${mso.adapters.requestDb.auth:#{null}}") private String msoAdaptersAuth; private String getOrchestrationFilterURI = "/infraActiveRequests/getOrchestrationFiltersFromInfraActive/"; @@ -104,7 +106,10 @@ public class RequestsDbClient { private String requestProcessingDataURI = "/requestProcessingData"; - private final String findBySoRequestIdOrderByGroupingIdDesc = + private static final String findBySoRequestIdAndGroupIdAndName = + "/requestProcessingData/search/findOneBySoRequestIdAndGroupingIdAndName"; + + private static final String findBySoRequestIdOrderByGroupingIdDesc = "/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc"; @@ -333,12 +338,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); diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/requestsdb/RequestsDBHelperTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/requestsdb/RequestsDBHelperTest.java new file mode 100644 index 0000000000..b37ca0af63 --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/requestsdb/RequestsDBHelperTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Samsung 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.requestsdb; + +import static org.junit.Assert.assertEquals; +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 org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; + +@RunWith(MockitoJUnitRunner.class) +public class RequestsDBHelperTest { + + @InjectMocks + private RequestsDBHelper requestsDBHelper; + + @Mock + private RequestsDbClient requestsDbClient; + + @Test + public void updateInfraSuccessCompletion() { + + when(requestsDbClient.getInfraActiveRequestbyRequestId(any())).thenReturn(new InfraActiveRequests()); + + requestsDBHelper.updateInfraSuccessCompletion("messageText", "requestId", "operationalEnvId"); + + ArgumentCaptor<InfraActiveRequests> infraActiveRequests = ArgumentCaptor.forClass(InfraActiveRequests.class); + + verify(requestsDbClient, times(1)).save(infraActiveRequests.capture()); + assertEquals("COMPLETE", infraActiveRequests.getValue().getRequestStatus()); + assertEquals("APIH", infraActiveRequests.getValue().getLastModifiedBy()); + assertEquals(Long.valueOf(100), infraActiveRequests.getValue().getProgress()); + assertEquals("SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: messageText", + infraActiveRequests.getValue().getStatusMessage()); + assertEquals("operationalEnvId", infraActiveRequests.getValue().getOperationalEnvId()); + } + + @Test + public void updateInfraFailureCompletion() { + + when(requestsDbClient.getInfraActiveRequestbyRequestId(any())).thenReturn(new InfraActiveRequests()); + + requestsDBHelper.updateInfraFailureCompletion("messageText", "requestId", "operationalEnvId"); + + ArgumentCaptor<InfraActiveRequests> infraActiveRequests = ArgumentCaptor.forClass(InfraActiveRequests.class); + verify(requestsDbClient, times(1)).save(infraActiveRequests.capture()); + assertEquals("FAILED", infraActiveRequests.getValue().getRequestStatus()); + assertEquals("APIH", infraActiveRequests.getValue().getLastModifiedBy()); + assertEquals(Long.valueOf(100), infraActiveRequests.getValue().getProgress()); + assertEquals("FAILURE, operationalEnvironmentId - operationalEnvId; Error message: messageText", + infraActiveRequests.getValue().getStatusMessage()); + assertEquals("operationalEnvId", infraActiveRequests.getValue().getOperationalEnvId()); + + } +} |