diff options
104 files changed, 4492 insertions, 2079 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java index cd5879c093..e47dea6350 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java @@ -21,7 +21,6 @@ package org.openecomp.mso.openstack.utils; -import java.lang.StackTraceElement; import org.openecomp.mso.logger.MsoAlarmLogger; import org.openecomp.mso.logger.MsoLogger; import org.openecomp.mso.logger.MessageEnum; @@ -41,7 +40,7 @@ import com.woorea.openstack.quantum.model.NeutronError; public class MsoCommonUtils { - private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); protected static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); protected static String retryDelayProp = "ecomp.mso.adapters.po.retryDelay"; @@ -111,18 +110,18 @@ public class MsoCommonUtils { boolean retry = false; if (retryCodes != null ) { int code = e.getStatus(); - LOGGER.debug ("Config values RetryDelay:" + retryDelay + " RetryCount:" + retryCount + " RetryCodes:" + retryCodes + " ResponseCode:" + code); + logger.debug ("Config values RetryDelay:" + retryDelay + " RetryCount:" + retryCount + " RetryCodes:" + retryCodes + " ResponseCode:" + code); for (String rCode : retryCodes.split (",")) { try { if (retryCount > 0 && code == Integer.parseInt (rCode)) { retryCount--; retry = true; - LOGGER.debug ("OpenStackResponseException ResponseCode:" + code + " at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + logger.debug ("OpenStackResponseException ResponseCode:" + code + " at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); break; } } catch (NumberFormatException e1) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, "No retries. Exception in parsing retry code in config:" + rCode, "", "", MsoLogger.ErrorCode.SchemaError, "Exception in parsing retry code in config"); + logger.error (MessageEnum.RA_CONFIG_EXC, "No retries. Exception in parsing retry code in config:" + rCode, "", "", MsoLogger.ErrorCode.SchemaError, "Exception in parsing retry code in config"); throw e; } } @@ -132,7 +131,7 @@ public class MsoCommonUtils { try { Thread.sleep (retryDelay * 1000L); } catch (InterruptedException e1) { - LOGGER.debug ("Thread interrupted while sleeping", e1); + logger.debug ("Thread interrupted while sleeping", e1); } } else @@ -143,11 +142,11 @@ public class MsoCommonUtils { if (retryCount > 0) { retryCount--; - LOGGER.debug ("OpenstackConnectException at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + logger.debug ("OpenstackConnectException at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); try { Thread.sleep (retryDelay * 1000L); } catch (InterruptedException e1) { - LOGGER.debug ("Thread interrupted while sleeping", e1); + logger.debug ("Thread interrupted while sleeping", e1); } } else @@ -170,11 +169,11 @@ public class MsoCommonUtils { try { // Failed Keystone calls return an Error entity body. Error error = re.getResponse ().getErrorEntity (Error.class); - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Keystone Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone Error on " + context); + logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Keystone Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone Error on " + context); me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ()); } catch (Exception e2) { // Can't parse the body as an "Error". Report the HTTP error - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "HTTP Error on " + context + ": " + re.getStatus() + "," + re.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "HTTP Error on " + context, e2); + logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "HTTP Error on " + context + ": " + re.getStatus() + "," + re.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "HTTP Error on " + context, e2); me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); } @@ -192,7 +191,7 @@ public class MsoCommonUtils { me.addContext (context); // Generate an alarm for all connection errors. - LOGGER.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "Openstack Keystone connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone connection error on " + context); + logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "Openstack Keystone connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone connection error on " + context); alarmLogger.sendAlarm ("KeystoneIOError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); } @@ -212,16 +211,16 @@ public class MsoCommonUtils { try { // Failed Heat calls return an Explanation entity body. Explanation explanation = re.getResponse ().getErrorEntity (Explanation.class); - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error on " + context + ": " + explanation.toString(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - Openstack Error on " + context); + logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error on " + context + ": " + explanation.toString(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - Openstack Error on " + context); String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType() + ", error.message=" + explanation.getError().getMessage(); - LOGGER.debug(fullError); + logger.debug(fullError); me = new MsoOpenstackException (explanation.getCode (), explanation.getTitle (), //explanation.getExplanation ()); fullError); } catch (Exception e2) { // Couldn't parse the body as an "Explanation". Report the original HTTP error. - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); + logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); } @@ -240,7 +239,7 @@ public class MsoCommonUtils { // Generate an alarm for all connection errors. alarmLogger.sendAlarm ("HeatIOError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Heat connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Heat connection error on " + context); + logger.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Heat connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Heat connection error on " + context); } return me; @@ -259,11 +258,11 @@ public class MsoCommonUtils { try { // Failed Neutron calls return an NeutronError entity body NeutronError error = re.getResponse ().getErrorEntity (NeutronError.class); - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Error on " + context); + logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Error on " + context); me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ()); } catch (Exception e2) { // Couldn't parse body as a NeutronError. Report the HTTP error. - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack HTTP Error on " + context, e2); + logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack HTTP Error on " + context, e2); me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null); } @@ -282,7 +281,7 @@ public class MsoCommonUtils { // Generate an alarm for all connection errors. alarmLogger.sendAlarm ("NeutronIOError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Connection error on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Connection error on "+ context); + logger.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Connection error on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Connection error on "+ context); } return me; @@ -300,7 +299,7 @@ public class MsoCommonUtils { me.setCategory (MsoExceptionCategory.INTERNAL); // Always generate an alarm for internal exceptions - LOGGER.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); + logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); alarmLogger.sendAlarm ("AdapterInternalError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); return me; diff --git a/adapters/mso-vfc-adapter/WebContent/WEB-INF/jboss-deployment-structure.xml b/adapters/mso-vfc-adapter/WebContent/WEB-INF/jboss-deployment-structure.xml index e7bc08ae83..fb268917f2 100644 --- a/adapters/mso-vfc-adapter/WebContent/WEB-INF/jboss-deployment-structure.xml +++ b/adapters/mso-vfc-adapter/WebContent/WEB-INF/jboss-deployment-structure.xml @@ -1,17 +1,21 @@ <jboss-deployment-structure>
<deployment>
- <!-- Exclusions allow you to prevent the server from automatically adding
- some dependencies -->
+ <!-- Exclusions allow you to prevent the server from automatically adding some dependencies -->
<exclusions>
<module name="org.apache.log4j" />
<module name="org.slf4j" />
<module name="org.slf4j.impl" />
+ <module name="org.jboss.resteasy.resteasy-jackson-provider" />
+ <module name="org.jboss.resteasy.resteasy-jettison-provider" />
</exclusions>
<dependencies>
- <module name="org.jboss.jandex" slot="main" />
- <module name="org.javassist" slot="main" />
- <module name="org.antlr" slot="main" />
- <module name="org.dom4j" slot="main" />
+ <module name="org.jboss.jandex" slot="main" />
+ <module name="org.javassist" slot="main" />
+ <module name="org.antlr" slot="main" />
+ <module name="org.dom4j" slot="main" />
+ <module name="org.jboss.resteasy.resteasy-jackson2-provider" services="import" />
+ <!-- This module contain the ProviderBase class: -->
+ <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" export="true" />
</dependencies>
</deployment>
-</jboss-deployment-structure>
\ No newline at end of file +</jboss-deployment-structure>
diff --git a/adapters/mso-vfc-adapter/WebContent/WEB-INF/web.xml b/adapters/mso-vfc-adapter/WebContent/WEB-INF/web.xml index 0c198defa0..cd97471b5b 100644 --- a/adapters/mso-vfc-adapter/WebContent/WEB-INF/web.xml +++ b/adapters/mso-vfc-adapter/WebContent/WEB-INF/web.xml @@ -41,22 +41,10 @@ </servlet> <servlet-mapping> <servlet-name>Resteasy</servlet-name> - <url-pattern>/vfcadapter/*</url-pattern> + <url-pattern>/rest/*</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> - <web-resource-name>SoapRequests</web-resource-name> - <description>Soap Ingress Requests</description> - <url-pattern>/VfcAdapter</url-pattern> - <url-pattern>/VfcAdapterAsync</url-pattern> - <http-method>POST</http-method> - </web-resource-collection> - <auth-constraint> - <role-name>BPEL-Client</role-name> - </auth-constraint> - </security-constraint> - <security-constraint> - <web-resource-collection> <web-resource-name>SiteStatus</web-resource-name> <description>SiteStatus APIs</description> <url-pattern>/rest/setStatus/*</url-pattern> @@ -70,7 +58,7 @@ <web-resource-collection> <web-resource-name>RestRequests</web-resource-name> <description>Rest Ingress Requests</description> - <url-pattern>/rest/v1/vfc/*</url-pattern> + <url-pattern>/rest/v1/vfcadapter/*</url-pattern> <http-method>DELETE</http-method> <http-method>GET</http-method> <http-method>POST</http-method> diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/AaiUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/AaiUtil.java index 719385f97f..7f1a6daae5 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/AaiUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/AaiUtil.java @@ -34,6 +34,7 @@ public class AaiUtil { public static RestfulResponse addRelation(String globalSubsriberId, String serviceType, String serviceInstanceId, String resourceInstanceId) { // sent rest to aai to add relation for service and ns. + return null; } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcAdapterRest.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcAdapterRest.java index 6c2ab4d081..ef3c1b79ca 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcAdapterRest.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcAdapterRest.java @@ -20,7 +20,6 @@ package org.openecomp.mso.adapters.vfc; -import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.POST; @@ -29,14 +28,12 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import org.openecomp.mso.adapters.vfc.exceptions.ApplicationException; import org.openecomp.mso.adapters.vfc.model.NSResourceInputParameter; import org.openecomp.mso.adapters.vfc.model.NsOperationKey; import org.openecomp.mso.adapters.vfc.model.RestfulResponse; import org.openecomp.mso.adapters.vfc.util.JsonUtil; -import org.openecomp.mso.adapters.vfc.util.RestfulUtil; import org.openecomp.mso.adapters.vfc.util.ValidateUtil; import org.openecomp.mso.logger.MsoLogger; @@ -48,164 +45,149 @@ import org.openecomp.mso.logger.MsoLogger; * @author * @version ONAP Amsterdam Release 2017-08-28 */ -@Path("/vfcadapter/v1") +@Path("/v1/vfcadapter") public class VfcAdapterRest { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); - private final VfcManager driverMgr = new VfcManager(); + private final VfcManager driverMgr = new VfcManager(); - public VfcAdapterRest() { + public VfcAdapterRest() { - } - - /** - * Create a NS <br> - * - * @param servletReq the http request - * @return - * @since ONAP Amsterdam Release - */ - @POST - @Path("/ns") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - public Response createNfvoNs(HttpServletRequest servletReq) { - // Step 1: get parameters from request for current node - try { - String body = RestfulUtil.getRequestBody(servletReq); - ValidateUtil.assertObjectNotNull(body); - LOGGER.debug("body from request is {}" + body); - NSResourceInputParameter nsInput = JsonUtil.unMarshal(body, NSResourceInputParameter.class); - RestfulResponse rsp = driverMgr.createNs(nsInput); - return buildResponse(rsp); - } catch (ApplicationException e) { - LOGGER.debug("ApplicationException: ", e); - return e.buildErrorResponse(); } - } - /** - * Delete NS instance<br> - * - * @param servletReq http request - * @return response - * @since ONAP Amsterdam Release - */ - @DELETE - @Path("/ns/{nsInstanceId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - public Response deleteNfvoNs(HttpServletRequest servletReq, - @PathParam("nsInstanceId") String nsInstanceId) { - try { - // Step 1: get parameters from request for current node - String body = RestfulUtil.getRequestBody(servletReq); - ValidateUtil.assertObjectNotNull(body); - LOGGER.debug("body from request is {}" + body); - NsOperationKey nsOperationKey = JsonUtil.unMarshal(body, NsOperationKey.class); - RestfulResponse rsp = driverMgr.deleteNs(nsOperationKey, nsInstanceId); - return buildResponse(rsp); - } catch (ApplicationException e) { - LOGGER.debug("ApplicationException: ", e); - return e.buildErrorResponse(); + /** + * Create a NS <br> + * + * @param servletReq the http request + * @return + * @since ONAP Amsterdam Release + */ + @POST + @Path("/ns") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + public Response createNfvoNs(String data) { + try { + ValidateUtil.assertObjectNotNull(data); + LOGGER.debug("body from request is {}" + data); + NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class); + RestfulResponse rsp = driverMgr.createNs(nsInput); + return buildResponse(rsp); + } catch(ApplicationException e) { + LOGGER.debug("ApplicationException: ", e); + return e.buildErrorResponse(); + } } - } - /** - * Query Operation job status <br> - * - * @param servletReq The Http Request - * @param jobId The job id - * @return - * @since ONAP Amsterdam Release - */ - @POST - @Path("/jobs/{jobId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - public Response queryNfvoJobStatus(HttpServletRequest servletReq, - @PathParam("jobId") String jobId) { - try { - ValidateUtil.assertObjectNotNull(jobId); - String body = RestfulUtil.getRequestBody(servletReq); - ValidateUtil.assertObjectNotNull(body); - LOGGER.debug("body from request is {}" + body); - NsOperationKey nsOperationKey = JsonUtil.unMarshal(body, NsOperationKey.class); + /** + * Delete NS instance<br> + * + * @param servletReq http request + * @return response + * @since ONAP Amsterdam Release + */ + @DELETE + @Path("/ns/{nsInstanceId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + public Response deleteNfvoNs(String data, @PathParam("nsInstanceId") String nsInstanceId) { + try { + + ValidateUtil.assertObjectNotNull(data); + LOGGER.debug("body from request is {}" + data); + NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class); + RestfulResponse rsp = driverMgr.deleteNs(nsOperationKey, nsInstanceId); + return buildResponse(rsp); + } catch(ApplicationException e) { + LOGGER.debug("ApplicationException: ", e); + return e.buildErrorResponse(); + } + } - RestfulResponse rsp = driverMgr.getNsProgress(nsOperationKey, jobId); - return buildResponse(rsp); - } catch (ApplicationException e) { - LOGGER.debug("ApplicationException: ", e); - return e.buildErrorResponse(); + /** + * Query Operation job status <br> + * + * @param servletReq The Http Request + * @param jobId The job id + * @return + * @since ONAP Amsterdam Release + */ + @POST + @Path("/jobs/{jobId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + public Response queryNfvoJobStatus(String data, @PathParam("jobId") String jobId) { + try { + ValidateUtil.assertObjectNotNull(data); + LOGGER.debug("body from request is {}" + data); + NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class); + RestfulResponse rsp = driverMgr.getNsProgress(nsOperationKey, jobId); + return buildResponse(rsp); + } catch(ApplicationException e) { + LOGGER.debug("ApplicationException: ", e); + return e.buildErrorResponse(); + } } - } - /** - * Instantiate NS instance <br> - * - * @param servletReq The http request - * @param nsInstanceId The NS instance id - * @return - * @since ONAP Amsterdam Release - */ - @POST - @Path("/ns/{nsInstanceId}/instantiate") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - public Response instantiateNfvoNs(HttpServletRequest servletReq, - @PathParam("nsInstanceId") String nsInstanceId) { - String body = RestfulUtil.getRequestBody(servletReq); - try { - ValidateUtil.assertObjectNotNull(body); - LOGGER.debug("body from request is {}" + body); - NSResourceInputParameter nsInput = JsonUtil.unMarshal(body, NSResourceInputParameter.class); - RestfulResponse rsp = driverMgr.instantiateNs(nsInstanceId, nsInput); - return buildResponse(rsp); - } catch (ApplicationException e) { - LOGGER.debug("ApplicationException: ", e); - return e.buildErrorResponse(); + /** + * Instantiate NS instance <br> + * + * @param servletReq The http request + * @param nsInstanceId The NS instance id + * @return + * @since ONAP Amsterdam Release + */ + @POST + @Path("/ns/{nsInstanceId}/instantiate") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + public Response instantiateNfvoNs(String data, @PathParam("nsInstanceId") String nsInstanceId) { + try { + ValidateUtil.assertObjectNotNull(data); + LOGGER.debug("body from request is {}" + data); + NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class); + RestfulResponse rsp = driverMgr.instantiateNs(nsInstanceId, nsInput); + return buildResponse(rsp); + } catch(ApplicationException e) { + LOGGER.debug("ApplicationException: ", e); + return e.buildErrorResponse(); + } } - } - /** - * Terminate NS instance <br> - * - * @param servletReq The http request - * @param nsInstanceId The NS instance id - * @return - * @since ONAP Amsterdam Release - */ - @POST - @Path("/ns/{nsInstanceId}/terminate") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - public Response terminateNfvoNs(HttpServletRequest servletReq, - @PathParam("nsInstanceId") String nsInstanceId) { - try { - ValidateUtil.assertObjectNotNull(nsInstanceId); - String body = RestfulUtil.getRequestBody(servletReq); - ValidateUtil.assertObjectNotNull(body); - LOGGER.debug("body from request is {}" + body); - NsOperationKey nsOperationKey = JsonUtil.unMarshal(body, NsOperationKey.class); - RestfulResponse rsp = driverMgr.terminateNs(nsOperationKey, nsInstanceId); - return buildResponse(rsp); - } catch (ApplicationException e) { - LOGGER.debug("ApplicationException: ", e); - return e.buildErrorResponse(); + /** + * Terminate NS instance <br> + * + * @param servletReq The http request + * @param nsInstanceId The NS instance id + * @return + * @since ONAP Amsterdam Release + */ + @POST + @Path("/ns/{nsInstanceId}/terminate") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + public Response terminateNfvoNs(String data, @PathParam("nsInstanceId") String nsInstanceId) { + try { + ValidateUtil.assertObjectNotNull(data); + LOGGER.debug("body from request is {}" + data); + NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class); + RestfulResponse rsp = driverMgr.terminateNs(nsOperationKey, nsInstanceId); + return buildResponse(rsp); + } catch(ApplicationException e) { + LOGGER.debug("ApplicationException: ", e); + return e.buildErrorResponse(); + } } - } - /** - * build response from restful response <br> - * - * @param rsp general response object - * @return - * @since ONAP Amsterdam Release - */ - private Response buildResponse(RestfulResponse rsp) { - ResponseBuilder rspBuilder = Response.status(rsp.getStatus()); - rspBuilder.entity(rsp.getResponseContent()); - return rspBuilder.build(); - } + /** + * build response from restful response <br> + * + * @param rsp general response object + * @return + * @since ONAP Amsterdam Release + */ + private Response buildResponse(RestfulResponse rsp) { + return Response.status(rsp.getStatus()).entity(rsp.getResponseContent()).build(); + } } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcManager.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcManager.java index fed6d5e805..e3297ff2d4 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcManager.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcManager.java @@ -111,22 +111,8 @@ public class VfcManager { ValidateUtil.assertObjectNotNull(createRsp); LOGGER.info("create ns response status is : {}", createRsp.getStatus()); LOGGER.info("create ns response content is : {}", createRsp.getResponseContent()); - @SuppressWarnings("unchecked") - Map<String, String> rsp = JsonUtil.unMarshal(createRsp.getResponseContent(), Map.class); - String nsInstanceId = rsp.get(CommonConstant.NS_INSTANCE_ID); - if (ValidateUtil.isStrEmpty(nsInstanceId)) { - LOGGER.error("Invalid instanceId from create operation"); - throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, - DriverExceptionID.INVALID_RESPONSEE_FROM_CREATE_OPERATION); - } - LOGGER.info("create ns -> end"); - LOGGER.info("save segment and operaton info -> begin"); - // Step 5: add relation between service and NS - AaiUtil.addRelation(segInput.getNsOperationKey().getGlobalSubscriberId(), - segInput.getNsOperationKey().getServiceType(), segInput.getNsOperationKey().getServiceId(), - nsInstanceId); - // Step 6: save resource operation information + // Step 5: save resource operation information ResourceOperationStatus nsOperInfo = (RequestsDatabase.getInstance()) .getResourceOperationStatus(segInput.getNsOperationKey().getServiceId(), segInput.getNsOperationKey().getOperationId(), @@ -142,6 +128,20 @@ public class VfcManager { throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.FAIL_TO_CREATE_NS); } + @SuppressWarnings("unchecked") + Map<String, String> rsp = JsonUtil.unMarshal(createRsp.getResponseContent(), Map.class); + String nsInstanceId = rsp.get(CommonConstant.NS_INSTANCE_ID); + if (ValidateUtil.isStrEmpty(nsInstanceId)) { + LOGGER.error("Invalid instanceId from create operation"); + throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, + DriverExceptionID.INVALID_RESPONSEE_FROM_CREATE_OPERATION); + } + LOGGER.info("create ns -> end"); + LOGGER.info("save segment and operaton info -> begin"); + // Step 6: add relation between service and NS + AaiUtil.addRelation(segInput.getNsOperationKey().getGlobalSubscriberId(), + segInput.getNsOperationKey().getServiceType(), segInput.getNsOperationKey().getServiceId(), + nsInstanceId); LOGGER.info("save segment and operation info -> end"); return createRsp; } @@ -220,18 +220,27 @@ public class VfcManager { String url = getUrl(nsInstanceId, CommonConstant.Step.INSTANTIATE); String methodType = CommonConstant.MethodType.POST; - RestfulResponse instRsp = RestfulUtil.send(url, methodType, instReq); + RestfulResponse instRsp = RestfulUtil.send(url, methodType, instReq); + ResourceOperationStatus nsOperInfo = (RequestsDatabase.getInstance()) + .getResourceOperationStatus(segInput.getNsOperationKey().getServiceId(), + segInput.getNsOperationKey().getOperationId(), + segInput.getNsOperationKey().getNodeTemplateUUID()); ValidateUtil.assertObjectNotNull(instRsp); + if (!HttpCode.isSucess(instRsp.getStatus())) { + LOGGER.error("update segment operation status : fail to instantiate ns"); + nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR); + nsOperInfo.setErrorCode(String.valueOf(instRsp.getStatus())); + nsOperInfo.setStatusDescription(CommonConstant.StatusDesc.INSTANTIATE_NS_FAILED); + (RequestsDatabase.getInstance()).updateResOperStatus(nsOperInfo); + throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, + DriverExceptionID.FAIL_TO_INSTANTIATE_NS); + } LOGGER.info("instantiate ns response status is : {}", instRsp.getStatus()); LOGGER.info("instantiate ns response content is : {}", instRsp.getResponseContent()); - ValidateUtil.assertObjectNotNull(instRsp.getResponseContent()); + ValidateUtil.assertObjectNotNull(instRsp.getResponseContent()); @SuppressWarnings("unchecked") Map<String, String> rsp = JsonUtil.unMarshal(instRsp.getResponseContent(), Map.class); String jobId = rsp.get(CommonConstant.JOB_ID); - ResourceOperationStatus nsOperInfo = (RequestsDatabase.getInstance()) - .getResourceOperationStatus(segInput.getNsOperationKey().getServiceId(), - segInput.getNsOperationKey().getOperationId(), - segInput.getNsOperationKey().getNodeTemplateUUID()); if (ValidateUtil.isStrEmpty(jobId)) { LOGGER.error("Invalid jobId from instantiate operation"); nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR); @@ -242,17 +251,6 @@ public class VfcManager { DriverExceptionID.INVALID_RESPONSE_FROM_INSTANTIATE_OPERATION); } LOGGER.info("instantiate ns -> end"); - - if (!HttpCode.isSucess(instRsp.getStatus())) { - LOGGER.error("update segment operation status : fail to instantiate ns"); - nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR); - nsOperInfo.setErrorCode(String.valueOf(instRsp.getStatus())); - nsOperInfo.setStatusDescription(CommonConstant.StatusDesc.INSTANTIATE_NS_FAILED); - (RequestsDatabase.getInstance()).updateResOperStatus(nsOperInfo); - throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, - DriverExceptionID.FAIL_TO_INSTANTIATE_NS); - } - // Step 3: update segment operation job id LOGGER.info("update resource operation status job id -> begin"); nsOperInfo.setJobId(jobId); @@ -296,6 +294,17 @@ public class VfcManager { ValidateUtil.assertObjectNotNull(terminateRsp); LOGGER.info("terminate ns response status is : {}", terminateRsp.getStatus()); LOGGER.info("terminate ns response content is : {}", terminateRsp.getResponseContent()); + // Step 3: update segment operation + if (!HttpCode.isSucess(terminateRsp.getStatus())) { + LOGGER.error("fail to instantiate ns"); + nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR); + nsOperInfo.setErrorCode(String.valueOf(terminateRsp.getStatus())); + nsOperInfo.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED); + (RequestsDatabase.getInstance()).updateResOperStatus(nsOperInfo); + + throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, + DriverExceptionID.FAIL_TO_TERMINATE_NS); + } @SuppressWarnings("unchecked") Map<String, String> rsp = JsonUtil.unMarshal(terminateRsp.getResponseContent(), Map.class); String jobId = rsp.get(CommonConstant.JOB_ID); @@ -310,17 +319,6 @@ public class VfcManager { } LOGGER.info("terminate ns -> end"); - // Step 3: update segment operation - if (!HttpCode.isSucess(terminateRsp.getStatus())) { - LOGGER.error("fail to instantiate ns"); - nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR); - nsOperInfo.setErrorCode(String.valueOf(terminateRsp.getStatus())); - nsOperInfo.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED); - (RequestsDatabase.getInstance()).updateResOperStatus(nsOperInfo); - - throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, - DriverExceptionID.FAIL_TO_TERMINATE_NS); - } LOGGER.info("update segment job id -> begin"); nsOperInfo.setJobId(jobId); (RequestsDatabase.getInstance()).updateResOperStatus(nsOperInfo); diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/LocationConstraint.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/LocationConstraint.java index 8b259e915b..214451b22f 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/LocationConstraint.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/LocationConstraint.java @@ -19,8 +19,6 @@ */ package org.openecomp.mso.adapters.vfc.model; -import java.util.Map; - /** * <br> * <p> @@ -39,7 +37,7 @@ public class LocationConstraint { /** * location constraints: vimId */ - private Map<String, String> locationConstraints; + private VimLocation locationConstraints; /** * @return Returns the vnfProfileId. @@ -55,17 +53,19 @@ public class LocationConstraint { this.vnfProfileId = vnfProfileId; } + /** * @return Returns the locationConstraints. */ - public Map<String, String> getLocationConstraints() { + public VimLocation getLocationConstraints() { return locationConstraints; } + /** * @param locationConstraints The locationConstraints to set. */ - public void setLocationConstraints(Map<String, String> locationConstraints) { + public void setLocationConstraints(VimLocation locationConstraints) { this.locationConstraints = locationConstraints; } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NSResourceInputParameter.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NSResourceInputParameter.java index f88a11dee8..1f166062d1 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NSResourceInputParameter.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NSResourceInputParameter.java @@ -19,6 +19,15 @@ */ package org.openecomp.mso.adapters.vfc.model; +import java.io.ByteArrayOutputStream; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; + +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.SerializationConfig; +import org.openecomp.mso.logger.MsoLogger; + /** * NS Create Input Parameter For VFC Adapter<br> * <p> @@ -28,6 +37,8 @@ package org.openecomp.mso.adapters.vfc.model; */ public class NSResourceInputParameter { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); + private NsOperationKey nsOperationKey; private String nsServiceName; @@ -91,5 +102,29 @@ public class NSResourceInputParameter { public void setNsOperationKey(NsOperationKey nsOperationKey) { this.nsOperationKey = nsOperationKey; } + public String toJsonString() { + String jsonString = null; + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE); + jsonString = mapper.writeValueAsString(this); + } catch (Exception e) { + LOGGER.debug("Exception:", e); + } + return jsonString; + } + public String toXmlString() { + try { + ByteArrayOutputStream bs = new ByteArrayOutputStream(); + JAXBContext context = JAXBContext.newInstance(this.getClass()); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML + marshaller.marshal(this, bs); + return bs.toString(); + } catch (Exception e) { + LOGGER.debug("Exception:", e); + return ""; + } + } } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsOperationKey.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsOperationKey.java index e4d6d66cda..23bf36fe0c 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsOperationKey.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsOperationKey.java @@ -17,6 +17,7 @@ * limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.openecomp.mso.adapters.vfc.model;
/**
@@ -26,20 +27,20 @@ package org.openecomp.mso.adapters.vfc.model; * </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-09-15
+ * @version ONAP Amsterdam Release 2017-09-15
*/
public class NsOperationKey {
-
+
/**
* The subscriber id
*/
private String globalSubscriberId;
-
+
/**
* The serviceType
*/
private String serviceType;
-
+
/**
* The service ID
*/
@@ -49,15 +50,12 @@ public class NsOperationKey { * The Operation ID
*/
private String operationId;
-
+
/**
* the NS template uuid
*/
private String nodeTemplateUUID;
-
-
-
/**
* @return Returns the globalSubscriberId.
*/
@@ -65,14 +63,13 @@ public class NsOperationKey { return globalSubscriberId;
}
-
/**
* @param globalSubscriberId The globalSubscriberId to set.
*/
public void setGlobalSubscriberId(String globalSubscriberId) {
this.globalSubscriberId = globalSubscriberId;
}
-
+
/**
* @return Returns the serviceType.
*/
@@ -80,8 +77,6 @@ public class NsOperationKey { return serviceType;
}
-
-
/**
* @param serviceType The serviceType to set.
*/
@@ -89,9 +84,7 @@ public class NsOperationKey { this.serviceType = serviceType;
}
-
/**
- *
* <br>
*
* @return
@@ -102,7 +95,6 @@ public class NsOperationKey { }
/**
- *
* <br>
*
* @param serviceId
@@ -113,7 +105,6 @@ public class NsOperationKey { }
/**
- *
* <br>
*
* @return
@@ -124,7 +115,6 @@ public class NsOperationKey { }
/**
- *
* <br>
*
* @param operationId
@@ -134,7 +124,6 @@ public class NsOperationKey { this.operationId = operationId;
}
-
/**
* @return Returns the nodeTemplateUUID.
*/
@@ -142,7 +131,6 @@ public class NsOperationKey { return nodeTemplateUUID;
}
-
/**
* @param nodeTemplateUUID The nodeTemplateUUID to set.
*/
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java index 79d770ba4d..2a5c305926 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java @@ -19,6 +19,7 @@ */ package org.openecomp.mso.adapters.vfc.model; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -34,8 +35,7 @@ public class NsParameters { private List<LocationConstraint> locationConstraints; - private Map<String, String> additionalParamForNs; - + private Map<String, Object> additionalParamForNs = new HashMap<String,Object>(); /** * @return Returns the locationConstraints. */ @@ -50,18 +50,19 @@ public class NsParameters { this.locationConstraints = locationConstraints; } + /** * @return Returns the additionalParamForNs. */ - public Map<String, String> getAdditionalParamForNs() { + public Map<String, Object> getAdditionalParamForNs() { return additionalParamForNs; } + /** * @param additionalParamForNs The additionalParamForNs to set. */ - public void setAdditionalParamForNs(Map<String, String> additionalParamForNs) { + public void setAdditionalParamForNs(Map<String, Object> additionalParamForNs) { this.additionalParamForNs = additionalParamForNs; } - } diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNData.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/VimLocation.java index b2dcefb304..3c07f9cd8b 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNData.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/VimLocation.java @@ -2,7 +2,7 @@ * ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.
@@ -17,31 +17,34 @@ * limitations under the License.
* ============LICENSE_END=========================================================
*/
+package org.openecomp.mso.adapters.vfc.model;
-package org.openecomp.camunda.bpmn.plugin.urnmap.db;
+/**
+ *
+ * <br>
+ * <p>
+ * </p>
+ *
+ * @author
+ * @version ONAP Amsterdam Release 2017-10-18
+ */
+public class VimLocation {
+ private String vimId;
-public class URNData {
+
+ /**
+ * @return Returns the vimId.
+ */
+ public String getVimId() {
+ return vimId;
+ }
- private String URNName;
- private String URNValue;
- private String Ver_;
- public String getURNName() {
- return URNName;
- }
- public void setURNName(String uRNName) {
- URNName = uRNName;
- }
- public String getURNValue() {
- return URNValue;
- }
- public void setURNValue(String uRNValue) {
- URNValue = uRNValue;
- }
- public String getVer_() {
- return Ver_;
- }
- public void setVer_(String ver_) {
- Ver_ = ver_;
- }
-
+
+ /**
+ * @param vimId The vimId to set.
+ */
+ public void setVimId(String vimId) {
+ this.vimId = vimId;
+ }
+
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java index 85065c0953..e8718fafc2 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java @@ -18,17 +18,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.openecomp.mso.adapters.vfc.util; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; -import javax.servlet.http.HttpServletRequest; - import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; @@ -46,6 +41,8 @@ import org.openecomp.mso.adapters.vfc.model.RestfulResponse; import org.openecomp.mso.logger.MessageEnum; import org.openecomp.mso.logger.MsoAlarmLogger; import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; /** * <br> @@ -58,179 +55,197 @@ import org.openecomp.mso.logger.MsoLogger; */ public class RestfulUtil { - /** - * Log service - */ - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); - - private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger(); - - private static final int DEFAULT_TIME_OUT = 60; - - private RestfulUtil() { - - } - - public static RestfulResponse send(String url, String methodType, String content) { - LOGGER.info(MessageEnum.RA_NS_EXC, url, "VFC", ""); - LOGGER.debug("VFC Request Body:\n" + content); - - HttpRequestBase method = null; - HttpResponse httpResponse = null; - - try { - int timeout = DEFAULT_TIME_OUT; - - RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) - .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build(); - - HttpClient client = HttpClientBuilder.create().build(); - - if ("POST".equals(methodType)) { - HttpPost httpPost = new HttpPost(url); - httpPost.setConfig(requestConfig); - httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); - method = httpPost; - } else if ("PUT".equals(methodType)) { - HttpPut httpPut = new HttpPut(url); - httpPut.setConfig(requestConfig); - httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); - method = httpPut; - } else if ("GET".equals(methodType)) { - HttpGet httpGet = new HttpGet(url); - httpGet.setConfig(requestConfig); - method = httpGet; - } else if ("DELETE".equals(methodType)) { - HttpDelete httpDelete = new HttpDelete(url); - httpDelete.setConfig(requestConfig); - method = httpDelete; - } - - // now VFC have no auth - // String userCredentials = - // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP, - // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); - // String authorization = "Basic " + - // DatatypeConverter.printBase64Binary(userCredentials.getBytes()); - // method.setHeader("Authorization", authorization); - - httpResponse = client.execute(method); - - String responseContent = null; - if (httpResponse.getEntity() != null) { - responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); - } - - int statusCode = httpResponse.getStatusLine().getStatusCode(); - String statusMessage = httpResponse.getStatusLine().getReasonPhrase(); - - LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage - + (responseContent == null ? "" : System.lineSeparator() + responseContent)); - - if (httpResponse.getStatusLine().getStatusCode() >= 300) { - String errMsg = "VFC returned " + statusCode + " " + statusMessage; - logError(errMsg); - return createResponse(statusCode, errMsg); - } - - httpResponse = null; - - if (null != method) { - method.reset(); - } else { - LOGGER.debug("method is NULL:"); - } - - method = null; - - LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", ""); - return createResponse(statusCode, responseContent); - - } catch (SocketTimeoutException e) { - String errMsg = "Request to SDNC timed out"; - logError(errMsg, e); - return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg); - - } catch (ConnectTimeoutException e) { - String errMsg = "Request to SDNC timed out"; - logError(errMsg, e); - return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg); - - } catch (Exception e) { - String errMsg = "Error processing request to SDNC"; - logError(errMsg, e); - return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg); - - } finally { - if (httpResponse != null) { - try { - EntityUtils.consume(httpResponse.getEntity()); - } catch (Exception e) { - LOGGER.debug("Exception :", e); - } - } + /** + * Log service + */ + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + + private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger(); - if (method != null) { + private static final int DEFAULT_TIME_OUT = 60000; + + private static final MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + + public static String getMsbHost() { + String msbIp = "10.229.32.131"; + String msbPort = "8090"; try { - method.reset(); - } catch (Exception e) { - LOGGER.debug("Exception :", e); + msbIp = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-ip", + "10.229.32.131"); + msbPort = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-port", "8099"); + + } catch(MsoPropertiesException e) { + LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, + "Get msb properties failed"); + e.printStackTrace(); } - } + return "http://" + msbIp + ":" + msbPort; + } + + private RestfulUtil() { + } - } - - private static void logError(String errMsg, Throwable t) { - LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, - t); - ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); - } - - private static void logError(String errMsg) { - LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg); - ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); - } - - private static RestfulResponse createResponse(int statusCode, String content) { - RestfulResponse rsp = new RestfulResponse(); - rsp.setStatus(statusCode); - rsp.setResponseContent(content); - return rsp; - } - - /** - * @param request - * @return - */ - public static String getRequestBody(HttpServletRequest request) { - String body = null; - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader bufferedReader = null; - try { - InputStream inputStream = request.getInputStream(); - if (inputStream != null) { - bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - char[] charBuffer = new char[128]; - int bytesRead = -1; - while ((bytesRead = bufferedReader.read(charBuffer)) > 0) - stringBuilder.append(charBuffer, 0, bytesRead); - } - } catch (IOException ex) { - LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, - "read inputStream buffer catch exception:", ex); - } finally { - if (bufferedReader != null) { + + public static RestfulResponse send(String url, String methodType, String content) { + String msbUrl = getMsbHost() + url; + LOGGER.info(MessageEnum.RA_NS_EXC, msbUrl, "VFC", ""); + LOGGER.debug("VFC Request Body:\n" + content); + + HttpRequestBase method = null; + HttpResponse httpResponse = null; + try { - bufferedReader.close(); - } catch (IOException ex) { - LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, - "close buffer catch exception:", ex); + int timeout = DEFAULT_TIME_OUT; + + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout).build(); + + HttpClient client = HttpClientBuilder.create().build(); + + if("POST".equals(methodType.toUpperCase())) { + HttpPost httpPost = new HttpPost(msbUrl); + httpPost.setConfig(requestConfig); + httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); + method = httpPost; + } else if("PUT".equals(methodType.toUpperCase())) { + HttpPut httpPut = new HttpPut(msbUrl); + httpPut.setConfig(requestConfig); + httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); + method = httpPut; + } else if("GET".equals(methodType.toUpperCase())) { + HttpGet httpGet = new HttpGet(msbUrl); + httpGet.setConfig(requestConfig); + method = httpGet; + } else if("DELETE".equals(methodType.toUpperCase())) { + HttpDelete httpDelete = new HttpDelete(msbUrl); + httpDelete.setConfig(requestConfig); + method = httpDelete; + } + + // now VFC have no auth + // String userCredentials = + // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP, + // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); + // String authorization = "Basic " + + // DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + // method.setHeader("Authorization", authorization); + + httpResponse = client.execute(method); + + String responseContent = null; + if(httpResponse.getEntity() != null) { + responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); + } + + int statusCode = httpResponse.getStatusLine().getStatusCode(); + String statusMessage = httpResponse.getStatusLine().getReasonPhrase(); + + LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage + + (responseContent == null ? "" : System.lineSeparator() + responseContent)); + + if(httpResponse.getStatusLine().getStatusCode() >= 300) { + String errMsg = "VFC returned " + statusCode + " " + statusMessage; + logError(errMsg); + return createResponse(statusCode, errMsg); + } + + httpResponse = null; + + if(null != method) { + method.reset(); + } else { + LOGGER.debug("method is NULL:"); + } + + method = null; + + LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "VFC", ""); + return createResponse(statusCode, responseContent); + + } catch(SocketTimeoutException e) { + String errMsg = "Request to VFC timed out"; + logError(errMsg, e); + return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg); + + } catch(ConnectTimeoutException e) { + String errMsg = "Request to VFC timed out"; + logError(errMsg, e); + return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg); + + } catch(Exception e) { + String errMsg = "Error processing request to VFC"; + logError(errMsg, e); + return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg); + + } finally { + if(httpResponse != null) { + try { + EntityUtils.consume(httpResponse.getEntity()); + } catch(Exception e) { + LOGGER.debug("Exception :", e); + } + } + + if(method != null) { + try { + method.reset(); + } catch(Exception e) { + LOGGER.debug("Exception :", e); + } + } } - } } - body = stringBuilder.toString(); - return body; - } + private static void logError(String errMsg, Throwable t) { + LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); + } + + private static void logError(String errMsg) { + LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); + } + + private static RestfulResponse createResponse(int statusCode, String content) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(statusCode); + rsp.setResponseContent(content); + return rsp; + } + + /** + * @param request + * @return + */ + // public static String getRequestBody(HttpServletRequest request) { + // String body = null; + // StringBuilder stringBuilder = new StringBuilder(); + // BufferedReader bufferedReader = null; + // try { + // InputStream inputStream = request.getInputStream(); + // if (inputStream != null) { + // bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + // char[] charBuffer = new char[128]; + // int bytesRead = -1; + // while ((bytesRead = bufferedReader.read(charBuffer)) > 0) + // stringBuilder.append(charBuffer, 0, bytesRead); + // } + // } catch (IOException ex) { + // LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, + // "read inputStream buffer catch exception:", ex); + // } finally { + // if (bufferedReader != null) { + // try { + // bufferedReader.close(); + // } catch (IOException ex) { + // LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, + // "close buffer catch exception:", ex); + // } + // } + // } + // + // body = stringBuilder.toString(); + // return body; + // } } diff --git a/adapters/mso-vfc-adapter/src/test/java/org/openecomp/mso/adapters/vfc/VfcAdapterTest.java b/adapters/mso-vfc-adapter/src/test/java/org/openecomp/mso/adapters/vfc/VfcAdapterTest.java index 84991d77c8..95d3bf610f 100644 --- a/adapters/mso-vfc-adapter/src/test/java/org/openecomp/mso/adapters/vfc/VfcAdapterTest.java +++ b/adapters/mso-vfc-adapter/src/test/java/org/openecomp/mso/adapters/vfc/VfcAdapterTest.java @@ -24,8 +24,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; - import org.apache.commons.io.IOUtils; import org.junit.After; import org.junit.Assert; @@ -52,194 +50,191 @@ import mockit.MockUp; */ public class VfcAdapterTest { - private VfcAdapterRest vfcAdapter = new VfcAdapterRest(); - - /** - * File path - */ - private static final String FILE_PATH = "src/test/resources/json/"; - - /** - * Mock the request body form a file <br> - * - * @param fileName - * @since ONAP Amsterdam Release - */ - private void mockRestfulUtil(String fileName) { - new MockUp<RestfulUtil>() { - - /** - * mock get request body <br> - * - * @param request - * @return - * @since ONAP Amsterdam Release - */ - @Mock - public String getRequestBody(HttpServletRequest request) { + private VfcAdapterRest vfcAdapter = new VfcAdapterRest(); + + /** + * File path + */ + private static final String FILE_PATH = "src/test/resources/json/"; + + /** + * mock get request body <br> + * + * @param request + * @return + * @since ONAP Amsterdam Release + */ + public String getRequestBody(String fileName) { return getJsonString(fileName); - } - - /** - * mock get send method <br> - * - * @param url - * @param methodType - * @param content - * @return - * @since ONAP Amsterdam Release - */ - @Mock - public RestfulResponse send(String url, String methodType, String content) { - if (url.equals(CommonConstant.NFVO_CREATE_URL) - && methodType.equals(CommonConstant.MethodType.POST)) { - return getResponse("createNsRsp.json"); - } else if (url.contains("instantiate") - && methodType.equals(CommonConstant.MethodType.POST)) { - return getResponse("instantiateNsRsp.json"); - } else if (methodType.equals(CommonConstant.MethodType.DELETE)) { - return getResponse(null); - } else if (url.contains("terminate") && methodType.equals(CommonConstant.MethodType.POST)) { - return getResponse("terminateNsRsp.json"); - } else if (url.contains("/api/nslcm/v1/jobs") - && methodType.equals(CommonConstant.MethodType.GET)) { - return getResponse("queryJobRsp.json"); - } else { - return null; - } - } - }; - } - - /** - * Mock the request body form a file <br> - * - * @param fileName - * @since ONAP Amsterdam Release - */ - private void mockRequestDatabase() { - new MockUp<RequestsDatabase>() { - - /** - * mock get resource operation status <br> - * - * @param request - * @return - * @since ONAP Amsterdam Release - */ - @Mock - public ResourceOperationStatus getResourceOperationStatus(String serviceId, - String operationId, String resourceTemplateUUID) { - ResourceOperationStatus resStatus = new ResourceOperationStatus(); - resStatus.setServiceId("111"); - resStatus.setOperationId("111"); - return resStatus; - } - - /** - * Mock update Res Oper Status <br> - * - * @param operStatus - * @since ONAP Amsterdam Release - */ - @Mock - public void updateResOperStatus(ResourceOperationStatus operStatus) { - - } - }; - } - - /** - * Before executing UT, start mock requst database <br> - * - * @since ONAP Amsterdam Release - */ - @Before - public void start() { - mockRequestDatabase(); - } - - /** - * After executing UT, close session<br/> - * - * @since ONAP Amsterdam Release - */ - @After - public void stop() { - - } - - @Test - public void createTest() { - // get request - mockRestfulUtil(FILE_PATH + "createNsReq.json"); - vfcAdapter.createNfvoNs(null); - } - - @Test - public void deleteTest() { - // get request - mockRestfulUtil(FILE_PATH + "deleteNsReq.json"); - vfcAdapter.deleteNfvoNs(null, "9b9f02c0-298b-458a-bc9c-be3692e4f354"); - } - - @Test - public void instantiateTest() { - // get request - mockRestfulUtil(FILE_PATH + "instantiateNsReq.json"); - vfcAdapter.instantiateNfvoNs(null, "9b9f02c0-298b-458a-bc9c-be3692e4f354"); - } - - @Test - public void terminateTest() { - mockRestfulUtil(FILE_PATH + "terminateNsReq.json"); - vfcAdapter.terminateNfvoNs(null, "9b9f02c0-298b-458a-bc9c-be3692e4f354"); - } - - @Test - public void queryJobTest() { - mockRestfulUtil(FILE_PATH + "queryJobReq.json"); - vfcAdapter.queryNfvoJobStatus(null, "1"); - } - - /** - * Get json string from file.<br/> - * - * @param file the path of file - * @return json string - * @throws IOException when fail to read - * @since ONAP Amsterdam Release 2017-9-6 - */ - @SuppressWarnings("deprecation") - private String getJsonString(final String file) { - if (ValidateUtil.isStrEmpty(file)) { - return ""; } - String json = null; - try { - FileInputStream fileStream = new FileInputStream(new File(file)); - json = IOUtils.toString(fileStream); - } catch (Exception e) { - Assert.fail(e.getMessage()); + /** + * Mock the request body form a file <br> + * + * @param fileName + * @since ONAP Amsterdam Release + */ + private void mockRestfulUtil() { + new MockUp<RestfulUtil>() { + + /** + * mock get send method <br> + * + * @param url + * @param methodType + * @param content + * @return + * @since ONAP Amsterdam Release + */ + @Mock + public RestfulResponse send(String url, String methodType, String content) { + if(url.equals(CommonConstant.NFVO_CREATE_URL) && methodType.equals(CommonConstant.MethodType.POST)) { + return getResponse("createNsRsp.json"); + } else if(url.contains("instantiate") && methodType.equals(CommonConstant.MethodType.POST)) { + return getResponse("instantiateNsRsp.json"); + } else if(methodType.equals(CommonConstant.MethodType.DELETE)) { + return getResponse(null); + } else if(url.contains("terminate") && methodType.equals(CommonConstant.MethodType.POST)) { + return getResponse("terminateNsRsp.json"); + } else if(url.contains("/api/nslcm/v1/jobs") && methodType.equals(CommonConstant.MethodType.GET)) { + return getResponse("queryJobRsp.json"); + } else { + return null; + } + } + }; + } + + /** + * Mock the request body form a file <br> + * + * @param fileName + * @since ONAP Amsterdam Release + */ + private void mockRequestDatabase() { + new MockUp<RequestsDatabase>() { + + /** + * mock get resource operation status <br> + * + * @param request + * @return + * @since ONAP Amsterdam Release + */ + @Mock + public ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId, + String resourceTemplateUUID) { + ResourceOperationStatus resStatus = new ResourceOperationStatus(); + resStatus.setServiceId("111"); + resStatus.setOperationId("111"); + return resStatus; + } + + /** + * Mock update Res Oper Status <br> + * + * @param operStatus + * @since ONAP Amsterdam Release + */ + @Mock + public void updateResOperStatus(ResourceOperationStatus operStatus) { + + } + }; + } + + /** + * Before executing UT, start mock requst database <br> + * + * @since ONAP Amsterdam Release + */ + @Before + public void start() { + mockRequestDatabase(); + mockRestfulUtil(); + } + + /** + * After executing UT, close session<br/> + * + * @since ONAP Amsterdam Release + */ + @After + public void stop() { + + } + + @Test + public void createTest() { + // get request + String createReq = getRequestBody(FILE_PATH + "createNsReq.json"); + vfcAdapter.createNfvoNs(createReq); + } + + @Test + public void deleteTest() { + // get request + String req = getRequestBody(FILE_PATH + "deleteNsReq.json"); + vfcAdapter.deleteNfvoNs(req, "9b9f02c0-298b-458a-bc9c-be3692e4f354"); } - return json; - } - - /** - * get the response from file <br> - * - * @param fileName - * @return - * @since ONAP Amsterdam Release - */ - private RestfulResponse getResponse(String fileName) { - RestfulResponse responseSuccess = new RestfulResponse(); - responseSuccess.setStatus(HttpCode.RESPOND_OK); - if (null != fileName) { - String jsonStr = getJsonString(FILE_PATH + fileName); - responseSuccess.setResponseContent(jsonStr); + + @Test + public void instantiateTest() { + // get request + String req = getRequestBody(FILE_PATH + "instantiateNsReq.json"); + vfcAdapter.instantiateNfvoNs(req, "9b9f02c0-298b-458a-bc9c-be3692e4f354"); + } + + @Test + public void terminateTest() { + String req = getRequestBody(FILE_PATH + "terminateNsReq.json"); + vfcAdapter.deleteNfvoNs(req, "9b9f02c0-298b-458a-bc9c-be3692e4f354"); + } + + @Test + public void queryJobTest() { + String req = getRequestBody(FILE_PATH + "queryJobReq.json"); + vfcAdapter.queryNfvoJobStatus(req, "1"); + } + + /** + * Get json string from file.<br/> + * + * @param file the path of file + * @return json string + * @throws IOException when fail to read + * @since ONAP Amsterdam Release 2017-9-6 + */ + @SuppressWarnings("deprecation") + private String getJsonString(final String file) { + if(ValidateUtil.isStrEmpty(file)) { + return ""; + } + + String json = null; + try { + FileInputStream fileStream = new FileInputStream(new File(file)); + json = IOUtils.toString(fileStream); + } catch(Exception e) { + Assert.fail(e.getMessage()); + } + return json; + } + + /** + * get the response from file <br> + * + * @param fileName + * @return + * @since ONAP Amsterdam Release + */ + private RestfulResponse getResponse(String fileName) { + RestfulResponse responseSuccess = new RestfulResponse(); + responseSuccess.setStatus(HttpCode.RESPOND_OK); + if(null != fileName) { + String jsonStr = getJsonString(FILE_PATH + fileName); + responseSuccess.setResponseContent(jsonStr); + } + return responseSuccess; } - return responseSuccess; - } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy index cd5ae79bd3..94b423669d 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy @@ -283,7 +283,7 @@ class MsoUtils { def log(logmode,logtxt,isDebugLogEnabled="false"){
MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
if ("INFO"==logmode) {
- msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt);
+ msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt, "BPMN", MsoLogger.getServiceName());
} else if ("WARN"==logmode) {
// to see the warning text displayed in the log entry, the text must also be passed as arg0 (2nd argument) to invoke the correct MsoLogger warn() method
msoLogger.warn (MessageEnum.BPMN_GENERAL_WARNING, logtxt, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java index b1d1085b43..c0be8992ef 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java @@ -25,9 +25,9 @@ import java.util.HashMap; import java.util.List;
import java.util.Map;
-import org.camunda.bpm.BpmPlatform;
import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
import org.camunda.bpm.engine.ProcessEngineServices;
+import org.camunda.bpm.engine.ProcessEngines;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.MessageCorrelationResult;
@@ -371,7 +371,7 @@ public abstract class AbstractCallbackService { protected ProcessEngineServices getProcessEngineServices() {
if (pes4junit == null) {
- return BpmPlatform.getDefaultProcessEngine();
+ return ProcessEngines.getProcessEngine("infrastructure");
} else {
return pes4junit;
}
@@ -380,4 +380,4 @@ public abstract class AbstractCallbackService { public void setProcessEngineServices4junit(ProcessEngineServices pes) {
pes4junit = pes;
}
-}
\ No newline at end of file +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java index 249283923a..4534b56efc 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java @@ -27,6 +27,6 @@ import org.camunda.bpm.engine.ProcessEngines; public class WorkflowAsyncCommonResource extends WorkflowAsyncResource {
protected ProcessEngineServices getProcessEngineServices() {
- return pes4junit.orElse(ProcessEngines.getProcessEngine("common"));
+ return pes4junit.orElse(ProcessEngines.getProcessEngine("infrastructure"));
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java index 7a537218b3..0521fb4df3 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java @@ -618,7 +618,7 @@ public class WorkflowResource { private ProcessEngineServices getProcessEngineServices() {
if (pes4junit == null) {
- return ProcessEngines.getDefaultProcessEngine();
+ return ProcessEngines.getProcessEngine("infrastructure");
} else {
return pes4junit;
}
diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn index 2629ea7437..9bfd4535ea 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn @@ -50,7 +50,7 @@ completeMsoProcess.setUpdateDBstatustoSuccessPayload(execution)]]></bpmn2:script <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="payload"><![CDATA[${execution.getVariable("CMSO_setUpdateDBstatustoSuccessPayload")}]]></camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn index 4ac34f9210..4f27e0026a 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn @@ -133,7 +133,7 @@ falloutHandler.buildDBWorkflowException(execution, "FH_updateRequestInfraRespons <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="method">POST</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java index 7c9247addb..8281687dec 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java @@ -40,6 +40,11 @@ import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; */
public class FalloutHandlerTest extends WorkflowTest {
private void setupMocks() {
+ stubFor(post(urlEqualTo("/dbadapters/MsoRequestsDbAdapter"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBody("<DbTag>Notified</DbTag>")));
stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter"))
.willReturn(aResponse()
.withStatus(200)
diff --git a/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties b/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties index ba45f545c8..5520d187be 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties +++ b/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties @@ -13,8 +13,8 @@ mso.healthcheck.log.debug=false mso.adapters.completemsoprocess.endpoint=http://localhost:28090/CompleteMsoProcess
-mso.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter
-mso.openecomp.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter
+mso.adapters.db.endpoint=http://localhost:28090/dbadapters/MsoRequestsDbAdapter
+mso.adapters.openecomp.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter
mso.adapters.db.auth=757A94191D685FD2092AC1490730A4FC
mso.adapters.network.endpoint=http://localhost:28090/networks/NetworkAdapter
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java index 75858b14ec..204d9e4e5e 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java @@ -54,7 +54,7 @@ public class HealthCheckHandler { private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); private static final String SITENAME = "mso.sitename"; - private static final String ADAPTER_ENDPOINT = "mso.adapters.db.endpoint"; + private static final String ADAPTER_ENDPOINT = "mso.adapters.openecomp.db.endpoint"; private static final String ADAPTER_NAMESPACE = "mso.adapters.namespace"; private static final String CONFIG = "mso.bpmn.urn.properties"; private static final String CREDENTIAL = "mso.adapters.db.auth"; diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy index 73066b3722..abd693660d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy @@ -140,7 +140,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor utils.log("DEBUG", "User Input Parameters map: " + userParams.toString(), isDebugEnabled) execution.setVariable("serviceInputParams", inputMap) - + execution.setVariable("URN_mso_openecomp_adapters_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") //TODO //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams")) //execution.setVariable("failExists", true) @@ -304,7 +304,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor execution.setVariable("operationId", operationId) execution.setVariable("operationType", operationType) - def dbAdapterEndpoint = execution.getVariable("URN_mso_openecomp_adapters_db_endpoint") + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) @@ -317,7 +317,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor <serviceId>${serviceId}</serviceId> <operationId>${operationId}</operationId> <operationType>${operationType}</operationType> - <userId>${userId}</responseBody> + <userId>${userId}</userId> <result>${result}</result> <operationContent>${operationContent}</operationContent> <progress>${progress}</progress> @@ -338,4 +338,4 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor utils.log("DEBUG", "======== COMPLETED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled) } -}
\ No newline at end of file +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy index 9416e6851a..80d714893d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy @@ -37,6 +37,7 @@ import org.camunda.bpm.engine.runtime.Execution import org.apache.commons.lang3.* import org.apache.commons.codec.binary.Base64; import org.springframework.web.util.UriUtils +import org.json.JSONException; /** * This groovy class supports the <class>CreateGenericALaCarteServiceInstance.bpmn</class> process. @@ -85,7 +86,12 @@ public class CreateGenericALaCarteServiceInstance extends AbstractServiceTaskPro execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")) execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")) execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback")) - String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + String productFamilyId = null; + try { + productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + } catch (JSONException e) { + productFamilyId = null; + } if (isBlank(productFamilyId)) { msg = "Input productFamilyId is null" diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy index 99c37fb142..37ff4944ff 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy @@ -408,7 +408,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { // vfModuleName may be generated by DoCreateVfModule subprocess if it is not specified on the input def vfModuleName = execution.getVariable("CVFMI_vfModuleName") - def dbAdapterEndpoint = execution.getVariable("URN_mso_openecomp_adapters_db_endpoint") + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy index a2be3035a6..a8506fdc94 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -636,7 +636,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { } } - def dbAdapterEndpoint = execution.getVariable("URN_mso_openecomp_adapters_db_endpoint") + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy index 0eb16a2d9e..18925d399e 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -257,6 +257,8 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { } String statusLine = isBlank(oStatus) ? "" : "<orchestration-status>${oStatus}</orchestration-status>" + String serviceTypeLine = isBlank(serviceType) ? "" : "<service-type>${serviceType}</service-type>" + String serviceRoleLine = isBlank(serviceRole) ? "" : "<service-role>${serviceRole}</service-role>" AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) @@ -264,8 +266,8 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { String serviceInstanceData = """<service-instance xmlns=\"${namespace}\"> <service-instance-name>${serviceInstanceName}</service-instance-name> - <service-type>${serviceType}</service-type> - <service-role>${serviceRole}</service-role> + ${serviceTypeLine} + ${serviceRoleLine} ${statusLine} <model-invariant-id>${modelInvariantUuid}</model-invariant-id> <model-version-id>${modelUuid}</model-version-id> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy index b7aaef097a..8ab8d61019 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy @@ -523,7 +523,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } } - def dbAdapterEndpoint = execution.getVariable("URN_mso_openecomp_adapters_db_endpoint") + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn index 04b47b452a..4b26e6b544 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn @@ -152,11 +152,11 @@ csi.prepareInitServiceOperationStatus(execution)]]></bpmn:script> <bpmn:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> <camunda:entry key="content-type">application/soap+xml</camunda:entry> - <camunda:entry key="Authorization">#{BasicAuthHeaderValueDB}</camunda:entry> + <camunda:entry key="Authorization">Basic QlBFTENsaWVudDpwYXNzd29yZDEk</camunda:entry> </camunda:map> </camunda:inputParameter> <camunda:inputParameter name="payload">${CVFMI_updateServiceOperStatusRequest}</camunda:inputParameter> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn index 24a9a6d73c..0316e26d9a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn @@ -116,7 +116,7 @@ CreateNetworkInstance.prepareDBRequestError(execution)]]></bpmn2:script> <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="payload">${CRENI_createDBRequest}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn index 72c275380f..84ab4177e2 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn @@ -70,7 +70,7 @@ createVfModule.prepareUpdateInfraRequest(execution)]]></bpmn2:script> <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> <camunda:entry key="content-type">application/soap+xml</camunda:entry> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn index ec4afa4ea4..111b6c7032 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn @@ -200,7 +200,7 @@ createVfModuleVolumeInfraV1.executeMethod('postProcessResponse', execution, isDe <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="payload">${CVMVINFRAV1_createDBRequest}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn index 079599d7ca..3b5c629182 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn @@ -116,7 +116,7 @@ DeleteNetworkInstance.prepareDBRequestError(execution)]]></bpmn2:script> <bpmn2:extensionElements>
<camunda:connector>
<camunda:inputOutput>
- <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter>
+ <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter>
<camunda:inputParameter name="payload">${DELNI_deleteDBRequest}</camunda:inputParameter>
<camunda:inputParameter name="headers">
<camunda:map>
diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn index a687d5df87..e19ea1bd86 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn @@ -79,7 +79,7 @@ dvfm.completionHandlerPrep(execution, 'DELVfModI_CompletionHandlerRequest') <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="method">POST</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn index 21f74a2a29..c7092ffb30 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn @@ -198,7 +198,7 @@ execution.setVariable("DELVfModVol_TransactionSuccessIndicator", true)]]></bpmn2 <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="payload">${DELVfModVol_updateInfraRequest}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn index 7e54b805e1..a9d81d05bc 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn @@ -116,7 +116,7 @@ UpdateNetworkInstance.prepareDBRequestError(execution)]]></bpmn2:script> <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="payload">${UPDNI_createDBRequest}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn index 15b5bc7fcf..7e5f41ba26 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn @@ -21,7 +21,7 @@ <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="payload">${UPDVfModVol_updateInfraRequest}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn index 109cf69b92..43c8aee766 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn @@ -188,11 +188,11 @@ ddsi.preInitResourcesOperStatus(execution)]]></bpmn2:script> <bpmn2:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> <camunda:entry key="content-type">application/soap+xml</camunda:entry> - <camunda:entry key="Authorization">#{BasicAuthHeaderValueDB}</camunda:entry> + <camunda:entry key="Authorization">Basic QlBFTENsaWVudDpwYXNzd29yZDEk</camunda:entry> </camunda:map> </camunda:inputParameter> <camunda:inputParameter name="payload">${CVFMI_initResOperStatusRequest}</camunda:inputParameter> diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCustomDeleteE2EServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCustomDeleteE2EServiceInstance.bpmn index 91f5404c9b..581ab3a47d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCustomDeleteE2EServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCustomDeleteE2EServiceInstance.bpmn @@ -166,7 +166,7 @@ ddsi.preInitResourcesOperStatus(execution)]]></bpmn:script> <bpmn:extensionElements> <camunda:connector> <camunda:inputOutput> - <camunda:inputParameter name="url">${URN_mso_openecomp_adapters_db_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="url">${URN_mso_adapters_openecomp_db_endpoint}</camunda:inputParameter> <camunda:inputParameter name="headers"> <camunda:map> <camunda:entry key="content-type">application/soap+xml</camunda:entry> diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java index 80ec724630..e89c64e6df 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java @@ -89,7 +89,7 @@ public class DeleteVfModuleInfraTest extends WorkflowTest { "</vfModuleException>" + EOL;
private final String sdncAdapterDeleteCallback =
- "<output xmlns=\"org:openecomp:sdnctl:l3api\">" + EOL +
+ "<output xmlns=\"org:onap:sdnctl:l3api\">" + EOL +
" <svc-request-id>{{REQUEST-ID}}</svc-request-id>" + EOL +
" <ack-final-indicator>Y</ack-final-indicator>" + EOL +
"</output>" + EOL;
@@ -576,4 +576,4 @@ public class DeleteVfModuleInfraTest extends WorkflowTest { }
-}
\ No newline at end of file +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java index 18a5e079c8..1d0cb0cd10 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java @@ -67,7 +67,7 @@ public class DoCreateVfModuleRollbackTest extends WorkflowTest { "</vfModuleException>" + EOL;
private final String sdncAdapterDeleteCallback =
- "<output xmlns=\"org:openecomp:sdnctl:l3api\">" + EOL +
+ "<output xmlns=\"org:onap:sdnctl:l3api\">" + EOL +
" <svc-request-id>{{REQUEST-ID}}</svc-request-id>" + EOL +
" <ack-final-indicator>Y</ack-final-indicator>" + EOL +
"</output>" + EOL;
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java index 488c5329b8..c741dfd2ed 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java @@ -70,7 +70,7 @@ public class DoDeleteVfModuleTest extends WorkflowTest { "</vfModuleException>" + EOL;
private final String sdncAdapterDeleteCallback =
- "<output xmlns=\"org:openecomp:sdnctl:l3api\">" + EOL +
+ "<output xmlns=\"org:onap:sdnctl:l3api\">" + EOL +
" <svc-request-id>{{REQUEST-ID}}</svc-request-id>" + EOL +
" <ack-final-indicator>Y</ack-final-indicator>" + EOL +
"</output>" + EOL;
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml index 4b3ac855df..5e0b8c6c54 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml @@ -1,7 +1,7 @@ <sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1">
<sdncadapterworkflow:response-data>
<tag0:RequestData xmlns:tag0="http://org.openecomp/workflow/sdnc/adapter/schema/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">
- <output xmlns="org:openecomp:sdnctl:vnf"><svc-request-id>1660b8da-0a94-442d-8ed5-ea079e3c67c8</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><vnf-information><vnf-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</vnf-id></vnf-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output>
+ <output xmlns="org:onap:sdnctl:vnf"><svc-request-id>1660b8da-0a94-442d-8ed5-ea079e3c67c8</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><vnf-information><vnf-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</vnf-id></vnf-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output>
</tag0:RequestData>
</sdncadapterworkflow:response-data>
-</sdncadapterworkflow:SDNCAdapterWorkflowResponse>
\ No newline at end of file +</sdncadapterworkflow:SDNCAdapterWorkflowResponse> diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryBRGCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryBRGCallback.xml index 410ba05e5f..d81b7e8f50 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryBRGCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryBRGCallback.xml @@ -1,5 +1,5 @@ -<output xmlns="org:openecomp:sdnctl:vnf">
-<brg-topology xmlns="org:openecomp:sdnctl:vnf">
+<output xmlns="org:onap:sdnctl:vnf">
+<brg-topology xmlns="org:onap:sdnctl:vnf">
<ecomp-model-information>
<model-invariant-uuid>36e20198-c67a-464b-96d0-aaa99eb2639e</model-invariant-uuid>
<model-uuid>5b9b15d0-5dd7-47dc-95b9-0440c340a3ba</model-uuid>
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryTXCCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryTXCCallback.xml index ac85be4e97..f770ec6aff 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryTXCCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryTXCCallback.xml @@ -1,5 +1,5 @@ -<output xmlns="org:openecomp:sdnctl:vnf">
-<tunnelxconn-topology xmlns="org:openecomp:sdnctl:vnf">
+<output xmlns="org:onap:sdnctl:vnf">
+<tunnelxconn-topology xmlns="org:onap:sdnctl:vnf">
<ecomp-model-information>
<model-invariant-uuid>36e20198-c67a-464b-96d0-aaa99eb2639e</model-invariant-uuid>
<model-uuid>5b9b15d0-5dd7-47dc-95b9-0440c340a3ba</model-uuid>
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml index 410ba05e5f..d81b7e8f50 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml @@ -1,5 +1,5 @@ -<output xmlns="org:openecomp:sdnctl:vnf">
-<brg-topology xmlns="org:openecomp:sdnctl:vnf">
+<output xmlns="org:onap:sdnctl:vnf">
+<brg-topology xmlns="org:onap:sdnctl:vnf">
<ecomp-model-information>
<model-invariant-uuid>36e20198-c67a-464b-96d0-aaa99eb2639e</model-invariant-uuid>
<model-uuid>5b9b15d0-5dd7-47dc-95b9-0440c340a3ba</model-uuid>
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml index ac85be4e97..f770ec6aff 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml @@ -1,5 +1,5 @@ -<output xmlns="org:openecomp:sdnctl:vnf">
-<tunnelxconn-topology xmlns="org:openecomp:sdnctl:vnf">
+<output xmlns="org:onap:sdnctl:vnf">
+<tunnelxconn-topology xmlns="org:onap:sdnctl:vnf">
<ecomp-model-information>
<model-invariant-uuid>36e20198-c67a-464b-96d0-aaa99eb2639e</model-invariant-uuid>
<model-uuid>5b9b15d0-5dd7-47dc-95b9-0440c340a3ba</model-uuid>
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyCreateCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyCreateCallback.xml index 11022f6aec..b579f232b1 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyCreateCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyCreateCallback.xml @@ -1,4 +1,4 @@ - <output xmlns="org:openecomp:sdnctl:vnf">
+ <output xmlns="org:onap:sdnctl:vnf">
<vnf-information>
<vnf-id>skask</vnf-id>
</vnf-information>
@@ -13,4 +13,4 @@ <instance-reference>
<object-path>restconf/SDNCObjectPath</object-path>
</instance-reference>
- </output>
\ No newline at end of file + </output> diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallback.xml index acea1459bc..3cf0c81c72 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallback.xml @@ -1,4 +1,4 @@ -<output xmlns="org:openecomp:sdnctl:vnf">
+<output xmlns="org:onap:sdnctl:vnf">
<vnf-information>
<vnf-id>skask</vnf-id>
</vnf-information>
@@ -10,4 +10,4 @@ <service-instance-id>0</service-instance-id>
<service-type>SDN-MOBILITY</service-type>
</service-information>
-</output>
\ No newline at end of file +</output> diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml index bf2b3c0882..df5004edf5 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml @@ -1,4 +1,4 @@ -<output xmlns="org:openecomp:sdnctl:vnf">
+<output xmlns="org:onap:sdnctl:vnf">
<vnf-information>
<vnf-id>skask</vnf-id>
</vnf-information>
diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeleteCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeleteCallback.xml index 11022f6aec..b579f232b1 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeleteCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyDeleteCallback.xml @@ -1,4 +1,4 @@ - <output xmlns="org:openecomp:sdnctl:vnf">
+ <output xmlns="org:onap:sdnctl:vnf">
<vnf-information>
<vnf-id>skask</vnf-id>
</vnf-information>
@@ -13,4 +13,4 @@ <instance-reference>
<object-path>restconf/SDNCObjectPath</object-path>
</instance-reference>
- </output>
\ No newline at end of file + </output> diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyUnassignCallback.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyUnassignCallback.xml index 11022f6aec..b579f232b1 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyUnassignCallback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/SDNCTopologyUnassignCallback.xml @@ -1,4 +1,4 @@ - <output xmlns="org:openecomp:sdnctl:vnf">
+ <output xmlns="org:onap:sdnctl:vnf">
<vnf-information>
<vnf-id>skask</vnf-id>
</vnf-information>
@@ -13,4 +13,4 @@ <instance-reference>
<object-path>restconf/SDNCObjectPath</object-path>
</instance-reference>
- </output>
\ No newline at end of file + </output> diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties b/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties index 8a557c433a..aad79b00f0 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties @@ -14,7 +14,7 @@ mso.healthcheck.log.debug=false mso.adapters.completemsoprocess.endpoint=http://localhost:28090/CompleteMsoProcess
mso.workflow.message.endpoint=http://localhost:8080/mso/WorkflowMessage
mso.adapters.db.endpoint=http://localhost:28090/dbadapters/MsoRequestsDbAdapter
-mso.openecomp.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter
+mso.adapters.openecomp.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter
mso.adapters.db.auth=757A94191D685FD2092AC1490730A4FC
mso.adapters.network.endpoint=http://localhost:28090/networks/NetworkAdapter
diff --git a/bpmn/MSOMockServer/.gitignore b/bpmn/MSOMockServer/.gitignore new file mode 100644 index 0000000000..f6c8fbcdef --- /dev/null +++ b/bpmn/MSOMockServer/.gitignore @@ -0,0 +1,4 @@ +/bin +/target +/target +/target diff --git a/bpmn/MSOMockServer/WebContent/META-INF/MANIFEST.MF b/bpmn/MSOMockServer/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/bpmn/MSOMockServer/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/bpmn/MSOMockServer/WebContent/WEB-INF/web.xml b/bpmn/MSOMockServer/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000000..1aa8cdb8d7 --- /dev/null +++ b/bpmn/MSOMockServer/WebContent/WEB-INF/web.xml @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="UTF-8"?> +<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> +</web-app>
\ No newline at end of file diff --git a/bpmn/MSOMockServer/pom.xml b/bpmn/MSOMockServer/pom.xml new file mode 100644 index 0000000000..500535d740 --- /dev/null +++ b/bpmn/MSOMockServer/pom.xml @@ -0,0 +1,100 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <groupId>org.openecomp.so</groupId> + <artifactId>bpmn</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <groupId>org.openecomp.so</groupId> + <artifactId>MSOMockServer</artifactId> + <packaging>war</packaging> + + <build> + <plugins> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-war-plugin</artifactId> + <version>2.4</version> + <configuration> + <attachClasses>true</attachClasses> + <archiveClasses>true</archiveClasses> + <failOnMissingWebXml>false</failOnMissingWebXml> + </configuration> + </plugin> + </plugins> + </build> + <dependencies> + + <dependency> + <groupId>com.github.tomakehurst</groupId> + <artifactId>wiremock</artifactId> + <version>1.56</version> + <classifier>standalone</classifier> + <exclusions> + <exclusion> + <groupId>org.mortbay.jetty</groupId> + <artifactId>jetty</artifactId> + </exclusion> + <exclusion> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </exclusion> + <exclusion> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-core</artifactId> + </exclusion> + <exclusion> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-annotations</artifactId> + </exclusion> + <exclusion> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + </exclusion> + <exclusion> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </exclusion> + <exclusion> + <groupId>org.skyscreamer</groupId> + <artifactId>jsonassert</artifactId> + </exclusion> + <exclusion> + <groupId>xmlunit</groupId> + <artifactId>xmlunit</artifactId> + </exclusion> + <exclusion> + <groupId>com.jayway.jsonpath</groupId> + <artifactId>json-path</artifactId> + </exclusion> + <exclusion> + <groupId>net.sf.jopt-simple</groupId> + <artifactId>jopt-simple</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.openecomp.so</groupId> + <artifactId>common</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>javax.ws.rs</groupId> + <artifactId>javax.ws.rs-api</artifactId> + <version>2.0</version> + </dependency> + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-client</artifactId> + <version>3.0.8.Final</version> + <exclusions> + <exclusion> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </exclusion> + </exclusions> + </dependency> + </dependencies> +</project>
\ No newline at end of file diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/FileUtil.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/FileUtil.java new file mode 100644 index 0000000000..2ebb44a644 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/FileUtil.java @@ -0,0 +1,80 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import java.io.IOException; +import java.io.InputStream; +import org.openecomp.mso.logger.MsoLogger; + +/** + * + * File utility class.<br/> + * <p> + * </p> + * + * @author + * @version ONAP Sep 15, 2017 + */ +public class FileUtil { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); + + private FileUtil() { + /** + * Constructor. + */ + } + /** + * Read the specified resource file and return the contents as a String. + * + * @param fileName Name of the resource file + * @return the contents of the resource file as a String + * @throws IOException if there is a problem reading the file + */ + public static String readResourceFile(String fileName) { + InputStream stream; + try { + stream = getResourceAsStream(fileName); + byte[] bytes; + bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + return new String(bytes); + } catch (IOException e) { + LOGGER.debug("Exception:", e); + return ""; + } + } + + /** + * Get an InputStream for the resource specified. + * + * @param resourceName Name of resource for which to get InputStream. + * @return an InputStream for the resource specified. + * @throws IOException If we can't get the InputStream for whatever reason. + */ + private static InputStream getResourceAsStream(String resourceName) throws IOException { + InputStream stream = + FileUtil.class.getClassLoader().getResourceAsStream(resourceName); + if (stream == null) { + throw new IOException("Can't access resource '" + resourceName + "'"); + } + return stream; + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/MockResource.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/MockResource.java new file mode 100644 index 0000000000..fc97e69c5c --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/MockResource.java @@ -0,0 +1,205 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; + +/** + * + * Mock Resource which is used to start, stop the WireMock Server + * Also up to 50 mock properties can be added at run-time to change the properties used in transformers such as sdnc_delay in SDNCAdapterMockTransformer + * You can also selectively setup a stub (use reset before setting up), reset all stubs + */ +@Path("/server") +public class MockResource { + + private boolean started = false; + private final Integer defaultPort = 28090; + private WireMockServer wireMockServer = null; + private static Map<String,String> mockProperties = new HashMap<String,String>(); + + public static String getMockProperties(String key) { + return mockProperties.get(key); + } + + private synchronized void initMockServer(int portNumber) { + String path = FileUtil.class.getClassLoader().getResource("__files/sdncSimResponse.xml").getFile(); + path = path.substring(0,path.indexOf("__files/")); + + wireMockServer = new WireMockServer(wireMockConfig().port(portNumber).extensions("org.openecomp.mso.bpmn.mock.SDNCAdapterMockTransformer") + .extensions("org.openecomp.mso.bpmn.mock.SDNCAdapterNetworkTopologyMockTransformer") + .extensions("org.openecomp.mso.bpmn.mock.VnfAdapterCreateMockTransformer") + .extensions("org.openecomp.mso.bpmn.mock.VnfAdapterDeleteMockTransformer") + .extensions("org.openecomp.mso.bpmn.mock.VnfAdapterUpdateMockTransformer") + .extensions("org.openecomp.mso.bpmn.mock.VnfAdapterRollbackMockTransformer") + .extensions("org.openecomp.mso.bpmn.mock.VnfAdapterQueryMockTransformer")); + //.withRootDirectory(path)); + //Mocks were failing - commenting out for now, both mock and transformers seem to work fine + WireMock.configureFor("localhost", portNumber); + wireMockServer.start(); +// StubResponse.setupAllMocks(); + started= true; + } + + public static void main(String [] args) { + MockResource mockresource = new MockResource(); + mockresource.start(28090); + mockresource.reset(); +// mockresource.setupStub("MockCreateTenant"); + } + + /** + * Starts the wiremock server in default port + * @return + */ + @GET + @Path("/start") + @Produces("application/json") + public Response start() { + return startMockServer(defaultPort); + } + + private Response startMockServer(int port) { + if (!started) { + initMockServer(defaultPort); + System.out.println("Started Mock Server in port " + port); + return Response.status(200).entity("Started Mock Server in port " + port).build(); + } else { + return Response.status(200).entity("Mock Server is already running").build(); + } + } + + /** + * Starts the wiremock server in a different port + * @param portNumber + * @return + */ + @GET + @Path("/start/{portNumber}") + @Produces("application/json") + public Response start(@PathParam("portNumber") Integer portNumber) { + if (portNumber == null) portNumber = defaultPort; + return startMockServer(portNumber.intValue()); + } + + + /** + * Stop the wiremock server + * @return + */ + @GET + @Path("/stop") + @Produces("application/json") + public synchronized Response stop() { + if (wireMockServer.isRunning()) { + wireMockServer.stop(); + started = false; + return Response.status(200).entity("Stopped Mock Server in port ").build(); + } + return Response.status(200).entity("Mock Server is not running").build(); + } + + + /** + * Return list of mock properties + * @return + */ + @GET + @Path("/properties") + @Produces("application/json") + public Response getProperties() { + return Response.status(200).entity(mockProperties).build(); + } + + /** + * Update a particular mock property at run-time + * @param name + * @param value + * @return + */ + @POST + @Path("/properties/{name}/{value}") + public Response updateProperties(@PathParam("name") String name, @PathParam("value") String value) { + if (mockProperties.size() > 50) return Response.serverError().build(); + mockProperties.put(name, value); + return Response.status(200).build(); + } + + /** + * Reset all stubs + * @return + */ + @GET + @Path("/reset") + @Produces("application/json") + public Response reset() { + WireMock.reset(); + return Response.status(200).entity("Wiremock stubs are reset").build(); + } + + + /** + * Setup a stub selectively + * Prior to use, make sure that stub method is available in StubResponse class + * @param methodName + * @return + */ + + // commenting for now until we figure out a way to use new StubResponse classes to setupStubs +// @GET +// @Path("/stub/{methodName}") +// @Produces("application/json") +// public Response setupStub(@PathParam("methodName") String methodName) { +// +// @SuppressWarnings("rawtypes") +// Class params[] = {}; +// Object paramsObj[] = {}; +// +// try { +// Method thisMethod = StubResponse.class.getDeclaredMethod(methodName, params); +// try { +// thisMethod.invoke(StubResponse.class, paramsObj); +// } catch (IllegalAccessException | IllegalArgumentException +// | InvocationTargetException e) { +// return Response.status(200).entity("Error invoking " + methodName ).build(); +// } +// } catch (NoSuchMethodException | SecurityException e) { +// return Response.status(200).entity("Stub " + methodName + " not found...").build(); +// } +// return Response.status(200).entity("Successfully invoked " + methodName).build(); +// } + + + public static Map<String,String> getMockProperties(){ + return mockProperties; + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/MockResourceApplication.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/MockResourceApplication.java new file mode 100644 index 0000000000..ebbfea5cd1 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/MockResourceApplication.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +/** + * + * JAX RS Application wiring for Mock Resource + */ +@ApplicationPath("/console") +public class MockResourceApplication extends Application { + + private Set<Object> singletons = new HashSet<Object>(); + private Set<Class<?>> classes = new HashSet<Class<?>>(); + + public MockResourceApplication() { + singletons.add(new MockResource()); + } + + @Override + public Set<Class<?>> getClasses() { + return classes; + } + + @Override + public Set<Object> getSingletons() { + return singletons; + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/SDNCAdapterMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/SDNCAdapterMockTransformer.java new file mode 100644 index 0000000000..9c4e7936b1 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/SDNCAdapterMockTransformer.java @@ -0,0 +1,140 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; +import org.openecomp.mso.logger.MsoLogger; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; + +import org.openecomp.mso.logger.MsoLogger; +/** + * + * Simulates SDNC Adapter Callback response + * + */ +public class SDNCAdapterMockTransformer extends ResponseTransformer { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private String callbackResponse; + private String requestId; + + public SDNCAdapterMockTransformer() { + callbackResponse = FileUtil.readResourceFile("__files/sdncSimResponse.xml"); + } + + public SDNCAdapterMockTransformer(String requestId) { + this.requestId = requestId; + } + + public String name() { + return "sdnc-adapter-transformer"; + } + + /** + * Grab the incoming request xml,extract the request id and replace the stub response with the incoming request id + * so that callback response can be correlated + * + * Mock Resource can be used to add dynamic properties. If sdnc_delay is not in the list by default waits for 300ms before + * the callback response is sent + */ + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, + FileSource fileSource) { + String requestBody = request.getBodyAsString(); + + String callbackUrl = requestBody.substring(requestBody.indexOf("<sdncadapter:CallbackUrl>")+25, requestBody.indexOf("</sdncadapter:CallbackUrl>")); + String requestId = requestBody.substring(requestBody.indexOf("<sdncadapter:RequestId>")+23, requestBody.indexOf("</sdncadapter:RequestId>")); + + callbackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + System.out.println("callbackResponse:" + callbackResponse); + + if (this.requestId != null) { + callbackResponse = callbackResponse.replace(this.requestId, requestId); + } else { + callbackResponse = callbackResponse.replace("testRequestId", requestId); + } + + + Object sdncDelay = MockResource.getMockProperties().get("sdnc_delay"); + int delay = 300; + if (sdncDelay != null) { + delay = Integer.parseInt(sdncDelay.toString()); + } + + //Kick off callback thread + System.out.println("callback Url:" + callbackUrl + ":delay:" + delay); + CallbackResponseThread calbackResponseThread = new CallbackResponseThread(callbackUrl,callbackResponse, delay); + calbackResponseThread.start(); + + //return 200 OK with empty body + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody("").withHeader("Content-Type", "text/xml") + .build(); + } + + @Override + public boolean applyGlobally() { + return false; + } + + /** + * + * Callback response thread which sends the callback response asynchronously + * + */ + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + LOGGER.debug("Exception :",e1); + } + LOGGER.debug("Sending callback response:" + callbackUrl); + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + System.err.println(payLoad); + try { + ClientResponse result = request.post(); + //System.err.println("Successfully posted callback:" + result.getStatus()); + } catch (Exception e) { + LOGGER.debug("Exception :",e); + } + } + + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/SDNCAdapterNetworkTopologyMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/SDNCAdapterNetworkTopologyMockTransformer.java new file mode 100644 index 0000000000..e59e3b67d2 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/SDNCAdapterNetworkTopologyMockTransformer.java @@ -0,0 +1,132 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; + +import org.openecomp.mso.logger.MsoLogger; + +public class SDNCAdapterNetworkTopologyMockTransformer extends ResponseTransformer { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private String callbackResponse; + private String requestId; + + public SDNCAdapterNetworkTopologyMockTransformer() { + callbackResponse = ""; // FileUtil.readResourceFile("__files/sdncDeleteNetworkTopologySimResponse.xml"); + } + + public SDNCAdapterNetworkTopologyMockTransformer(String requestId) { + this.requestId = requestId; + } + + public String name() { + return "network-topology-operation-transformer"; + } + + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource fileSource) { + String requestBody = request.getBodyAsString(); + + String callbackUrl = requestBody.substring(requestBody.indexOf("<sdncadapter:CallbackUrl>")+25, requestBody.indexOf("</sdncadapter:CallbackUrl>")); + String requestId = requestBody.substring(requestBody.indexOf("<sdncadapter:RequestId>")+23, requestBody.indexOf("</sdncadapter:RequestId>")); + System.out.println("request callbackUrl : " + callbackUrl); + System.out.println("request requestId : " + requestId); + + System.out.println("file path/name : " + responseDefinition.getBodyFileName()); + callbackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + // extract Response responseRequestId + String responseRequestId = callbackResponse.substring(callbackResponse.indexOf("<RequestId>")+11, callbackResponse.indexOf("</RequestId>")); + System.out.println("response requestId: " + responseRequestId); + System.out.println("callbackResponse (before): " + callbackResponse); + callbackResponse = callbackResponse.replace(responseRequestId, requestId); + if (this.requestId != null) { + callbackResponse = callbackResponse.replace(this.requestId, requestId); + } else { + callbackResponse = callbackResponse.replace(responseRequestId, requestId); + } + System.out.println("callbackResponse (after):" + callbackResponse); + + Object sdncDelay = MockResource.getMockProperties().get("sdnc_delay"); + int delay = 300; + if (sdncDelay != null) { + delay = Integer.parseInt(sdncDelay.toString()); + } + + //Kick off callback thread + System.out.println("(NetworkTopologyMockTransformer) callback Url:" + callbackUrl + ":delay:" + delay); + CallbackResponseThread calbackResponseThread = new CallbackResponseThread(callbackUrl,callbackResponse, delay); + calbackResponseThread.start(); + + //return 200 OK with body + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody(callbackResponse).withHeader("Content-Type", "text/xml") + .build(); + } + + @Override + public boolean applyGlobally() { + return false; + } + + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + LOGGER.debug("Exception :",e1); + } + LOGGER.debug("Sending callback response to url: " + callbackUrl); + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + //System.err.println(payLoad); + try { + ClientResponse result = request.post(); + LOGGER.debug("Successfully posted callback? Status: " + result.getStatus()); + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.debug("catch error in - request.post() "); + LOGGER.debug("Exception :",e); + } + } + + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java new file mode 100644 index 0000000000..32f2641ddb --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java @@ -0,0 +1,1069 @@ +/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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.openecomp.mso.bpmn.mock;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.containing;
+import static com.github.tomakehurst.wiremock.client.WireMock.delete;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.patch;
+import static com.github.tomakehurst.wiremock.client.WireMock.put;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
+
+
+/**
+ * Reusable Mock StubResponses for AAI Endpoints
+ *
+ */
+public class StubResponseAAI {
+
+ public static void setupAllMocks() {
+
+ }
+
+
+ /**
+ * Tunnel-XConnect Mock Stub Response
+ */
+ public static void MockPutTunnelXConnect(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String tunnelId){
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId + "/tunnel-xconnects/tunnel-xconnect/" + tunnelId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+
+ /**
+ * Allotted Resource Mock StubResponses below
+ */
+ public static void MockGetAllottedResource(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutAllottedResource(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutAllottedResource_500(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockDeleteAllottedResource(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String resourceVersion) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(204)));
+ }
+
+ public static void MockPatchAllottedResource(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) {
+ stubFor(patch(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockQueryAllottedResourceById(String allottedResourceId, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=allotted-resource[&]filter=id:EQUALS:" + allottedResourceId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+
+ /**
+ * Service Instance Mock StubResponses below
+ */
+ public static void MockGetServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetServiceInstance_404(String customer, String serviceSubscription, String serviceInstanceId){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockGetServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockGetServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(500)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockNodeQueryServiceInstanceByName(String serviceInstanceName, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-name:EQUALS:" + serviceInstanceName))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockNodeQueryServiceInstanceByName_404(String serviceInstanceName){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockNodeQueryServiceInstanceByName_500(String serviceInstanceName){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockNodeQueryServiceInstanceById(String serviceInstanceId, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-id:EQUALS:" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockNodeQueryServiceInstanceById_404(String serviceInstanceId){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockNodeQueryServiceInstanceById_500(String serviceInstanceId){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(204)));
+ }
+
+ public static void MockGetServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockGetServiceInstance(String customer, String serviceSubscription, String resourceVersion, int statusCode){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")));
+ }
+
+ public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String resourceVersion, int statusCode){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" +1234))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockDeleteServiceInstance_404(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockDeleteServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockPutServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutServiceInstance_500(String globalCustId, String subscriptionType, String serviceInstanceId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ /**
+ * Service-Subscription Mock StubResponses below
+ */
+ public static void MockGetServiceSubscription(String globalCustId, String subscriptionType, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteServiceSubscription(String globalCustId, String subscriptionType, int statusCode) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockDeleteServiceInstanceId(String globalCustId, String subscriptionType, String serviceInstanceId) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutServiceSubscription(String globalCustId, String subscriptionType) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockGetServiceSubscription(String globalCustId, String subscriptionType, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ /**
+ * Customer Mock StubResponses below
+ */
+ public static void MockGetCustomer(String globalCustId, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteCustomer(String globalCustId) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutCustomer(String globalCustId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutCustomer_500(String globalCustId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+
+ /**
+ * Generic-Vnf Mock StubResponses below
+ */
+
+ public static void MockGetGenericVnfById(String vnfId, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=1"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfById(String vnfId, String responseFile, int statusCode){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByIdWithPriority(String vnfId, int statusCode, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
+ .atPriority(1)
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByIdWithPriority(String vnfId, String vfModuleId, int statusCode, String responseFile, int priority) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .atPriority(priority)
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByIdWithDepth(String vnfId, int depth, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=" + depth))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfById_404(String vnfId){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockGetGenericVnfById_500(String vnfId){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockGetGenericVnfByName(String vnfName, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByNameWithDepth(String vnfName, int depth, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName + "[&]depth=" + depth))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByName_404(String vnfName){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockDeleteGenericVnf(String vnfId, String resourceVersion){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(204)));
+ }
+
+ public static void MockDeleteGenericVnf(String vnfId, String resourceVersion, int statusCode){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockDeleteGenericVnf_500(String vnfId, String resourceVersion){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+
+ public static void MockPutGenericVnf(String vnfId){
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutGenericVnf(String vnfId, String requestBodyContaining, int statusCode) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
+ .withRequestBody(containing(requestBodyContaining))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockPutGenericVnf(String vnfId, int statusCode) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockPutGenericVnf_Bad(String vnfId, int statusCode){
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockPatchGenericVnf(String vnfId){
+ stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+ /**
+ * Vce Mock StubResponses below
+ */
+ public static void MockGetVceById(String vnfId, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVceByName(String vnfName, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteVce(String vnfId, String resourceVersion, int statusCode){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockPutVce(String vnfId){
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockGetGenericVceByNameWithDepth(String vnfName, int depth, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName + "[&]depth=" + depth))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVceGenericQuery(String serviceInstanceName, int depth, int statusCode, String responseFile){
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=service-instance.service-instance-name:" + serviceInstanceName + "[&]start-node-type=service-instance[&]include=vce[&]depth=" + depth))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ /**
+ * Tenant Mock StubResponses below
+ */
+ public static void MockGetTenantGenericQuery(String customer, String serviceType, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=customer.global-customer-id:" + customer + "&key=service-subscription.service-type:" + serviceType + "&start-node-type=service-subscription&include=tenant&include=service-subscription&depth=1"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetTenant(String tenantId, String responseFile) {
+ stubFor(get(urlEqualTo("/aai/v2/cloud-infrastructure/tenants/tenant/" + tenantId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ /**
+ * Network Mock StubResponses below
+ */
+ public static void MockGetNetwork(String networkId, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkByIdWithDepth(String networkId, String responseFile, String depth) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId + "[?]depth=" + depth))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkCloudRegion(String responseFile, String cloudRegion) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/"+cloudRegion))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkByName(String networkName, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name="+networkName))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkByName_404(String responseFile, String networkName) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name="+networkName))
+ .willReturn(aResponse()
+ .withStatus(404)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkCloudRegion_404(String cloudRegion) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/"+cloudRegion))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockPutNetwork(String networkId, int statusCode, String responseFile) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutNetwork(String networkPolicyId, String responseFile, int statusCode) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicyId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkName(String networkPolicyName, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkPolicyName))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkVpnBinding(String responseFile, String vpnBinding) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/"+vpnBinding + "[?]depth=all"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkPolicy(String responseFile, String policy) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/"+policy + "[?]depth=all"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkVpnBinding(String networkBindingId, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + networkBindingId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkPolicy(String networkPolicy, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicy))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkTableReference(String responseFile, String tableReference) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/"+tableReference + "[?]depth=all"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutNetworkIdWithDepth(String responseFile, String networkId, String depth) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/"+networkId+"[?]depth="+depth ))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkPolicyfqdn(String networkPolicy, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy[?]network-policy-fqdn=" + networkPolicy))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkRouteTable(String networkRouteId, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/" + networkRouteId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPatchVfModuleId(String vnfId, String vfModuleId) {
+ stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ /////////////
+
+ public static void MockVNFAdapterRestVfModule() {
+ stubFor(put(urlEqualTo("/vnfs/v1/vnfs/skask/vf-modules/supercool"))
+ .willReturn(aResponse()
+ .withStatus(202)
+ .withHeader("Content-Type", "application/xml")));
+ stubFor(post(urlMatching("/vnfs/v1/vnfs/.*/vf-modules"))
+ .willReturn(aResponse()
+ .withStatus(202)
+ .withHeader("Content-Type", "application/xml")));
+ stubFor(post(urlEqualTo("/vnfs/v1/vnfs/skask/vf-modules"))
+ .willReturn(aResponse()
+ .withStatus(202)
+ .withHeader("Content-Type", "application/xml")));
+ stubFor(put(urlEqualTo("/vnfs/v1/volume-groups/78987"))
+ .willReturn(aResponse()
+ .withStatus(202)
+ .withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void MockDBUpdateVfModule(){
+ stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/DBUpdateResponse.xml")));
+ }
+
+ // start of mocks used locally and by other VF Module unit tests
+ public static void MockSDNCAdapterVfModule() {
+ // simplified the implementation to return "success" for all requests
+ stubFor(post(urlEqualTo("/SDNCAdapter"))
+// .withRequestBody(containing("SvcInstanceId><"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/StandardSDNCSynchResponse.xml")));
+
+ }
+
+ // start of mocks used locally and by other VF Module unit tests
+ public static void MockAAIVfModule() {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool"))
+ .atPriority(1)
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VfModule-supercool.xml")));
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/lukewarm"))
+ .atPriority(2)
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VfModule-lukewarm.xml")));
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ .atPriority(5)
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VfModule-new.xml")));
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask[?]depth=1"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/GenericVnf.xml")));
+ stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool"))
+// .withRequestBody(containing("PCRF"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+// .withRequestBody(containing("PCRF"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ // HTTP PUT stub still used by CreateAAIvfModuleVolumeGroup
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ .withRequestBody(containing("PCRF"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ // HTTP PUT stub still used by DoCreateVfModuleTest
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ .withRequestBody(containing("MODULELABEL"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group[?]volume-group-id=78987"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/ConfirmVolumeGroupTenantResponse.xml")));
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group[?]volume-group-id=78987"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/ConfirmVolumeGroupTenantResponse.xml")));
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/MDTWNJ21/volume-groups/volume-group/78987"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VolumeGroup.xml")));
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/volume-groups/volume-group/78987"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VolumeGroup.xml")));
+ stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group/78987[?]resource-version=0000020"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("DeleteCinderVolumeV1/DeleteVolumeId_AAIResponse_Success.xml")));
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/AddNetworkPolicy_AAIResponse_Success.xml")));
+ stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/NEWvBNGModuleId"))
+ .withRequestBody(containing("NEWvBNGModuleId"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+
+
+ //////////////
+
+ /**
+ * Cloud infrastructure below
+ */
+
+ public static void MockGetCloudRegion(String cloudRegionId, int statusCode, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ /**
+ * Volume Group StubResponse below
+ */
+ public static void MockGetVolumeGroupById(String cloudRegionId, String volumeGroupId, String responseFile) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutVolumeGroupById(String cloudRegionId, String volumeGroupId, String responseFile, int statusCode) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVolumeGroupByName(String cloudRegionId, String volumeGroupName, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteVolumeGroupById(String cloudRegionId, String volumeGroupId, String resourceVersion, int statusCode) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ public static void MockGetVolumeGroupByName_404(String cloudRegionId, String volumeGroupName) {
+ stubFor(get(urlMatching("/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ public static void MockDeleteVolumeGroup(String cloudRegionId, String volumeGroupId, String resourceVersion) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ /**
+ * VF-Module StubResponse below
+ * @param statusCode TODO
+ */
+ public static void MockGetVfModuleId(String vnfId, String vfModuleId, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVfModuleByNameWithDepth(String vnfId, String vfModuleName, int depth, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module[?]vf-module-name=" + vfModuleName + "[?]depth=" + depth))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVfModuleIdNoResponse(String vnfId, String requestContaining, String vfModuleId) {
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .withRequestBody(containing(requestContaining))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")));
+ }
+
+ public static void MockPutVfModuleIdNoResponse(String vnfId, String requestContaining, String vfModuleId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId +"/vf-modules/vf-module/" +vfModuleId))
+ .withRequestBody(containing(requestContaining))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutVfModuleId(String vnfId, String vfModuleId) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+
+ public static void MockPutVfModuleId(String vnfId, String vfModuleId, int returnCode) {
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse()
+ .withStatus(returnCode)));
+ }
+
+ public static void MockDeleteVfModuleId(String vnfId, String vfModuleId, String resourceVersion, int returnCode) {
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId + "/[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse()
+ .withStatus(returnCode)));
+ }
+
+ public static void MockAAIVfModuleBadPatch(String endpoint, int statusCode) {
+ stubFor(patch(urlMatching(endpoint))
+ .willReturn(aResponse()
+ .withStatus(statusCode)));
+ }
+
+ /* AAI Pserver Queries */
+ public static void MockGetPserverByVnfId(String vnfId, String responseFile, int statusCode) {
+ stubFor(put(urlMatching("/v10/query.*"))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfsByVnfId(String vnfId, String responseFile, int statusCode) {
+ stubFor(get(urlMatching("/v10/network/generic-vnfs/.*"))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ .withHeader("Content-Type", "application/json; charset=utf-8")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockSetInMaintFlagByVnfId(String vnfId, int statusCode) {
+ stubFor(patch(urlMatching("/v10/network/generic-vnfs/.*"))
+ .willReturn(aResponse()
+ .withStatus(statusCode)
+ ));
+ }
+
+ //// Deprecated Stubs below - to be deleted once unit test that reference them are refactored to use common ones above ////
+ @Deprecated
+ public static void MockGetVceById(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123?depth=1"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getVceResponse.xml")));
+ }
+ @Deprecated
+ public static void MockGetVceByName(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getVceByNameResponse.xml")));
+ }
+ @Deprecated
+ public static void MockPutVce(){
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+ @Deprecated
+ public static void MockDeleteVce(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse()
+ .withStatus(204)));
+ }
+ @Deprecated
+ public static void MockDeleteVce_404(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+
+ @Deprecated
+ public static void MockDeleteServiceSubscription(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234"))
+ .willReturn(aResponse()
+ .withStatus(204)));
+ }
+ @Deprecated
+ public static void MockGetServiceSubscription(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getServiceSubscription.xml")));
+ }
+ @Deprecated
+ public static void MockGetServiceSubscription_200Empty(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBody(" ")));
+ }
+ @Deprecated
+ public static void MockGetServiceSubscription_404() {
+ stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+ @Deprecated
+ public static void MockGENPSIPutServiceInstance(){
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericPutServiceInstance/GenericPutServiceInstance_PutServiceInstance_AAIResponse_Success.xml")));
+ }
+
+ @Deprecated
+ public static void MockGENPSIPutServiceSubscription(){
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericPutServiceInstance/GenericPutServiceInstance_PutServiceInstance_AAIResponse_Success.xml")));
+ }
+ @Deprecated
+ public static void MockGENPSIPutServiceInstance_get500(){
+ stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET"))
+ .willReturn(aResponse()
+ .withStatus(500)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericPutServiceInstance/aaiFault.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfById(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfByNameResponse.xml")));
+ }
+ @Deprecated
+ public static void MockGetGenericVnfById_404(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+ @Deprecated
+ public static void MockGetGenericVnfByName(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfResponse.xml")));
+ }
+ @Deprecated
+ public static void MockGetGenericVnfByName_hasRelationships(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml")));
+ }
+ @Deprecated
+ public static void MockGetGenericVnfById_hasRelationships(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml")));
+ }
+ @Deprecated
+ public static void MockGetGenericVnfById_500(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+ @Deprecated
+ public static void MockGetGenericVnfByName_404(){
+ stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+ @Deprecated
+ public static void MockPutGenericVnf(){
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(200)));
+ }
+ @Deprecated
+ public static void MockPutGenericVnf_400(){
+ stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse()
+ .withStatus(400)));
+ }
+ @Deprecated
+ public static void MockDeleteGenericVnf(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse()
+ .withStatus(204)));
+ }
+ @Deprecated
+ public static void MockDeleteGenericVnf_404(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse()
+ .withStatus(404)));
+ }
+ @Deprecated
+ public static void MockDeleteGenericVnf_500(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse()
+ .withStatus(500)));
+ }
+ @Deprecated
+ public static void MockDeleteGenericVnf_412(){
+ stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[[?]]resource-version=testReVer123"))
+ .willReturn(aResponse()
+ .withStatus(412)));
+ }
+
+}
diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseDatabase.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseDatabase.java new file mode 100644 index 0000000000..c9f64d9b26 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseDatabase.java @@ -0,0 +1,102 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; + +/** + * Stub response class for Database stubs + * including database adapter, catalog db, + * and other databases. + */ +public class StubResponseDatabase { + + public static void setupAllMocks() { + + } + + public static void MockUpdateRequestDB(String fileName){ + stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(fileName))); + } + + public static void mockUpdateRequestDB(int statusCode, String reponseFile) { + stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(reponseFile))); + } + + public static void MockGetAllottedResourcesByModelInvariantId(String modelInvariantId, String responseFile){ + stubFor(get(urlEqualTo("/v1/serviceAllottedResources?serviceModelInvariantUuid=" + modelInvariantId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBodyFile(responseFile))); + } + + public static void MockGetAllottedResourcesByModelInvariantId_500(String modelInvariantId, String responseFile){ + stubFor(get(urlEqualTo("/v1/serviceAllottedResources?serviceModelInvariantUuid=" + modelInvariantId)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockGetVnfCatalogDataCustomizationUuid(String vnfModelCustomizationUuid, String responseFile){ + stubFor(get(urlEqualTo("/v2/serviceVnfs?vnfModelCustomizationUuid=" + vnfModelCustomizationUuid)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBodyFile(responseFile))); + } + + public static void MockGetVfModuleByModelNameCatalogData(String vfModuleModelName, String responseFile){ + stubFor(get(urlEqualTo("/v2/vfModules?vfModuleModelName=" + vfModuleModelName)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBodyFile(responseFile))); + } + + public static void MockGetServiceResourcesCatalogData(String serviceModelInvariantUuid, String serviceModelVersion, String responseFile){ + stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=" + serviceModelInvariantUuid + + "&serviceModelVersion=" + serviceModelVersion)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBodyFile(responseFile))); + } + + public static void MockGetServiceResourcesCatalogData(String serviceModelInvariantUuid, String responseFile){ + stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=" + serviceModelInvariantUuid)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBodyFile(responseFile))); + } + + +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseNetworkAdapter.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseNetworkAdapter.java new file mode 100644 index 0000000000..8baeb1b137 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseNetworkAdapter.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; + +/** + * Please describe the StubResponseNetwork.java class + * + */ +public class StubResponseNetworkAdapter { + + private static final String EOL = "\n"; + + public static void setupAllMocks() { + + } + + + public static void MockNetworkAdapter() { + stubFor(post(urlEqualTo("/networks/NetworkAdapter")) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockNetworkAdapter(String response) { + stubFor(post(urlEqualTo("/networks/NetworkAdapter")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(response))); + } + + public static void MockNetworkAdapter_500() { + stubFor(post(urlEqualTo("/networks/NetworkAdapter")) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockNetworkAdapterPost(String responseFile, String requestContaining) { + stubFor(post(urlEqualTo("/networks/NetworkAdapter")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockNetworkAdapter(String networkId, int statusCode, String responseFile) { + stubFor(delete(urlEqualTo("/networks/NetworkAdapter/" + networkId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml") + .withBodyFile(responseFile))); + } + + public static void MockNetworkAdapterContainingRequest(String requestContaining, int statusCode, String responseFile) { + stubFor(post(urlEqualTo("/networks/NetworkAdapter")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockPutNetworkAdapter(String networkId, String requestContaining, int statusCode, String responseFile) { + stubFor(put(urlEqualTo("/networks/NetworkAdapter/" + networkId)) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockNetworkAdapterRestRollbackDelete(String responseFile, String networkId) { + stubFor(delete(urlEqualTo("/networks/NetworkAdapter/"+networkId+"/rollback")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockNetworkAdapterRestPut(String responseFile, String networkId) { + stubFor(put(urlEqualTo("/networks/NetworkAdapter/"+networkId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponsePolicy.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponsePolicy.java new file mode 100644 index 0000000000..38b81c54c6 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponsePolicy.java @@ -0,0 +1,94 @@ +/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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.openecomp.mso.bpmn.mock;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.containing;
+import static com.github.tomakehurst.wiremock.client.WireMock.delete;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.patch;
+import static com.github.tomakehurst.wiremock.client.WireMock.put;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
+
+/**
+ * Reusable Mock StubResponses for Policy
+ *
+ */
+public class StubResponsePolicy {
+
+ public static void setupAllMocks() {
+
+ }
+
+ // start of Policy mocks
+ public static void MockPolicyAbort() {
+ stubFor(post(urlEqualTo("/pdp/api/getDecision"))
+ .withRequestBody(containing("BB1"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+ stubFor(post(urlEqualTo("/pdp/api/getDecision"))
+ .withRequestBody(containing("UPDVnfI"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+ stubFor(post(urlEqualTo("/pdp/api/getDecision"))
+ .withRequestBody(containing("RPLVnfI"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+
+ }
+
+ public static void MockPolicySkip() {
+ stubFor(post(urlEqualTo("/pdp/api/getDecision"))
+ .withRequestBody(containing("BB1"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+ stubFor(post(urlEqualTo("/pdp/api/getDecision"))
+ .withRequestBody(containing("UPDVnfI"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+ stubFor(post(urlEqualTo("/pdp/api/getDecision"))
+ .withRequestBody(containing("RPLVnfI"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+
+ }
+
+
+}
diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseSDNCAdapter.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseSDNCAdapter.java new file mode 100644 index 0000000000..f41d6d7dba --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseSDNCAdapter.java @@ -0,0 +1,146 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; + +/** + * Please describe the StubResponseSDNC.java class + */ +public class StubResponseSDNCAdapter { + + public static void setupAllMocks() { + + } + + public static void mockSDNCAdapter_500() { + stubFor(post(urlEqualTo("/SDNCAdapter")) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void mockSDNCAdapter_500(String requestContaining) { + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void mockSDNCAdapter(int statusCode) { + stubFor(post(urlEqualTo("/SDNCAdapter")) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void mockSDNCAdapter(String endpoint, int statusCode, String responseFile) { + stubFor(post(urlEqualTo(endpoint)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void mockSDNCAdapter(String responseFile) { + stubFor(post(urlEqualTo("/SDNCAdapter")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void mockSDNCAdapter(String endpoint, String requestContaining, int statusCode, String responseFile) { + stubFor(post(urlEqualTo(endpoint)) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void mockSDNCAdapterSimulator(String responseFile) { + MockResource mockResource = new MockResource(); + mockResource.updateProperties("sdnc_delay", "300"); + stubFor(post(urlEqualTo("/SDNCAdapter")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/soap+xml") + .withTransformers("sdnc-adapter-transformer") + .withBodyFile(responseFile))); + } + + public static void mockSDNCAdapterSimulator(String responseFile, String requestContaining) { + MockResource mockResource = new MockResource(); + mockResource.updateProperties("sdnc_delay", "300"); + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/soap+xml") + .withTransformers("sdnc-adapter-transformer") + .withBodyFile(responseFile))); + } + + public static void mockSDNCAdapterRest() { + stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")) + .willReturn(aResponse() + .withStatus(202) + .withHeader("Content-Type", "application/json"))); + } + + public static void mockSDNCAdapterRest_500() { + stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "application/json"))); + } + + public static void mockSDNCAdapterRest(String requestContaining) { + stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(202) + .withHeader("Content-Type", "application/json"))); + } + + public static void mockSDNCAdapterRest_500(String requestContaining) { + stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "application/json"))); + } + + public static void mockSDNCAdapterTopology(String responseFile, String requestContaining) { + MockResource mockResource = new MockResource(); + mockResource.updateProperties("sdnc_delay", "300"); + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withTransformers("network-topology-operation-transformer") + .withBodyFile(responseFile))); + } + + +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseSNIRO.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseSNIRO.java new file mode 100644 index 0000000000..a8f4db80aa --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseSNIRO.java @@ -0,0 +1,69 @@ +/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/*
+ * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property.
+ */
+package org.openecomp.mso.bpmn.mock;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+
+/**
+ * Please describe the StubResponseSNIRO.java class
+ *
+ * @author cb645j
+ */
+public class StubResponseSNIRO {
+
+ public static void setupAllMocks() {
+
+ }
+
+ public static void mockSNIRO() {
+ stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse()
+ .withStatus(202)
+ .withHeader("Content-Type", "application/json")));
+ }
+
+ public static void mockSNIRO(String responseFile) {
+ stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse()
+ .withStatus(202)
+ .withHeader("Content-Type", "application/json")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void mockSNIRO_400() {
+ stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse()
+ .withStatus(400)
+ .withHeader("Content-Type", "application/json")));
+ }
+
+ public static void mockSNIRO_500() {
+ stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse()
+ .withStatus(500)
+ .withHeader("Content-Type", "application/json")));
+ }
+
+}
diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseVNFAdapter.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseVNFAdapter.java new file mode 100644 index 0000000000..b4aca5081e --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseVNFAdapter.java @@ -0,0 +1,158 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; + +/** + * Please describe the StubResponseVNF.java class + */ +public class StubResponseVNFAdapter { + + public static void mockVNFAdapter() { + stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void mockVNFAdapter(String responseFile) { + stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void mockVNFAdapter_500() { + stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void mockVNFAdapterTransformer(String transformer, String responseFile) { + MockResource mockResource = new MockResource(); + mockResource.updateProperties("vnf_delay", "300"); + stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/soap+xml") + .withTransformers(transformer) + .withBodyFile(responseFile))); + } + + public static void mockVNFAdapterTransformer(String transformer, String responseFile, String requestContaining) { + MockResource mockResource = new MockResource(); + mockResource.updateProperties("vnf_delay", "300"); + stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/soap+xml") + .withTransformers(transformer) + .withBodyFile(responseFile))); + } + + public static void mockVNFPost(String vfModuleId, int statusCode, String vnfId) { + stubFor(post(urlEqualTo("/vnfs/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockVNFPut(String vfModuleId, int statusCode) { + stubFor(put(urlEqualTo("/vnfs/v1/vnfs/vnfId/vf-modules" + vfModuleId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockVNFPut(String vnfId, String vfModuleId, int statusCode) { + stubFor(put(urlEqualTo("/vnfs/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockVNFDelete(String vnfId, String vfModuleId, int statusCode) { + stubFor(delete(urlEqualTo("/vnfs/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockVNFRollbackDelete(String vfModuleId, int statusCode) { + stubFor(delete(urlEqualTo("/vnfs/v1/vnfs/vnfId/vf-modules" + vfModuleId + "/rollback")) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockPutVNFVolumeGroup(String volumeGroupId, int statusCode) { + stubFor(put(urlEqualTo("/vnfs/v1/volume-groups/" + volumeGroupId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockPutVNFVolumeGroupRollback(String volumeGroupId, int statusCode) { + stubFor(delete(urlMatching("/vnfs/v1/volume-groups/" + volumeGroupId + "/rollback")) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + public static void mockPostVNFVolumeGroup(int statusCode) { + stubFor(post(urlEqualTo("/vnfs/v1/volume-groups")) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockVNFAdapterRest(String vnfId) { + stubFor(post(urlEqualTo("/vnfs/v1/vnfs/" + vnfId + "/vf-modules")) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void mockVNFAdapterRest_500(String vnfId) { + stubFor(post(urlEqualTo("/vnfs/v1/vnfs/" + vnfId + "/vf-modules")) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void mockVfModuleDelete(String volumeGroupId) { + stubFor(delete(urlMatching("/vnfs/v1/volume-groups/"+ volumeGroupId)) + .willReturn(aResponse() + .withStatus(202) + .withHeader("Content-Type", "application/xml"))); + } + + public static void mockVfModuleDelete(String volumeGroupId, int statusCode) { + stubFor(delete(urlMatching("/vnfs/v1/volume-groups/78987")) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/xml"))); + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterCreateMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterCreateMockTransformer.java new file mode 100644 index 0000000000..23921da8d8 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterCreateMockTransformer.java @@ -0,0 +1,148 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import javax.xml.ws.Endpoint; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; +import org.openecomp.mso.logger.MsoLogger; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; + +import org.openecomp.mso.logger.MsoLogger; +/** + * Please describe the VnfAdapterCreateMockTransformer.java class + * + */ +public class VnfAdapterCreateMockTransformer extends ResponseTransformer { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private String notifyCallbackResponse; + private String ackResponse; + + public VnfAdapterCreateMockTransformer() { + notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfCreateSimResponse.xml"); // default response + } + + @Override + public String name() { + return "vnf-adapter-create-transformer"; + } + + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, + FileSource fileSource) { + + String requestBody = request.getBodyAsString(); + + String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); + String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); + String responseMessageId = ""; + String updatedResponse = ""; + + try { + // try supplied response file (if any) + System.out.println(" Supplied fileName: " + responseDefinition.getBodyFileName()); + ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + notifyCallbackResponse = ackResponse; + responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); + updatedResponse = ackResponse.replace(responseMessageId, messageId); + } catch (Exception ex) { + LOGGER.debug("Exception :",ex); + System.out.println(" ******* Use default response file in '__files/vnfAdapterMocks/vnfCreateSimResponse.xml'"); + responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); + updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); + } + + System.out.println("response (mock) messageId : " + responseMessageId); + System.out.println("request (replacement) messageId: " + messageId); + + System.out.println("vnf Response (before):" + notifyCallbackResponse); + System.out.println("vnf Response (after):" + updatedResponse); + + Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); + int delay = 300; + if (vnfDelay != null) { + delay = Integer.parseInt(vnfDelay.toString()); + } + + //Kick off callback thread + System.out.println("VnfAdapterCreateMockTransformer notficationUrl: " + notficationUrl + ":delay: " + delay); + CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); + callbackResponseThread.start(); + + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") + .build(); + + } + + @Override + public boolean applyGlobally() { + return false; + } + + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + @SuppressWarnings("deprecation") + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + LOGGER.debug("Exception :",e1); + } + LOGGER.debug("Sending callback response to url: " + callbackUrl); + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + //System.out.println("payLoad: " + payLoad); + + try { + ClientResponse result = request.post(); + LOGGER.debug("Successfully posted callback? Status: " + result.getStatus()); + //System.err.println("Successfully posted callback:" + result.getStatus()); + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.debug("catch error in - request.post() "); + LOGGER.debug("Exception :",e); + } + } + + } + + +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterDeleteMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterDeleteMockTransformer.java new file mode 100644 index 0000000000..ee6972e46e --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterDeleteMockTransformer.java @@ -0,0 +1,143 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; +import org.openecomp.mso.logger.MsoLogger; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; +/** + * Please describe the VnfAdapterCreateMockTransformer.java class + * + */ +public class VnfAdapterDeleteMockTransformer extends ResponseTransformer { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private String notifyCallbackResponse; + private String ackResponse; + + public VnfAdapterDeleteMockTransformer() { + notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfDeleteSimResponse.xml"); + } + + @Override + public String name() { + return "vnf-adapter-delete-transformer"; + } + + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, + FileSource fileSource) { + + // System.err.println("notifyCallbackResponse:" + notifyCallbackResponse); + + String requestBody = request.getBodyAsString(); + + String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); + String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); + String responseMessageId = ""; + String updatedResponse = ""; + + try { + // try supplied response file (if any) + System.out.println(" Supplied fileName: " + responseDefinition.getBodyFileName()); + ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + notifyCallbackResponse = ackResponse; + responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); + updatedResponse = ackResponse.replace(responseMessageId, messageId); + } catch (Exception ex) { + LOGGER.debug("Exception :",ex); + System.out.println(" ******* Use default response file in '__files/vnfAdapterMocks/vnfDeleteSimResponse.xml'"); + responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); + updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); + } + + System.out.println("response (mock) messageId : " + responseMessageId); + System.out.println("request (replacement) messageId: " + messageId); + + System.out.println("vnf Response (before):" + notifyCallbackResponse); + System.out.println("vnf Response (after):" + updatedResponse); + + Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); + int delay = 300; + if (vnfDelay != null) { + delay = Integer.parseInt(vnfDelay.toString()); + } + + //Kick off callback thread + System.out.println("VnfAdapterDeleteMockTransformer notficationUrl: " + notficationUrl + ":delay: " + delay); + CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); + callbackResponseThread.start(); + + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") + .build(); + + } + + @Override + public boolean applyGlobally() { + return false; + } + + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + @SuppressWarnings("deprecation") + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + LOGGER.debug("Exception :",e1); + } + System.out.println("Sending callback response to url: " + callbackUrl); + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + //System.err.println(payLoad); + try { + ClientResponse result = request.post(); + System.out.println("Successfully posted callback? Status: " + result.getStatus()); + //System.err.println("Successfully posted callback:" + result.getStatus()); + } catch (Exception e) { + // TODO Auto-generated catch block + System.out.println("catch error in - request.post() "); + LOGGER.debug("Exception :",e); + } + } + + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterQueryMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterQueryMockTransformer.java new file mode 100644 index 0000000000..1582071d3a --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterQueryMockTransformer.java @@ -0,0 +1,161 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + + +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; +import org.openecomp.mso.logger.MsoLogger; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; + +import org.openecomp.mso.logger.MsoLogger; +/** + * Please describe the VnfAdapterQueryMockTransformer.java class + * + */ + + +public class VnfAdapterQueryMockTransformer extends ResponseTransformer{ + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private String notifyCallbackResponse; + private String ackResponse; + private String messageId; + + public VnfAdapterQueryMockTransformer() { + notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfQuerySimResponse.xml"); + } + + public VnfAdapterQueryMockTransformer(String messageId) { + this.messageId = messageId; + } + + @Override + public String name() { + return "vnf-adapter-query-transformer"; + } + + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, + FileSource fileSource) { + + String requestBody = request.getBodyAsString(); + + String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); + String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); + // String updatedResponse = notifyCallbackResponse.replace("b1a82ce6-7f5c-45fd-9273-acaf88fc2137", messageId); + + String responseMessageId = ""; + String updatedResponse = ""; + + // if (ackResponse == null) { + //System.err.println("file:" + responseDefinition.getBodyFileName()); + // ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + //} + + + try { + // try supplied response file (if any) + System.out.println(" Supplied fileName: " + responseDefinition.getBodyFileName()); + ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + notifyCallbackResponse = ackResponse; + responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); + updatedResponse = ackResponse.replace(responseMessageId, messageId); + } catch (Exception ex) { + LOGGER.debug("Exception :",ex); + System.out.println(" ******* Use default response file in '__files/vnfAdapterMocks/vnfQuerySimResponse.xml'"); + responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); + updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); + } + + System.out.println("response (mock) messageId : " + responseMessageId); + System.out.println("request (replacement) messageId: " + messageId); + + System.out.println("vnf Response (before):" + notifyCallbackResponse); + System.out.println("vnf Response (after):" + updatedResponse); + + + Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); + int delay = 300; + if (vnfDelay != null) { + delay = Integer.parseInt(vnfDelay.toString()); + } + + //Kick off callback thread + + //System.out.println("notficationUrl" + notficationUrl); + //System.out.println("updatedResponse" + updatedResponse); + System.out.println("VnfAdapterQueryMockTransformer notficationUrl: " + notficationUrl + ":delay: " + delay); + CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); + System.out.println("Inside Callback" ); + callbackResponseThread.start(); + + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") + .build(); + } + + @Override + public boolean applyGlobally() { + return false; + } + + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + LOGGER.debug("Exception :",e1); + } + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + //System.err.println(payLoad); + try { + ClientResponse result = request.post(); + //System.err.println("Successfully posted callback:" + result.getStatus()); + } catch (Exception e) { + LOGGER.debug("Exception :",e); + } + } + + } + + +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterRollbackMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterRollbackMockTransformer.java new file mode 100644 index 0000000000..186fd35b6f --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterRollbackMockTransformer.java @@ -0,0 +1,144 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; + +import org.openecomp.mso.logger.MsoLogger; +/** + * Please describe the VnfAdapterCreateMockTransformer.java class + * + */ +public class VnfAdapterRollbackMockTransformer extends ResponseTransformer { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private String notifyCallbackResponse; + private String ackResponse; + private String messageId; + + public VnfAdapterRollbackMockTransformer() { + notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfRollbackSimResponse.xml"); + } + + public VnfAdapterRollbackMockTransformer(String messageId) { + this.messageId = messageId; + } + + @Override + public String name() { + return "vnf-adapter-rollback-transformer"; + } + + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, + FileSource fileSource) { + + String requestBody = request.getBodyAsString(); + + String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); + String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); + String responseMessageId = ""; + String updatedResponse = ""; + + try { + // try supplied response file (if any) + System.out.println(" Supplied fileName: " + responseDefinition.getBodyFileName()); + ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + notifyCallbackResponse = ackResponse; + responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); + updatedResponse = ackResponse.replace(responseMessageId, messageId); + } catch (Exception ex) { + LOGGER.debug("Exception :",ex); + System.out.println(" ******* Use default response file in '__files/vnfAdapterMocks/vnfRollbackSimResponse.xml'"); + responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); + updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); + } + + System.out.println("response (mock) messageId : " + responseMessageId); + System.out.println("request (replacement) messageId: " + messageId); + + System.out.println("vnf Response (before):" + notifyCallbackResponse); + System.out.println("vnf Response (after):" + updatedResponse); + + Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); + int delay = 300; + if (vnfDelay != null) { + delay = Integer.parseInt(vnfDelay.toString()); + } + + //Kick off callback thread + System.out.println("VnfAdapterRollbackMockTransformer notficationUrl: " + notficationUrl + ":delay: " + delay); + CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); + callbackResponseThread.start(); + + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") + .build(); + + } + + @Override + public boolean applyGlobally() { + return false; + } + + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + LOGGER.debug("Exception :",e1); + } + System.out.println("Sending callback response to url: " + callbackUrl); + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + //System.err.println(payLoad); + try { + ClientResponse result = request.post(); + System.out.println("Successfully posted callback? Status: " + result.getStatus()); + //System.err.println("Successfully posted callback:" + result.getStatus()); + } catch (Exception e) { + System.out.println("catch error in - request.post() "); + LOGGER.debug("Exception :",e); + } + } + + } +} diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterUpdateMockTransformer.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterUpdateMockTransformer.java new file mode 100644 index 0000000000..7808b47d24 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/VnfAdapterUpdateMockTransformer.java @@ -0,0 +1,149 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.openecomp.mso.bpmn.mock; + +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; +import org.openecomp.mso.logger.MsoLogger; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.common.FileSource; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.http.Request; +import com.github.tomakehurst.wiremock.http.ResponseDefinition; + +import org.openecomp.mso.logger.MsoLogger; +/** + * Please describe the VnfAdapterUpdateMockTransformer.java class + * + */ +public class VnfAdapterUpdateMockTransformer extends ResponseTransformer { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private String notifyCallbackResponse; + private String requestId; + private String ackResponse; + + public VnfAdapterUpdateMockTransformer() { + notifyCallbackResponse = FileUtil.readResourceFile("vnfAdapter/vnfUpdateSimResponse.xml"); + } + + public VnfAdapterUpdateMockTransformer(String requestId) { + this.requestId = requestId; + } + + + public String name() { + return "vnf-adapter-update-transformer"; + } + + @Override + public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, + FileSource fileSource) { + + String requestBody = request.getBodyAsString(); + + String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); + String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); + String responseMessageId = ""; + String updatedResponse = ""; + + try { + // try supplied response file (if any) + System.out.println(" Supplied fileName: " + responseDefinition.getBodyFileName()); + ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); + notifyCallbackResponse = ackResponse; + responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); + updatedResponse = ackResponse.replace(responseMessageId, messageId); + } catch (Exception ex) { + LOGGER.debug("Exception :",ex); + System.out.println(" ******* Use default response file in 'vnfAdapter/vnfUpdateSimResponse.xml'"); + responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); + updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); + } + + System.out.println("response (mock) messageId : " + responseMessageId); + System.out.println("request (replacement) messageId: " + messageId); + + System.out.println("vnf Response (before):" + notifyCallbackResponse); + System.out.println("vnf Response (after):" + updatedResponse); + + Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); + int delay = 300; + if (vnfDelay != null) { + delay = Integer.parseInt(vnfDelay.toString()); + } + + //Kick off callback thread + System.out.println("VnfAdapterUpdateMockTransformer notficationUrl: " + notficationUrl + ":delay: " + delay); + CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); + callbackResponseThread.start(); + + return ResponseDefinitionBuilder + .like(responseDefinition).but() + .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") + .build(); + + } + + @Override + public boolean applyGlobally() { + return false; + } + + private class CallbackResponseThread extends Thread { + + private String callbackUrl; + private String payLoad; + private int delay; + + public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { + this.callbackUrl = callbackUrl; + this.payLoad = payLoad; + this.delay = delay; + } + + public void run () { + try { + //Delay sending callback response + sleep(delay); + } catch (InterruptedException e1) { + LOGGER.debug("Exception :", e1); + } + System.out.println("Sending callback response to url: " + callbackUrl); + ClientRequest request = new ClientRequest(callbackUrl); + request.body("text/xml", payLoad); + //System.err.println(payLoad); + try { + ClientResponse result = request.post(); + System.out.println("Successfully posted callback? Status: " + result.getStatus()); + //System.err.println("Successfully posted callback:" + result.getStatus()); + } catch (Exception e) { + System.out.println("catch error in - request.post() "); + LOGGER.debug("Exception :",e); + } + } + + } +} + diff --git a/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml b/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml new file mode 100644 index 0000000000..bef293dfde --- /dev/null +++ b/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:v1="http://domain2.openecomp.org/workflow/sdnc/adapter/schema/v1">
+ <soapenv:Header />
+ <soapenv:Body>
+ <SDNCAdapterCallbackRequest
+ xmlns="http://domain2.openecomp.org/workflow/sdnc/adapter/schema/v1">
+ <CallbackHeader>
+ <RequestId>d325c9a7-84c0-4081-b979-9cc773a0976d</RequestId>
+ <ResponseCode>200</ResponseCode>
+ <ResponseMessage>OK</ResponseMessage>
+ </CallbackHeader>
+ <RequestData xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><layer3-service-list
+ xmlns="com:att:sdnctl:l3api"><service-instance-id>0XX/VXXX/003717//Shakeout</service-instance-id><service-status><rpc-name>svc-topology-operation</rpc-name><rpc-action>delete</rpc-action><request-status>synccomplete</request-status><final-indicator>Y</final-indicator><l3sdn-action>DisconnectLayer3ServiceRequest</l3sdn-action><response-timestamp>2015-10-22T02:11:52.010Z</response-timestamp></service-status><service-data><svc-config-additional-data/></service-data></layer3-service-list>
+ </RequestData>
+ </SDNCAdapterCallbackRequest>
+ </soapenv:Body>
+</soapenv:Envelope>
diff --git a/bpmn/MSOMockServer/src/main/webapp/WEB-INF/jboss-web.xml b/bpmn/MSOMockServer/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000..cca27bb062 --- /dev/null +++ b/bpmn/MSOMockServer/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd"> +<jboss-web> + <security-domain>other</security-domain> + <context-root>/msomock</context-root> +</jboss-web>
\ No newline at end of file diff --git a/bpmn/MSOURN-plugin/build.properties b/bpmn/MSOURN-plugin/build.properties deleted file mode 100644 index 7e5fb9f22f..0000000000 --- a/bpmn/MSOURN-plugin/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -# Copy this file to 'build.properties' and modify it to match your system -# Alternatively, you can also copy it to '${user.home}/.camunda/build.properties' -# to have a central configuration that works with all camunda BPM projects - -# Defines the deployment folder in a camunda BPM installation (backslashes need to be escaped or replaced by forward slashes). -#deploy.jboss.dir=C:/camunda/camunda-bpm-jboss-7.3.0/server/jboss-as-${jboss-version}/standalone/deployments -deploy.jboss.dir=C:/D2/jboss-ee/server/jboss-as-7.2.0.Final/standalone/deployments
\ No newline at end of file diff --git a/bpmn/MSOURN-plugin/build.xml b/bpmn/MSOURN-plugin/build.xml deleted file mode 100644 index f2dbc55e52..0000000000 --- a/bpmn/MSOURN-plugin/build.xml +++ /dev/null @@ -1,60 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project name="urnMap-plugin" default="deploy.jboss"> - - <property file="build.properties" /> - <property file="${user.home}/.camunda/build.properties" /> - <property name="target.dir" value="target" /> - - <condition property="mvn.executable" value="mvn.bat" else="mvn"> - <os family="windows"/> - </condition> - - <target name="deploy.jboss" depends="package.mvn, install.cockpit.plugin" description="Copies the cockit plugin to the deployment directory defined in '${basedir}/build.properties' or '${user.home}/.camunda/build.properties'" /> - - <target name="deploy.tomcat" depends="package.mvn" description="Copies the cockpit plugin to the deployment directory defined in '${basedir}/build.properties' or '${user.home}/.camunda/build.properties'"> - <fail unless="deploy.tomcat.dir" message="No deployment folder has been configured. Please copy the file '${basedir}/build.properties.example' to '${basedir}/build.properties' or '${user.home}/.camunda/build.properties' and change it according to your environment." /> - <copy file="${target.dir}/${ant.project.name}.jar" todir="${deploy.tomcat.dir}/camunda/WEB-INF/lib" /> - <touch file="${deploy.tomcat.dir}/camunda/WEB-INF/web.xml"/> - </target> - - <target name="package.mvn"> - <exec executable="${mvn.executable}" dir="." failonerror="true"> - <env key="MAVEN_OPTS" value="-Xmx1024m -Xms512m -DskipTests=true -Dmaven.test.skip=true" /> - <arg line="clean package" /> - </exec> - </target> - - <target name="install.cockpit.plugin"> - <fail unless="deploy.jboss.dir" message="No deployment folder has been configured. Please copy the file '${basedir}/build.properties.example' to '${basedir}/build.properties' or '${user.home}/.camunda/build.properties' and change it according to your environment." /> - <path id="cockpit.file.id"> - <fileset dir="${deploy.jboss.dir}"> - <include name="camunda-webapp-*.war"/> - </fileset> - </path> - <property name="cockpit.file" refid="cockpit.file.id"/> - <war destfile="${cockpit.file}" update="true"> - <zipfileset file="${target.dir}/${ant.project.name}.jar" fullpath="WEB-INF/lib/${ant.project.name}.jar" /> - </war> - </target> - - <target name="undeploy.jboss" description="Deletes the cockpit plugin from the deployment directory defined in '${basedir}/build.properties' or '${user.home}/.camunda/build.properties'"> - <path id="cockpit.file.id"> - <fileset dir="${deploy.jboss.dir}"> - <include name="camunda-webapp-*.war"/> - </fileset> - </path> - <property name="cockpit.file" refid="cockpit.file.id"/> - <basename property="cockpit.filename" file="${cockpit.file}"/> - <move file="${cockpit.file}" todir="${java.io.tmpdir}"/> - <zip destfile="${cockpit.file}"> - <zipfileset src="${java.io.tmpdir}/${cockpit.filename}"> - <exclude name="WEB-INF/lib/${ant.project.name}.jar"/> - </zipfileset> - </zip> - </target> - - <target name="undeploy.tomcat" description="Deletes the cockpit plugin from the deployment directory defined in '${basedir}/build.properties' or '${user.home}/.camunda/build.properties'"> - <delete file="${deploy.tomcat.dir}/camunda/WEB-INF/lib/${ant.project.name}.jar" /> - </target> - -</project> diff --git a/bpmn/MSOURN-plugin/pom.xml b/bpmn/MSOURN-plugin/pom.xml deleted file mode 100644 index 40dcd1f666..0000000000 --- a/bpmn/MSOURN-plugin/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.openecomp.so</groupId>
- <artifactId>bpmn</artifactId>
- <version>1.1.0-SNAPSHOT</version>
- </parent>
-
- <groupId>org.openecomp.so</groupId>
- <artifactId>cockpit-urnmap-plugin</artifactId>
-
- <packaging>jar</packaging>
-
- <name>MSO URN Mapping Cockpit Plugin</name>
-
- <dependencies>
- <dependency>
- <groupId>org.camunda.bpm.webapp</groupId>
- <artifactId>camunda-webapp</artifactId>
- <classifier>classes</classifier>
- <version>${camunda.version}</version>
- <exclusions>
- <exclusion>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.2</version>
- </dependency>
- <dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
- <version>2.0</version>
- </dependency>
- <!-- TODO Upate it to ee version -->
- <dependency>
- <groupId>org.camunda.bpm</groupId>
- <artifactId>camunda-engine</artifactId>
- <version>${camunda.version}</version>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>3.0.1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.openecomp.so</groupId>
- <artifactId>common</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
-</project>
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java deleted file mode 100644 index 4f6ead0299..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java +++ /dev/null @@ -1,54 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.camunda.bpm.cockpit.plugin.spi.impl.AbstractCockpitPlugin;
-import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource;
-
-
-
-public class URNMapPlugin extends AbstractCockpitPlugin{
- public static final String ID = "urnMap-plugin";
-
- @Override
- public String getId() {
- return ID;
- }
-
- @Override
- public Set<Class<?>> getResourceClasses() {
- Set<Class<?>> classes = new HashSet<>();
-
- classes.add(URNMapPluginRootResource.class);
-
- return classes;
- }
-
- @Override
- public List<String> getMappingFiles() {
- return Arrays.asList("org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml");
- }
-}
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java deleted file mode 100644 index 60d65665fe..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap.db;
-
-import org.camunda.bpm.engine.ProcessEngineConfiguration;
-import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
-import org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration;
-import org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor;
-import org.camunda.bpm.engine.impl.interceptor.CommandInterceptor;
-import org.camunda.bpm.engine.impl.interceptor.LogInterceptor;
-import org.camunda.bpm.engine.impl.util.ReflectUtil;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-public class MyBatisExtendedSessionFactory extends StandaloneProcessEngineConfiguration {
-
- private String resourceName;
-
- @Override
- protected void init() {
- throw new IllegalArgumentException(
- "Normal 'init' on process engine only used for extended MyBatis mappings is not allowed, please use 'initFromProcessEngineConfiguration'. You cannot construct a process engine with this configuration.");
- }
-
- /**
- * initialize the {@link ProcessEngineConfiguration} from an existing one,
- * just using the database settings and initialize the database / MyBatis
- * stuff.
- */
- public void initFromProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration, String resourceName) {
- this.resourceName = resourceName;
-
- setDatabaseType(processEngineConfiguration.getDatabaseType());
- setDataSource(processEngineConfiguration.getDataSource());
- setDatabaseTablePrefix(processEngineConfiguration.getDatabaseTablePrefix());
-
- initDataSource();
- initCommandContextFactory();
- initTransactionFactory();
- initTransactionContextFactory();
- initCommandExecutors();
- initSqlSessionFactory();
- initIncidentHandlers();
- initIdentityProviderSessionFactory();
- initSessionFactories();
- }
-
- /**
- * In order to always open a new command context set the property
- * "alwaysOpenNew" to true inside the CommandContextInterceptor.
- *
- * If you execute the custom queries inside the process engine
- * (for example in a service task), you have to do this.
- */
- @Override
- protected Collection<? extends CommandInterceptor> getDefaultCommandInterceptorsTxRequired() {
- List<CommandInterceptor> defaultCommandInterceptorsTxRequired = new ArrayList<>();
- defaultCommandInterceptorsTxRequired.add(new LogInterceptor());
- defaultCommandInterceptorsTxRequired.add(new CommandContextInterceptor(commandContextFactory, this, true));
- return defaultCommandInterceptorsTxRequired;
- }
-
- @Override
- protected InputStream getMyBatisXmlConfigurationSteam() {
- return ReflectUtil.getResourceAsStream(resourceName);
- }
-
-}
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java deleted file mode 100644 index f81d8c604d..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java +++ /dev/null @@ -1,44 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap.db;
-
-import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
-import org.camunda.bpm.engine.impl.interceptor.Command;
-
-/**
- * Helper to initialize a minimized process engine which does all the transaction and MyBatis mapping stuff for us
- * and can be used to execute queries.
- */
-public class MyBatisQueryCommandExecutor {
-
- private MyBatisExtendedSessionFactory myBatisExtendedSessionFactory;
-
- public MyBatisQueryCommandExecutor(ProcessEngineConfigurationImpl processEngineConfiguration, String mappingResourceName) {
- myBatisExtendedSessionFactory = new MyBatisExtendedSessionFactory();
- myBatisExtendedSessionFactory.initFromProcessEngineConfiguration(processEngineConfiguration, mappingResourceName);
- }
-
- public <T> T executeQueryCommand(Command<T> command) {
- return myBatisExtendedSessionFactory.getCommandExecutorTxRequired().execute(command);
- }
-
-
-}
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java deleted file mode 100644 index 1eb0ba6f97..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java +++ /dev/null @@ -1,49 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap.db;
-
-import java.util.List;
-
-import org.camunda.bpm.engine.ProcessEngines;
-import org.camunda.bpm.engine.impl.ProcessEngineImpl;
-import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
-import org.camunda.bpm.engine.impl.interceptor.Command;
-import org.camunda.bpm.engine.impl.interceptor.CommandContext;
-
-public class URNService {
-
-
- public List<URNData> getProperties() {
- ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine();
- ProcessEngineConfigurationImpl processEngineConfiguration = processEngine.getProcessEngineConfiguration();
-
- MyBatisQueryCommandExecutor commandExecutor = new MyBatisQueryCommandExecutor(processEngineConfiguration, "mappings.xml");
- return commandExecutor.executeQueryCommand(new Command<List<URNData>>() {
-
- @SuppressWarnings("unchecked")
- @Override
- public List<URNData> execute(CommandContext commandContext) {
- return (List<URNData>) commandContext.getDbSqlSession().selectList("retrieveUrnKeyValuePair", null);
- }
- });
- }
-
-}
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java deleted file mode 100644 index 484981c99d..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java +++ /dev/null @@ -1,98 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap.resources;
-
-import java.util.List;
-import java.util.StringTokenizer;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.camunda.bpm.cockpit.db.QueryParameters;
-import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource;
-import org.openecomp.camunda.bpmn.plugin.urnmap.db.*;
-
-public class ProcessInstanceResource extends AbstractPluginResource {
-
- private static final Logger log = LoggerFactory.getLogger(ProcessInstanceResource.class);
-
- public ProcessInstanceResource(String engineName) {
- super(engineName);
- }
-
- @GET
- public List<URNData> getUrnDataMap() {
- List<URNData> list = getQueryService()
- .executeQuery(
- "cockpit.urnMap.retrieveUrnKeyValuePair",
- new QueryParameters<URNData>());
-
- log.info("urnmap-plugin project - Results Retrieved: ");
- log.info("URNName: " + " " + "URNValue: " );
- for(URNData d: list)
- {
- log.info( d.getURNName() + " " + d.getURNValue());
- }
-
- return list;
- }
-
- @PUT
- //public void insertNewRow(String key, String value)
- public void insertNewRow(String temp)
- {
- log.info("AddNewRow: XXXXXXXXXXXXXXXXX ---> " + temp);
- StringTokenizer st = new StringTokenizer(temp, "|");
- String key = "";
- String value = "";
-
- while(st.hasMoreTokens()) {
- key = st.nextToken();
- value = st.nextToken();
- log.info(key + "\t" + value);
- }
-
- log.info("AddNewRow: XXXXXXXXXXXXXXXXX ---> key: " + key + " , Value: " + value);
- URNData nRow = new URNData();
- nRow.setVer_("1");
- nRow.setURNName(key);
- nRow.setURNValue(value);
-
- getQueryService().executeQuery("cockpit.urnMap.insertNewRow", nRow, URNData.class);
-
- log.info("AddNewRow: XXXXXX END XXXXXXXXXXX");
- }
-
- @POST
- public void getPersistData(URNData d) {
-
- log.info("getPersistData: UrnName: " + d.getURNName() + " , URNValue: " + d.getURNValue() );
-
- getQueryService().executeQuery("cockpit.urnMap.persistURNData", d, URNData.class);
-
-
- log.info("XXXXXXXXXX - END - XXXXXXXXXXXXXXX");
- }
-}
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java deleted file mode 100644 index e8e5e47c07..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java +++ /dev/null @@ -1,41 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap.resources;
-
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-
-import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource;
-import org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin;
-
-@SuppressWarnings("deprecation")
-@Path("plugin/" + URNMapPlugin.ID)
-public class URNMapPluginRootResource extends AbstractPluginRootResource
-{
- public URNMapPluginRootResource() {
- super(URNMapPlugin.ID);
- }
-
- @Path("{engineName}/process-instance")
- public URNResource getProcessInstanceResource(@PathParam("engineName") String engineName) {
- return subResource(new URNResource(engineName), engineName);
- }
-}
diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java deleted file mode 100644 index 938b9d377f..0000000000 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java +++ /dev/null @@ -1,239 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.camunda.bpmn.plugin.urnmap.resources;
-/***
-import java.beans.Statement;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-*/
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.sql.DataSource;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-
-import org.camunda.bpm.cockpit.db.QueryParameters;
-import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource;
-
-
-//import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource;
-import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData;
-import org.openecomp.mso.logger.MsoLogger;
-
-
-//public class ProcessInstanceResource extends AbstractPluginResource {
-public class URNResource extends AbstractCockpitPluginResource{
- public URNResource(String engineName) {
- super(engineName);
- }
-
- private Connection conn;
- private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
- @GET
- public List<URNData> getUrnDataMap()
- {
- List<URNData> list = new ArrayList();
- PreparedStatement psData = null;
- try {
-
- conn = getDBConnection();
- psData = conn
- .prepareStatement("select * from MSO_URN_MAPPING order by NAME_");
-
- ResultSet r = psData.executeQuery();
-
- while(r.next())
- {
- URNData d = new URNData();
- d.setURNName(r.getString("NAME_"));
- d.setURNValue(r.getString("VALUE_"));
- d.setVer_( r.getString("REV_"));
-
- list.add(d);
- }
-
- } catch (Exception e)
- {
- msoLogger.debug("Exception in getUrnDataMap ", e);
- } finally {
- if(psData != null){
- try {
- psData.close();
- conn.close();
- } catch (SQLException e) {
- msoLogger.debug("Exception while closing the PreparedStatement: ", e);
- }
- }
- if(conn != null){
- try {
- conn.close();
- } catch (SQLException e) {
- msoLogger.debug("Exception while closing the connection: ", e);
- }
- }
- }
-
- for(URNData d: list)
- {
- msoLogger.debug( d.getURNName() + " " + d.getURNValue());
- //msoLogger.debug("Started Executing " + getTaskName());
- msoLogger.debug("Started Executing " + d.getURNName() + " " + d.getURNValue());
- }
-
- return list;
- }
-
- public List<URNData> getUrnDataMapOLD()
- {
-
- List<URNData> list = getQueryService()
- .executeQuery("cockpit.urnMap.retrieveUrnKeyValuePair", new QueryParameters<URNData>());
-
- msoLogger.debug("urnmap-plugin project - Results Retrieved: ");
- msoLogger.debug("URNName: " + " " + "URNValue: " );
-
- for(URNData d: list)
- {
- msoLogger.debug( d.getURNName() + " " + d.getURNValue());
- }
-
- return list;
- }
-
- public Connection getDBConnection()
- {
- try {
-
- if(conn == null)
- {
- Context ctx = new InitialContext();
- DataSource ds = (DataSource)ctx.lookup("java:jboss/datasources/ProcessEngine");//jboss
- conn = ds.getConnection();
-
- }
-
- } catch (Exception e)
- {
- msoLogger.debug("Exception in DBConnection ", e);
- }
-
- return conn;
- }
-
- @PUT
- public void insertNewRow(String temp)
- {
- msoLogger.debug("AddNewRow: XXXXXXXXXXXXXXXXX ---> " + temp);
- msoLogger.debug("AddNewRow: EngineName ---> " + engineName);
-
- StringTokenizer st = new StringTokenizer(temp, "|");
- String key_ = "";
- String value_ = "";
-
- while(st.hasMoreTokens()) {
- key_ = st.nextToken();
- value_ = st.nextToken();
- msoLogger.debug(key_ + "\t" + value_);
- }
-
- msoLogger.debug("AddNewRow: XXXXXXXXXXXXXXXXX ---> key: " + key_ + " , Value: " + value_);
- final URNData nRow = new URNData();
- nRow.setVer_("1");
- PreparedStatement psData = null;
-
- msoLogger.debug("----------- START ----------------------");
- try {
-
- conn = getDBConnection();
- psData = conn
- .prepareStatement("Insert into MSO_URN_MAPPING values ('" + key_ + "', '" + value_ + "', '1')");
-
- psData.executeUpdate();
-
- } catch (Exception e)
- {
- msoLogger.debug("Exception in insertNewRow ", e);
- }finally {
- if(psData != null){
- try {
- psData.close();
- conn.close();
- } catch (SQLException e) {
- msoLogger.debug("Exception while closing the PreparedStatement: ", e);
- }
- }
- if(conn != null){
- try {
- conn.close();
- } catch (SQLException e) {
- msoLogger.debug("Exception while closing the connection: ", e);
- }
- }
- }
- // getQueryService().executeQuery("cockpit.urnMap.insertNewRow", nRow, URNData.class);
- }
-
- @POST
- public void getPersistData(URNData d) {
-
- //getQueryService().executeQuery("cockpit.urnMap.persistURNData", d, URNData.class);
- PreparedStatement psData = null;
- try {
-
- conn = getDBConnection();
- psData = conn
- .prepareStatement("UPDATE MSO_URN_MAPPING set VALUE_ ='"+ d.getURNValue() + "' WHERE NAME_='" + d.getURNName() + "'");
-
- psData.executeUpdate();
-
- } catch (Exception e)
- {
- msoLogger.debug("Exception in PersistData ", e);
- }finally {
- if(psData != null){
- try {
- psData.close();
- conn.close();
- } catch (SQLException e) {
- msoLogger.debug("Exception while closing the PreparedStatement: ", e);
- }
- }
- if(conn != null){
- try {
- conn.close();
- } catch (SQLException e) {
- msoLogger.debug("Exception while closing the connection: ", e);
- }
- }
- }
-
- }
-}
diff --git a/bpmn/MSOURN-plugin/src/main/resources/META-INF/services/org.camunda.bpm.cockpit.plugin.spi.CockpitPlugin b/bpmn/MSOURN-plugin/src/main/resources/META-INF/services/org.camunda.bpm.cockpit.plugin.spi.CockpitPlugin deleted file mode 100644 index 9a5055af22..0000000000 --- a/bpmn/MSOURN-plugin/src/main/resources/META-INF/services/org.camunda.bpm.cockpit.plugin.spi.CockpitPlugin +++ /dev/null @@ -1 +0,0 @@ -org.openecomp.camunda.bpm.plugin.urnmap.URNMapPlugin
\ No newline at end of file diff --git a/bpmn/MSOURN-plugin/src/main/resources/mappings.xml b/bpmn/MSOURN-plugin/src/main/resources/mappings.xml deleted file mode 100644 index c66704ed15..0000000000 --- a/bpmn/MSOURN-plugin/src/main/resources/mappings.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ============LICENSE_START=======================================================
- ECOMP MSO
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-
-<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
-
-<configuration>
- <settings>
- <setting name="lazyLoadingEnabled" value="false" />
- </settings>
- <mappers>
- <mapper resource="org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml" />
- </mappers>
-</configuration>
diff --git a/bpmn/MSOURN-plugin/src/main/resources/org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml b/bpmn/MSOURN-plugin/src/main/resources/org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml deleted file mode 100644 index d0b58618e4..0000000000 --- a/bpmn/MSOURN-plugin/src/main/resources/org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml +++ /dev/null @@ -1,64 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<!-- - ============LICENSE_START======================================================= - ECOMP MSO - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> - - -<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - -<mapper namespace="cockpit.urnMap"> - <resultMap id="urnDataMap" type="org.openecomp.camunda.bpm.plugin.urnmap.db.URNData"> - <result property="URNName" column="URNNAME" jdbcType="VARCHAR"/> - <result property="URNValue" column="URNVALUE" jdbcType="VARCHAR" /> - </resultMap> - - <select id="retrieveUrnKeyValuePair" resultMap="urnDataMap"> - select NAME_ URNName, VALUE_ URNValue from MSO_URN_MAPPING - </select> - - - <!-- INSERT cockpit.InsertURNData keyProperty="NAME_" --> - <resultMap id="insertNewRow" type="org.openecomp.camunda.bpm.plugin.urnmap.db.URNData"> - <result property="URNName" column="NAME_" jdbcType="VARCHAR" /> - <result property="URNValue" column="VALUE_" jdbcType="VARCHAR" /> - <result property="1" column="REV_" jdbcType="INTEGER"/> - </resultMap> - - <insert id="insertNewRow" parameterType="org.openecomp.camunda.bpm.plugin.urnmap.db.URNData"> - insert into MSO_URN_MAPPING (NAME_, VALUE_, REV_) - values ( - #{URNName}, #{URNValue}, 1 - ) - </insert> - -<!-- UPDATE cockpit.InsertURNData --> - <resultMap id="saveURNMappingDataMap" type="org.openecomp.camunda.bpm.plugin.urnmap.db.URNData"> - <result property="URNName" column="NAME_" jdbcType="VARCHAR" /> - <result property="URNValue" column="VALUE_" jdbcType="VARCHAR" /> - <result property="1" column="REV_" jdbcType="INTEGER"/> - </resultMap> - - <update id="persistURNData"> - update MSO_URN_MAPPING set - NAME_ = #{URNName}, - VALUE_ = #{URNValue}, - REV_ = 1 - where NAME_=#{URNName} -</update> -</mapper> diff --git a/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/app/dashboard.html b/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/app/dashboard.html deleted file mode 100644 index cc794e5518..0000000000 --- a/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/app/dashboard.html +++ /dev/null @@ -1,63 +0,0 @@ -<!-- - ============LICENSE_START======================================================= - ECOMP MSO - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> - -<div class="form-group container"> - <form novalidate="novalidate" class="simple-form" name="urnMapper"> - <div class="panel panel-default"> - <div class="panel-heading" style="padding:3px;background:#871020 !important;color:#fff"> <h3 style="margin:1px" class="heading">Process Engine - URN Mapping</h3></div> - <div class="panel-body"> - <div class="well"> - <div class="input-group well" style="padding:5px"> - <input id="new_key" class="form-control input-md" placeholder="New URN Key" size="25" type="text" name="URNName" value="" ng-blur="enableAddRowBtn()"> - <span class="input-group-btn" style="width:0px;"></span> - <input type="text" class="form-control input-md" size="55" style="margin-left:-1px" id="new_value" placeholder="New URN Value" name="URNValue" /> - <span class="input-group-btn" style="width:0px;"></span> - <span class="input-group-btn"> - <button class="btn btn-primary" type="button" id="addRow_BTN" data-ng-click="addNewRow(); setTimeout( retrieveData(), 1000);" disabled data-original-title="" title="">Add!</button> - </span> - </div> - <div> - <table cellpadding="0" cellspacing="0" class="table responsive" widht="100%"> - <tbody> - <tr data-ng-repeat="urnData in UrnDataMap"> - <td> - <div class="input-group"> - <input id="{{ urnData.urnname }}_key" type="text" style="border:0px solid #bfbfbf" size="25" class="form-control input-md" ng-blur="SaveRow( urnData )" value="{{ urnData.urnName }}" data-ng-model= "urnData.urnname" data-ng-change="enableButton(urnData)"/> - <span class="input-group-btn" style="width:0px;"></span> - <input id="{{ urnData.urnname }}_value" type="text" style="border:0px solid #dfdfdf;border-left:1px solid #bfbfbf" size="55" class="form-control input-md" ng-blur="SaveRow( urnData )" value="{{ urnData.urnvalue }}" data-ng-model="urnData.urnvalue" data-ng-change="enableButton(urnData)"/> - <span class="input-group-btn"> - <button disabled="true" class="btn btn-primary" type="button" id="btn_{{ urnData.urnname }}_key" data-ng-click="SaveRow( urnData ); setTimeout( retrieveData(), 1000);"> - <span class="glyphicon glyphicon-floppy-disk"></span> - </button> - </span> - </div><!-- /input-group --> - </td> - <!-- - <td><button id="btn_{{ urnData.urnname }}_key" data-ng-click="SaveRow( urnData )" disabled>SaveRecord</button> </td> - --> - </tr> - </tbody> - </table> - </div> - </div> - </div> - </div> - </form> -</div> diff --git a/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/app/plugin.js b/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/app/plugin.js deleted file mode 100644 index 702f6cd3f5..0000000000 --- a/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/app/plugin.js +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -define(['angular'], function(angular) { - - var DashboardController = ["$scope", "$http", "Uri", function($scope, $http, Uri) { - - $http.get(Uri.appUri("plugin://urnMap-plugin/:engine/process-instance")) - .success(function(data) { - $scope.UrnDataMap = data; - }); - - //enable saveRow button - $scope.enableButton=function(urnData) - { - document.getElementById("btn_" + urnData.urnname + "_key").disabled = false; - }; - - $scope.enableAddRowBtn=function() - { - if(document.getElementById("new_key").value.trim().length >0) - document.getElementById("addRow_BTN").disabled = false; - else - document.getElementById("addRow_BTN").disabled = true; - }; - - - $scope.addNewRow = function() - { - var newKey = document.getElementById("new_key").value.trim(); - var newValue = document.getElementById("new_value").value.trim(); - var x; - - for (var i=0;i<$scope.UrnDataMap.length;i++) - { - var n = $scope.UrnDataMap[i].urnname.localeCompare(newKey); - if(n == 0){ - x = "match"; - } - } - - if(Boolean(x)) - { - alert("URN Name already exists, please check the KEY!"); - } - else - { - if(newKey.length >0 ) - { - - var temp = newKey + "|" + newValue; - - $http.put(Uri.appUri("plugin://urnMap-plugin/:engine/process-instance"), temp); - - document.getElementById("new_key").value = ""; - document.getElementById("new_value").value = ""; - - } - - } - //this.enableAddRowBtn; - document.getElementById("addRow_BTN").disabled = true; - - $http.get(Uri.appUri("plugin://urnMap-plugin/:engine/process-instance")) - .success(function(data) { - $scope.UrnDataMap = data; - }); - - - } - - $scope.retrieveData = function() { - - $http.get(Uri.appUri("plugin://urnMap-plugin/:engine/process-instance")) - .success(function(data) { - $scope.UrnDataMap = data; - }); - } - - $scope.SaveRow = function(user) - { - $http.post(Uri.appUri("plugin://urnMap-plugin/:engine/process-instance"), user); - - document.getElementById("btn_" + user.urnname + "_key").disabled = true; - document.getElementById(user.urnname + "_status").style.display = ""; - this.enableAddRowBtn; - - $http.get(Uri.appUri("plugin://urnMap-plugin/:engine/process-instance")) - .success(function(data) { - $scope.UrnDataMap = data; - }); - - }; - }]; - - var Configuration = ['ViewsProvider', function(ViewsProvider) { - - ViewsProvider.registerDefaultView('cockpit.dashboard', { - id: 'process-definitions', - label: 'Deployed Processes', - url: 'plugin://urnMap-plugin/static/app/dashboard.html', - controller: DashboardController, - // make sure we have a higher priority than the default plugin - priority: 12 - }); - }]; -//START -//END - - var ngModule = angular.module('cockpit.plugin.urnMap-plugin', []); - - ngModule.config(Configuration); - - return ngModule; -}); diff --git a/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/info.txt b/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/info.txt deleted file mode 100644 index 09b62620e6..0000000000 --- a/bpmn/MSOURN-plugin/src/main/resources/plugin-webapp/urnMap-plugin/info.txt +++ /dev/null @@ -1 +0,0 @@ -# Client side assets of the urnMap-plugin
\ No newline at end of file diff --git a/bpmn/pom.xml b/bpmn/pom.xml index b878467e72..4f96cc1ffe 100644 --- a/bpmn/pom.xml +++ b/bpmn/pom.xml @@ -31,11 +31,10 @@ <modules> <module>MSOCoreBPMN</module> - <!--<module>MSOMockServer</module> --> + <module>MSOMockServer</module> <module>MSORESTClient</module> <module>MSOCommonBPMN</module> <module>MSOInfrastructureBPMN</module> - <module>MSOURN-plugin</module> <module>MSOCockpit</module> </modules> diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java index 19115ce55b..86aedc1a43 100644 --- a/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java @@ -135,7 +135,7 @@ public class MsoLogger { } }; - private EELFLogger debugLogger, errorLogger, auditLogger, metricsLogger; + private EELFLogger logger, auditLogger, metricsLogger; private static final String CONFIG_FILE = System.getProperty("jboss.home.dir") + "/mso-config/uuid/uuid_" + System.getProperty("jboss.server.name"); private static String instanceUUID, serverIP, serverName; @@ -145,8 +145,7 @@ public class MsoLogger { private static final Logger LOGGER = Logger.getLogger(MsoLogger.class.getName()); private MsoLogger(MsoLogger.Catalog cat) { - this.debugLogger = EELFManager.getInstance().getDebugLogger(); - this.errorLogger = EELFManager.getInstance().getErrorLogger(); + this.logger = EELFManager.getInstance().getErrorLogger(); this.auditLogger = EELFManager.getInstance().getAuditLogger(); this.metricsLogger = EELFManager.getInstance().getMetricsLogger(); MsoLogger.initialization(); @@ -238,7 +237,7 @@ public class MsoLogger { */ public void debug(String msg) { prepareMsg(DEBUG_LEVEL); - debugLogger.debug(msg); + logger.debug(msg); } /** @@ -251,7 +250,7 @@ public class MsoLogger { */ public void debug(String msg, Throwable t) { prepareMsg(DEBUG_LEVEL); - debugLogger.debug(msg, t); + logger.debug(msg, t); } // Info methods @@ -264,7 +263,7 @@ public class MsoLogger { public void info(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg); + logger.info(msg); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -280,7 +279,7 @@ public class MsoLogger { public void info(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg, normalize(arg0)); + logger.info(msg, normalize(arg0)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -297,7 +296,7 @@ public class MsoLogger { String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg, normalize(arg0), normalize(arg1)); + logger.info(msg, normalize(arg0), normalize(arg1)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -314,7 +313,7 @@ public class MsoLogger { String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -331,7 +330,7 @@ public class MsoLogger { String targetEntity, String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -348,7 +347,7 @@ public class MsoLogger { String targetEntity, String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -365,7 +364,7 @@ public class MsoLogger { String arg5, String targetEntity, String targetServiceName) { prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4), + logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4), normalize(arg5)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); @@ -382,7 +381,7 @@ public class MsoLogger { String errorDesc) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg); + logger.warn(msg); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -398,9 +397,9 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg); - errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.warn(msg); + logger.warn("Exception raised: " + getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -416,7 +415,7 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, arg); + logger.warn(msg, arg); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -434,9 +433,9 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, arg); - errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.warn(msg, arg); + logger.warn("Exception raised: " + getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -452,7 +451,7 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1)); + logger.warn(msg, normalize(arg0), normalize(arg1)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -470,9 +469,9 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1)); - errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.warn(msg, normalize(arg0), normalize(arg1)); + logger.warn("Exception raised: " + getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -488,7 +487,7 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -506,9 +505,9 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2)); - errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.warn("Exception raised: " + getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -524,7 +523,7 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -542,9 +541,9 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); - errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.warn("Exception raised: " + getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -560,7 +559,7 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -578,9 +577,9 @@ public class MsoLogger { public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); - errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.warn("Exception raised: " + getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -595,7 +594,7 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg); + logger.error(msg); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -611,9 +610,9 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg); - errorLogger.error(exceptionArg, getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.error(msg); + logger.error(exceptionArg, getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -629,7 +628,7 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0)); + logger.error(msg, normalize(arg0)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -647,9 +646,9 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0)); - errorLogger.error(exceptionArg, getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.error(msg, normalize(arg0)); + logger.error(exceptionArg, getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -665,7 +664,7 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1)); + logger.error(msg, normalize(arg0), normalize(arg1)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -683,9 +682,9 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1)); - errorLogger.error(exceptionArg, getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.error(msg, normalize(arg0), normalize(arg1)); + logger.error(exceptionArg, getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -701,7 +700,7 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -719,9 +718,9 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2)); - errorLogger.error(exceptionArg, getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.error(exceptionArg, getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -737,7 +736,7 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -755,9 +754,9 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); - errorLogger.error(exceptionArg, getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.error(exceptionArg, getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -773,7 +772,7 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } @@ -791,15 +790,15 @@ public class MsoLogger { public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); - errorLogger.error(exceptionArg, getNormalizedStackTrace(t)); - debugLogger.debug("Exception raised", t); + logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.error(exceptionArg, getNormalizedStackTrace(t)); + logger.debug("Exception raised", t); MDC.remove(TARGETENTITY); MDC.remove(TARGETSERVICENAME); } public boolean isDebugEnabled() { - return debugLogger.isDebugEnabled(); + return logger.isDebugEnabled(); } private void prepareMsg(String loggingLevel) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstances.java index 2386848ad5..f33774faef 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstances.java @@ -21,6 +21,7 @@ package org.openecomp.mso.apihandlerinfra; import java.io.IOException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -28,7 +29,6 @@ import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; -import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; @@ -39,6 +39,8 @@ import javax.ws.rs.core.Response; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.codehaus.jackson.map.ObjectMapper; +import org.hibernate.Session; + import org.openecomp.mso.apihandler.common.ErrorNumbers; import org.openecomp.mso.apihandler.common.RequestClient; import org.openecomp.mso.apihandler.common.RequestClientFactory; @@ -51,6 +53,7 @@ import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestInfo; import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestParameters; import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesRequest; import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.SubscriberInfo; +import org.openecomp.mso.db.AbstractSessionFactoryManager; import org.openecomp.mso.db.catalog.CatalogDatabase; import org.openecomp.mso.db.catalog.beans.Service; import org.openecomp.mso.db.catalog.beans.ServiceRecipe; @@ -58,446 +61,483 @@ import org.openecomp.mso.logger.MessageEnum; import org.openecomp.mso.logger.MsoAlarmLogger; import org.openecomp.mso.logger.MsoLogger; import org.openecomp.mso.requestsdb.InfraActiveRequests; +import org.openecomp.mso.requestsdb.OperationStatus; import org.openecomp.mso.requestsdb.RequestsDatabase; +import org.openecomp.mso.requestsdb.RequestsDbSessionFactoryManager; import org.openecomp.mso.utils.UUIDChecker; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; @Path("/e2eServiceInstances") -@Api(value="/e2eServiceInstances",description="API Requests for E2E Service Instances") +@Api(value = "/e2eServiceInstances", description = "API Requests for E2E Service Instances") public class E2EServiceInstances { - private HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH); - private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger (); - public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; - - public E2EServiceInstances() { - } + private HashMap<String, String> instanceIdMap = new HashMap<>(); + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH); + private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + public static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; + private ServiceInstancesRequest sir = null; + public static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: "; + public static final String EXCEPTION_CREATING_DB_RECORD = "Exception while creating record in DB"; + public static final String EXCEPTION_COMMUNICATE_BPMN_ENGINE = "Exception while communicate with BPMN engine"; + /** - *POST Requests for E2E Service create Instance on a version provided - */ + * POST Requests for E2E Service create Instance on a version provided + */ @POST @Path("/{version:[vV][3-5]}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create a E2E Service Instance on a version provided",response=Response.class) + @ApiOperation(value = "Create a E2E Service Instance on a version provided", response = Response.class) public Response createE2EServiceInstance(String request, @PathParam("version") String version) { - return E2EserviceInstances(request, Action.createInstance, null, version); + return processE2EserviceInstances(request, Action.createInstance, null, version); } /** - *DELETE Requests for E2E Service delete Instance on a specified version and serviceId - */ - + * DELETE Requests for E2E Service delete Instance on a specified version + * and serviceId + */ + @DELETE @Path("/{version:[vV][3-5]}/{serviceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete E2E Service Instance on a specified version and serviceId",response=Response.class) - public Response deleteE2EServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceId") String serviceId) { + @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class) + public Response deleteE2EServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceId") String serviceId) { - instanceIdMap.put("serviceId", serviceId); + instanceIdMap.put("serviceId", serviceId); - return E2EserviceInstances(request, Action.deleteInstance, null, version); + return processE2EserviceInstances(request, Action.deleteInstance, null, version); } - - private Response E2EserviceInstances(String requestJSON, Action action, - HashMap<String, String> instanceIdMap, String version) { + + private Response processE2EserviceInstances(String requestJSON, Action action, + HashMap<String, String> instanceIdMap, String version) { String requestId = UUIDChecker.generateUUID(msoLogger); long startTime = System.currentTimeMillis(); msoLogger.debug("requestId is: " + requestId); - E2EServiceInstanceRequest sir = null; + E2EServiceInstanceRequest e2eSir = null; MsoRequest msoRequest = new MsoRequest(requestId); ObjectMapper mapper = new ObjectMapper(); try { - sir = mapper - .readValue(requestJSON, E2EServiceInstanceRequest.class); + e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class); } catch (Exception e) { msoLogger.debug("Mapping of request to JSON object failed : ", e); - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, - "Mapping of request to JSON object failed. " - + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, - null); - msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, - MSO_PROP_APIHANDLER_INFRA, "", "", + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null); + msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e); - msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, - MsoLogger.ResponseCode.SchemaError, + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Mapping of request to JSON object failed"); - msoLogger.debug("End of the transaction, the final response is: " - + (String) response.getEntity()); + msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity()); return response; } - InfraActiveRequests dup = null; - String instanceName = sir.getService().getName(); - String requestScope = sir.getService().getParameters().getNodeType(); + mapReqJsonToSvcInstReq(e2eSir, requestJSON); + sir.getRequestDetails().getRequestParameters().setaLaCarte(true); + try { + msoRequest.parse(sir, instanceIdMap, action, version); + } catch (Exception e) { + msoLogger.debug("Validation failed: ", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Error parsing request. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null); + if (msoRequest.getRequestId() != null) { + msoLogger.debug("Logging failed message to the database"); + msoRequest.createRequestRecord(Status.FAILED, action); + } + msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", + MsoLogger.ErrorCode.SchemaError, requestJSON, e); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, + "Validation of the input request failed"); + msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity()); + return response; + } + InfraActiveRequests dup = null; +// String instanceName = sir.getService().getName(); +// String requestScope = sir.getService().getParameters().getNodeType(); + String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); + String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); try { - if(!(instanceName==null && "service".equals(requestScope) && (action == Action.createInstance || action - == Action.activateInstance))){ - dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope); + if (!(instanceName == null && "service".equals(requestScope) + && (action == Action.createInstance || action == Action.activateInstance))) { + dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate(instanceIdMap, instanceName, + requestScope); } } catch (Exception e) { - msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e); - - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException, - e.getMessage(), - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, - null) ; + msoLogger.error(MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", + MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null); - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Error during duplicate check"); - msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ()); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, + "Error during duplicate check"); + msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity()); return response; } if (dup != null) { // Found the duplicate record. Return the appropriate error. String instance = null; - if(instanceName != null){ + if (instanceName != null) { instance = instanceName; - }else{ + } else { instance = instanceIdMap.get(requestScope + "InstanceId"); } - String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") " + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - " + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding."; - - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException, - dupMessage, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, - null) ; - - - msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, "Duplicate request - Subscriber already has a request for this service"); - msoRequest.createRequestRecord (Status.FAILED, action); - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage); - msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ()); + String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") " + + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - " + + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding."; + + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, + MsoException.ServiceException, dupMessage, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null); + + msoLogger.warn(MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, + "Duplicate request - Subscriber already has a request for this service"); + msoRequest.createRequestRecord(Status.FAILED, action); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, + dupMessage); + msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity()); return response; } - + CatalogDatabase db = null; RecipeLookupResult recipeLookupResult = null; try { db = CatalogDatabase.getInstance(); - recipeLookupResult = getServiceInstanceOrchestrationURI(db, sir, action); + recipeLookupResult = getServiceInstanceOrchestrationURI(db, action); } catch (Exception e) { - msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e); - msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); - Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND, - MsoException.ServiceException, - "No communication to catalog DB " + e.getMessage (), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, - null); - alarmLogger.sendAlarm ("MsoDatabaseAccessError", - MsoAlarmLogger.CRITICAL, - Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB)); - msoRequest.createRequestRecord (Status.FAILED,action); - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB"); - msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ()); + msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", + MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e); + msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null); + alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, + Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB)); + msoRequest.createRequestRecord(Status.FAILED, action); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, + "Exception while communciate with DB"); + msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity()); return response; } finally { - if(db != null) { - db.close(); - } + closeCatalogDB(db); } if (recipeLookupResult == null) { - msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB"); - msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); - Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND, - MsoException.ServiceException, - "Recipe does not exist in catalog DB", - ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, - null); - msoRequest.createRequestRecord (Status.FAILED, action); - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB"); - msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ()); + msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", + MsoLogger.ErrorCode.DataError, "No recipe found in DB"); + msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "Recipe does not exist in catalog DB", + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null); + msoRequest.createRequestRecord(Status.FAILED, action); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, + "No recipe found in DB"); + msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity()); return response; } try { - msoRequest.createRequestRecord (Status.PENDING, action); + msoRequest.createRequestRecord(Status.PENDING, action); + createOperationStatusRecord(action, requestId); } catch (Exception e) { - msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e); - msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); - Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_INTERNAL_SERVER_ERROR, - MsoException.ServiceException, - "Exception while creating record in DB " + e.getMessage(), - ErrorNumbers.SVC_BAD_PARAMETER, - null); - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while creating record in DB"); - msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ()); + msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", + MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e); + msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, "Exception while creating record in DB " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, + "Exception while creating record in DB"); + msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity()); return response; } - String modelInfo = sir.getService().getParameters().getNodeTemplateName(); + String modelInfo = e2eSir.getService().getParameters().getNodeTemplateName(); String[] arrayOfInfo = modelInfo.split(":"); String serviceInstanceType = arrayOfInfo[0]; - - String serviceId = ""; RequestClient requestClient = null; HttpResponse response = null; long subStartTime = System.currentTimeMillis(); - String sirRequestJson = mappingObtainedRequestJSONToServiceInstanceRequest(sir); + String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON); try { - requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), MsoPropertiesUtils.loadMsoProperties ()); + requestClient = RequestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI(), + MsoPropertiesUtils.loadMsoProperties()); // Capture audit event - msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ()); + msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - response = requestClient.post(requestId, false, - recipeLookupResult.getRecipeTimeout(), - action.name(), serviceId, null, null, null, null, serviceInstanceType, - null, null, null, sirRequestJson); + response = requestClient.post(requestId, false, recipeLookupResult.getRecipeTimeout(), action.name(), + serviceId, null, null, null, null, serviceInstanceType, null, null, null, sirRequestJson); - msoLogger.recordMetricEvent(subStartTime, - MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - "Successfully received response from BPMN engine", "BPMN", - recipeLookupResult.getOrchestrationURI(), null); + msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(), + null); } catch (Exception e) { - msoLogger.recordMetricEvent(subStartTime, - MsoLogger.StatusCode.ERROR, - MsoLogger.ResponseCode.CommunicationError, - "Exception while communicate with BPMN engine", "BPMN", + msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR, + MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(), null); - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "Failed calling bpmn " + e.getMessage(), + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null); - alarmLogger.sendAlarm("MsoConfigurationError", - MsoAlarmLogger.CRITICAL, + alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL, Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL)); - msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, - MSO_PROP_APIHANDLER_INFRA, "", "", - MsoLogger.ErrorCode.AvailabilityError, + msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", + MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine"); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine"); - msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, - MsoLogger.ResponseCode.CommunicationError, - "Exception while communicate with BPMN engine"); - msoLogger.debug("End of the transaction, the final response is: " - + (String) resp.getEntity()); + msoLogger.debug("End of the transaction, the final response is: " + (String) resp.getEntity()); return resp; } if (response == null) { - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null); - msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, - MSO_PROP_APIHANDLER_INFRA, "", "", - MsoLogger.ErrorCode.BusinessProcesssError, - "Null response from BPEL"); - msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, - MsoLogger.ResponseCode.InternalError, + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null); + msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", + MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL"); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN"); - msoLogger.debug("End of the transaction, the final response is: " - + (String) resp.getEntity()); + msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity()); return resp; } - ResponseHandler respHandler = new ResponseHandler(response, - requestClient.getType()); + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); int bpelStatus = respHandler.getStatus(); + return beplStatusUpdate(requestId, startTime, msoRequest, requestClient, respHandler, bpelStatus); + } + + private void closeCatalogDB(CatalogDatabase db) { + if (db != null) { + db.close(); + } + } + + private InfraActiveRequests checkForDuplicateRecord(Action action, HashMap<String, String> instanceIdMap, + String instanceName, String requestScope) { + InfraActiveRequests dupValue = null; + if (!(instanceName == null && "service".equals(requestScope) + && (action == Action.createInstance || action == Action.activateInstance))) { + dupValue = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate(instanceIdMap, instanceName, + requestScope); + } + return dupValue; + } + + private Response duplicateRecordFound(Action action, HashMap<String, String> instanceIdMap, long startTime, + MsoRequest msoRequest, InfraActiveRequests dup, String instanceName, String requestScope) { + String instance = null; + if (instanceName != null) { + instance = instanceName; + } else { + instance = instanceIdMap.get(requestScope + "InstanceId"); + } + String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") " + + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - " + + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding."; + + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException, + dupMessage, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null); + + msoLogger.warn(MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, + "Duplicate request - Subscriber already has a request for this service"); + msoRequest.createRequestRecord(Status.FAILED, action); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage); + msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity()); + return response; + } + + private Response beplStatusUpdate(String requestId, long startTime, MsoRequest msoRequest, + RequestClient requestClient, ResponseHandler respHandler, int bpelStatus) { // BPEL accepted the request, the request is in progress if (bpelStatus == HttpStatus.SC_ACCEPTED) { String camundaJSONResponseBody = respHandler.getResponseBody(); - msoLogger - .debug("Received from Camunda: " + camundaJSONResponseBody); - (RequestsDatabase.getInstance()).updateInfraStatus(requestId, - Status.IN_PROGRESS.toString(), - Constants.PROGRESS_REQUEST_IN_PROGRESS, - Constants.MODIFIED_BY_APIHANDLER); - - msoLogger.recordAuditEvent(startTime, - MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + msoLogger.debug("Received from Camunda: " + camundaJSONResponseBody); + (RequestsDatabase.getInstance()).updateInfraStatus(requestId, Status.IN_PROGRESS.toString(), + Constants.PROGRESS_REQUEST_IN_PROGRESS, Constants.MODIFIED_BY_APIHANDLER); + + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN accepted the request, the request is in progress"); - msoLogger.debug("End of the transaction, the final response is: " - + (String) camundaJSONResponseBody); - return Response.status(HttpStatus.SC_ACCEPTED) - .entity(camundaJSONResponseBody).build(); + msoLogger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody); + return Response.status(HttpStatus.SC_ACCEPTED).entity(camundaJSONResponseBody).build(); } else { - List<String> variables = new ArrayList<String>(); + List<String> variables = new ArrayList<>(); variables.add(bpelStatus + ""); String camundaJSONResponseBody = respHandler.getResponseBody(); - if (camundaJSONResponseBody != null - && !camundaJSONResponseBody.isEmpty()) { - 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); - msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR, - requestClient.getUrl(), "", "", + if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) { + 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); + msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, - "Response from BPEL engine is failed with HTTP Status=" - + bpelStatus); - msoLogger.recordAuditEvent(startTime, - MsoLogger.StatusCode.ERROR, - MsoLogger.ResponseCode.InternalError, + "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPMN engine is failed"); - msoLogger - .debug("End of the transaction, the final response is: " - + (String) resp.getEntity()); + msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity()); return resp; } else { - Response resp = msoRequest - .buildServiceErrorResponse( - bpelStatus, - MsoException.ServiceException, - "Request Failed due to BPEL error with HTTP Status= %1", - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, - variables); - msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR, - requestClient.getUrl(), "", "", - MsoLogger.ErrorCode.BusinessProcesssError, - "Response from BPEL engine is empty"); - msoLogger.recordAuditEvent(startTime, - MsoLogger.StatusCode.ERROR, - MsoLogger.ResponseCode.InternalError, + Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, + "Request Failed due to BPEL error with HTTP Status= %1", + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables); + msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl(), "", "", + MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty"); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty"); - msoLogger - .debug("End of the transaction, the final response is: " - + (String) resp.getEntity()); + msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity()); return resp; } } } - private RecipeLookupResult getServiceInstanceOrchestrationURI( - CatalogDatabase db, E2EServiceInstanceRequest sir, Action action) { - - RecipeLookupResult recipeLookupResult = null; + /** + * Getting recipes from catalogDb + * + * @param db + * @param action + * @return + */ + private RecipeLookupResult getServiceInstanceOrchestrationURI(CatalogDatabase db, Action action) { - recipeLookupResult = getServiceURI(db, sir, action); + RecipeLookupResult recipeLookupResult = getServiceURI(db, action); if (recipeLookupResult != null) { - msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ())); - } - else { + msoLogger.debug("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout())); + } else { msoLogger.debug("No matching recipe record found"); } return recipeLookupResult; } - private RecipeLookupResult getServiceURI(CatalogDatabase db, - E2EServiceInstanceRequest sir, Action action) { + /** + * Getting recipes from catalogDb + * + * @param db + * @param action + * @return + */ + private RecipeLookupResult getServiceURI(CatalogDatabase db, Action action) { String defaultServiceModelName = "UUI_DEFAULT"; - Service serviceRecord = null; - ServiceRecipe recipe = null; - - serviceRecord = db.getServiceByModelName(defaultServiceModelName); - recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name()); + Service serviceRecord = db.getServiceByModelName(defaultServiceModelName); + ServiceRecipe recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name()); if (recipe == null) { return null; } - return new RecipeLookupResult(recipe.getOrchestrationUri(), - recipe.getRecipeTimeout()); + return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()); } - private String mappingObtainedRequestJSONToServiceInstanceRequest(E2EServiceInstanceRequest e2eSir){ + /** + * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and + * passing it to camunda engine. + * + * @param e2eSir + * @return + */ + private String mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir, String requestJSON) { - ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir = new ServiceInstancesRequest(); String returnString = null; RequestDetails requestDetails = new RequestDetails(); ModelInfo modelInfo = new ModelInfo(); - - //ModelInvariantId + + // ModelInvariantId modelInfo.setModelInvariantId(e2eSir.getService().getServiceDefId()); - - //modelNameVersionId + + // modelNameVersionId modelInfo.setModelNameVersionId(e2eSir.getService().getTemplateId()); - + String modelInfoValue = e2eSir.getService().getParameters().getNodeTemplateName(); String[] arrayOfInfo = modelInfoValue.split(":"); String modelName = arrayOfInfo[0]; String modelVersion = arrayOfInfo[1]; - - //modelName + + // modelName modelInfo.setModelName(modelName); - - //modelVersion + + // modelVersion modelInfo.setModelVersion(modelVersion); - - //modelType - //if(ModelType.service.equals(e2eSir.getService().getParameters().getNodeType())){ - modelInfo.setModelType(ModelType.service); - //} - - //setting modelInfo to requestDetails + + // modelType + modelInfo.setModelType(ModelType.service); + + // setting modelInfo to requestDetails requestDetails.setModelInfo(modelInfo); - + SubscriberInfo subscriberInfo = new SubscriberInfo(); - //globalsubscriberId + // globalsubscriberId subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getParameters().getGlobalSubscriberId()); - //subscriberName + // subscriberName subscriberInfo.setSubscriberName(e2eSir.getService().getParameters().getSubscriberName()); - - //setting subscriberInfo to requestDetails + + // setting subscriberInfo to requestDetails requestDetails.setSubscriberInfo(subscriberInfo); - + RequestInfo requestInfo = new RequestInfo(); - - //instanceName + + // instanceName requestInfo.setInstanceName(e2eSir.getService().getName()); - //source + // source requestInfo.setSource("UUI"); - //suppressRollback + // suppressRollback requestInfo.setSuppressRollback(true); - //setting requestInfo to requestDetails + // setting requestInfo to requestDetails requestDetails.setRequestInfo(requestInfo); - + RequestParameters requestParameters = new RequestParameters(); - - //subscriptionServiceType + + // subscriptionServiceType requestParameters.setSubscriptionServiceType("MOG"); - //Userparams + // Userparams List<E2EUserParam> userParams; userParams = e2eSir.getService().getParameters().getRequestParameters().getUserParams(); List<Map<String, String>> userParamList = new ArrayList<>(); - Map<String,String> userParamMap= new HashMap<>(); - for(E2EUserParam userp: userParams){ + Map<String, String> 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); - - //setting requestParameters to requestDetails + + // setting requestParameters to requestDetails requestDetails.setRequestParameters(requestParameters); - + sir.setRequestDetails(requestDetails); - //converting to string + // converting to string ObjectMapper mapper = new ObjectMapper(); try { returnString = mapper.writeValueAsString(sir); @@ -507,4 +547,42 @@ public class E2EServiceInstances { return returnString; } + + private void createOperationStatusRecord(Action action, String requestId) { + { + AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager(); + + Session session = null; + try { + + session = requestsDbSessionFactoryManager.getSessionFactory().openSession(); + session.beginTransaction(); + + // if (null == sir) { + // sir = new ServiceInstancesRequest(); + // } + OperationStatus os = new OperationStatus(); + os.setOperation(action.name()); + os.setOperationContent(""); + os.setOperationId(""); + os.setProgress("0"); + os.setReason(""); + os.setResult("Processing"); + os.setServiceId(requestId); + os.setUserId(""); + os.setFinishedAt(new Timestamp(System.currentTimeMillis())); + os.setOperateAt(new Timestamp(System.currentTimeMillis())); + + session.save(os); + session.getTransaction().commit(); + + } catch (Exception e) { + msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception when creation record request in Operation", e); + } finally { + if (null != session) { + session.close(); + } + } + } + } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstancesTest.java index 98a2a11800..b247d81d7f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/E2EServiceInstancesTest.java @@ -111,7 +111,7 @@ public class E2EServiceInstancesTest { };
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("Exception while creating record in DB null") != -1);
@@ -175,7 +175,7 @@ public class E2EServiceInstancesTest { };
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("Exception while creating record in DB null") != -1);
@@ -239,7 +239,7 @@ public class E2EServiceInstancesTest { };
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("Exception while creating record in DB null") != -1);
@@ -291,7 +291,7 @@ public class E2EServiceInstancesTest { };
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("Exception while creating record in DB null") != -1);
@@ -340,7 +340,7 @@ public class E2EServiceInstancesTest { };
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("Exception while creating record in DB null") != -1);
@@ -370,7 +370,7 @@ public class E2EServiceInstancesTest { }
};
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("Exception while creating record in DB null") != -1);
@@ -401,7 +401,7 @@ public class E2EServiceInstancesTest { }
};
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
//assertTrue(respStr.indexOf("Recipe could not be retrieved from catalog DB ") !=-1);
@@ -422,7 +422,7 @@ public class E2EServiceInstancesTest { }
};
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("The existing request must finish or be cleaned up before proceeding.") != -1);
@@ -437,7 +437,7 @@ public class E2EServiceInstancesTest { }
};
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
//assertTrue(respStr.indexOf("Recipe could not be retrieved from catalog DB ") != -1);
@@ -447,7 +447,7 @@ public class E2EServiceInstancesTest { @Test
public void createE2EServiceInstanceTestDBQueryFail(){
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.createE2EServiceInstance(request, "v3");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("SVC2000") != -1);
@@ -465,7 +465,7 @@ public class E2EServiceInstancesTest { @Test
public void deleteE2EServiceInstanceTestNormal(){
E2EServiceInstances instance = new E2EServiceInstances();
- String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"modelInvariantId value from SDC?\",\"templateId\":\"modelVersionId value from SDC??\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"NEED THIS UUI - AAI\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
+ String request = "{\"service\":{\"name\":\"service\",\"description\":\"so_test1\",\"serviceDefId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"templateId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"parameters\":{\"domainHost\":\"localhost\",\"nodeTemplateName\":\"modelName:v3\",\"nodeType\":\"service\",\"globalSubscriberId\":\"4050083f-465f-4838-af1e-47a545222ad1\",\"subscriberName\":\"NEED THIS UUI - AAI\",\"requestParameters\":{\"subscriptionServiceType\":\"MOG\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"},{\"name\":\"segments\",\"value\":\"value\"},{\"name\":\"nsParameters\",\"value\":\"othervalue\"}]}}}}";
Response resp = instance.deleteE2EServiceInstance(request, "v3", "12345678");
String respStr = resp.getEntity().toString();
assertTrue(respStr.indexOf("SVC2000") != -1);
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/OperationStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/OperationStatus.java index 010b79d38d..796a3f90fe 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/OperationStatus.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/OperationStatus.java @@ -19,6 +19,7 @@ */
package org.openecomp.mso.requestsdb;
+import java.io.Serializable;
import java.sql.Timestamp;
/**
@@ -30,8 +31,13 @@ import java.sql.Timestamp; * @author
* @version ONAP Amsterdam Release 2017-08-28
*/
-public class OperationStatus {
+public class OperationStatus implements Serializable{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
private String serviceId;
private String operationId;
@@ -152,4 +158,51 @@ public class OperationStatus { this.finishedAt = finishedAt;
}
+
+ /**
+ * <br>
+ *
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((operationId == null) ? 0 : operationId.hashCode());
+ result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());
+ return result;
+ }
+
+
+ /**
+ * <br>
+ *
+ * @param obj
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if(this == obj)
+ return true;
+ if(obj == null)
+ return false;
+ if(getClass() != obj.getClass())
+ return false;
+ OperationStatus other = (OperationStatus)obj;
+ if(operationId == null) {
+ if(other.operationId != null)
+ return false;
+ } else if(!operationId.equals(other.operationId))
+ return false;
+ if(serviceId == null) {
+ if(other.serviceId != null)
+ return false;
+ } else if(!serviceId.equals(other.serviceId))
+ return false;
+ return true;
+ }
+
+
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDatabase.java b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDatabase.java index b426c39176..c6f0cea993 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDatabase.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDatabase.java @@ -647,7 +647,7 @@ public class RequestsDatabase { + operStatus.getResourceTemplateUUID()); try { String hql = - "FROM ResourceOperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id and RESOURCE_TEMPLATE_UUID = : res_uuid"; + "FROM ResourceOperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id and RESOURCE_TEMPLATE_UUID = :res_uuid"; Query query = session.createQuery(hql); query.setParameter("service_id", operStatus.getServiceId()); query.setParameter("operation_id", operStatus.getOperationId()); diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/ResourceOperationStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/ResourceOperationStatus.java index 298eb9cf4b..2e91397d14 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/ResourceOperationStatus.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/ResourceOperationStatus.java @@ -19,6 +19,8 @@ */
package org.openecomp.mso.requestsdb;
+import java.io.Serializable;
+
/**
* The Resource operation status
* <br>
@@ -28,7 +30,12 @@ package org.openecomp.mso.requestsdb; * @author
* @version ONAP Amsterdam Release 2017-08-28
*/
-public class ResourceOperationStatus {
+public class ResourceOperationStatus implements Serializable{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
private String serviceId;
@@ -161,6 +168,55 @@ public class ResourceOperationStatus { public void setOperType(String operType) {
this.operType = operType;
}
-
+
+ /**
+ * <br>
+ *
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((operationId == null) ? 0 : operationId.hashCode());
+ result = prime * result + ((resourceTemplateUUID == null) ? 0 : resourceTemplateUUID.hashCode());
+ result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());
+ return result;
+ }
+
+ /**
+ * <br>
+ *
+ * @param obj
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if(this == obj)
+ return true;
+ if(obj == null)
+ return false;
+ if(getClass() != obj.getClass())
+ return false;
+ ResourceOperationStatus other = (ResourceOperationStatus)obj;
+ if(operationId == null) {
+ if(other.operationId != null)
+ return false;
+ } else if(!operationId.equals(other.operationId))
+ return false;
+ if(resourceTemplateUUID == null) {
+ if(other.resourceTemplateUUID != null)
+ return false;
+ } else if(!resourceTemplateUUID.equals(other.resourceTemplateUUID))
+ return false;
+ if(serviceId == null) {
+ if(other.serviceId != null)
+ return false;
+ } else if(!serviceId.equals(other.serviceId))
+ return false;
+ return true;
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/resources/OperationStatus.hbm.xml b/mso-api-handlers/mso-requests-db/src/main/resources/OperationStatus.hbm.xml index f00c2da408..8d80f76649 100644 --- a/mso-api-handlers/mso-requests-db/src/main/resources/OperationStatus.hbm.xml +++ b/mso-api-handlers/mso-requests-db/src/main/resources/OperationStatus.hbm.xml @@ -28,8 +28,10 @@ <meta attribute="class-description"> This class describes a operation status </meta> - <id name="serviceId" type="string" column="SERVICE_ID"/> - <id name="operationId" column="OPERATION_ID" type="string" length="256"/> + <composite-id> + <key-property name="serviceId" type="string" column="SERVICE_ID"/> + <key-property name="operationId" column="OPERATION_ID" type="string" length="256"/> + </composite-id> <property name="operation" column="OPERATION_TYPE" type="string" length="256"/> <property name="userId" column="USER_ID" type="string" length="256"/> <property name="result" column="RESULT" type="string" length="256"/> @@ -39,6 +41,6 @@ <property name="operateAt" type="timestamp" generated="insert" insert="false" update="false" not-null="true"> <column name="OPERATE_AT" default="CURRENT_TIMESTAMP"/> </property> - <property name="finishedAt" column="FINISHED_AT" type="timestamp" generated="update" insert="false" update="false"/> + <property name="finishedAt" column="FINISHED_AT" type="timestamp" generated="always" insert="false" update="false"/> </class> </hibernate-mapping> diff --git a/mso-api-handlers/mso-requests-db/src/main/resources/ResourceOperationStatus.hbm.xml b/mso-api-handlers/mso-requests-db/src/main/resources/ResourceOperationStatus.hbm.xml index 87e23980d6..22d147402d 100644 --- a/mso-api-handlers/mso-requests-db/src/main/resources/ResourceOperationStatus.hbm.xml +++ b/mso-api-handlers/mso-requests-db/src/main/resources/ResourceOperationStatus.hbm.xml @@ -28,9 +28,11 @@ <meta attribute="class-description"> This class describes a progress status </meta> - <id name="serviceId" type="string" column="SERVICE_ID"/> - <id name="operationId" column="OPERATION_ID" type="string" length="256"/> - <id name="resourceTemplateUUID" type="string" column="RESOURCE_TEMPLATE_UUID"/> + <composite-id> + <key-property name="serviceId" type="string" column="SERVICE_ID"/> + <key-property name="operationId" type="string" column="OPERATION_ID" length="256"/> + <key-property name="resourceTemplateUUID" type="string" column="RESOURCE_TEMPLATE_UUID"/> + </composite-id> <property name="operType" column="OPER_TYPE" type="string" length="256"/> <property name="resourceInstanceID" column="RESOURCE_INSTANCE_ID" type="string" length="256"/> <property name="jobId" column="JOB_ID" type="string" length="256"/> diff --git a/mso-api-handlers/mso-requests-db/src/main/resources/hibernate-requests-core-mysql.cfg.xml b/mso-api-handlers/mso-requests-db/src/main/resources/hibernate-requests-core-mysql.cfg.xml index 531b77196c..edf8333016 100644 --- a/mso-api-handlers/mso-requests-db/src/main/resources/hibernate-requests-core-mysql.cfg.xml +++ b/mso-api-handlers/mso-requests-db/src/main/resources/hibernate-requests-core-mysql.cfg.xml @@ -33,5 +33,7 @@ <mapping resource="InfraActiveRequests.hbm.xml"></mapping> <mapping resource="SiteStatus.hbm.xml"></mapping> + <mapping resource="OperationStatus.hbm.xml"></mapping> + <mapping resource="ResourceOperationStatus.hbm.xml"></mapping> </session-factory> </hibernate-configuration> diff --git a/packages/arquillian-unit-tests/src/test/resources/docker/mso/mso-docker.json b/packages/arquillian-unit-tests/src/test/resources/docker/mso/mso-docker.json index 3d24819c2f..c6fc555418 100644 --- a/packages/arquillian-unit-tests/src/test/resources/docker/mso/mso-docker.json +++ b/packages/arquillian-unit-tests/src/test/resources/docker/mso/mso-docker.json @@ -173,7 +173,8 @@ "aaiEndpoint": "http://mso:8080/aai-emul", "adaptersCompletemsoprocessEndpoint": "http://mso:8080/CompleteMsoProcess", "adaptersNamespace": "http://org.openecomp.mso", - "adaptersDbEndpoint": "http://mso:8080/dbadapters/RequestsDbAdapter", + "adaptersDbEndpoint": "http://mso:8080/dbadapters/MsoRequestsDbAdapter", + "adaptersOpenecompDbEndpoint": "http://mso:8080/dbadapters/RequestsDbAdapter", "adaptersSdncEndpoint": "http://mso:8080/adapters/SDNCAdapter", "adaptersTenantEndpoint": "http://mso:8080/tenants/TenantAdapter", "adaptersDbAuth": "6B0E6863FB8EE010AB6F191B3C0489437601E81DC7C86305CB92DB98AFC53D74", @@ -116,7 +116,7 @@ Change the environment file located here : **/shared/mso-docker.json** then run Here are the main parameters you could change: - mso_config_path: define the path where the configuration files for APIH, JRA and Camunda will be deployed. This parameter should not be changed. -- In the section mso-bpmn-urn-config, adaptersDbEndpoint: This configuration must point to the APIH hostname. It should have this form: http://mso:8080/dbadapters/RequestsDbAdapter Do not change it if you are not sure. +- In the section mso-bpmn-urn-config, adaptersOpenecompDbEndpoint: This configuration must point to the APIH hostname. It should have this form: http://mso:8080/dbadapters/RequestsDbAdapter Do not change it if you are not sure. - In the section mso-bpmn-urn-config, aaiEndpoint: This parameter should point to the A&AI component. It should be something like: https://c1.vm1.aai.simpledemo.opap.org:8443 - In the section mso-bpmn-urn-config, aaiAuth: This parameter is the encrypted value of login:password to access the A&AI server. The key used to encrypt is defined in the parameter msoKey. - In the section asdc-connection, asdcAddresss: Change the values with the value provided by the ASDC team. Possible value: https://c2.vm1.sdc.simpledemo.onap.org:8443 The password field may be changed as well. |