Deal With Error Response from Vfc 17/19417/4
authorc00149107 <chenchuanyu@huawei.com>
Wed, 18 Oct 2017 03:48:21 +0000 (11:48 +0800)
committerc00149107 <chenchuanyu@huawei.com>
Thu, 19 Oct 2017 06:12:16 +0000 (14:12 +0800)
Deal With Error Response from Vfc

Change-Id: Id5ce999d561099581b49524969c901ac6dac3f90
Issue-ID:SO-233
Signed-off-by: c00149107 <chenchuanyu@huawei.com>
18 files changed:
adapters/mso-vfc-adapter/WebContent/WEB-INF/jboss-deployment-structure.xml
adapters/mso-vfc-adapter/WebContent/WEB-INF/web.xml
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/AaiUtil.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcAdapterRest.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/VfcManager.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/LocationConstraint.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NSResourceInputParameter.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsOperationKey.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/VimLocation.java [new file with mode: 0644]
adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java
adapters/mso-vfc-adapter/src/test/java/org/openecomp/mso/adapters/vfc/VfcAdapterTest.java
mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/OperationStatus.java
mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDatabase.java
mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/ResourceOperationStatus.java
mso-api-handlers/mso-requests-db/src/main/resources/OperationStatus.hbm.xml
mso-api-handlers/mso-requests-db/src/main/resources/ResourceOperationStatus.hbm.xml
mso-api-handlers/mso-requests-db/src/main/resources/hibernate-requests-core-mysql.cfg.xml

index e7bc08a..fb26891 100644 (file)
@@ -1,17 +1,21 @@
 <jboss-deployment-structure>\r
        <deployment>\r
-               <!-- Exclusions allow you to prevent the server from automatically adding \r
-                       some dependencies -->\r
+               <!-- Exclusions allow you to prevent the server from automatically adding some dependencies -->\r
                <exclusions>\r
                        <module name="org.apache.log4j" />\r
                        <module name="org.slf4j" />\r
                        <module name="org.slf4j.impl" />\r
+                       <module name="org.jboss.resteasy.resteasy-jackson-provider" />\r
+                       <module name="org.jboss.resteasy.resteasy-jettison-provider" />\r
                </exclusions>\r
                <dependencies>\r
-                       <module name="org.jboss.jandex" slot="main" />\r
-                       <module name="org.javassist" slot="main" />\r
-                       <module name="org.antlr" slot="main" />\r
-                       <module name="org.dom4j" slot="main" />\r
+                           <module name="org.jboss.jandex" slot="main" />\r
+                <module name="org.javassist" slot="main" />\r
+                <module name="org.antlr" slot="main" />\r
+                <module name="org.dom4j" slot="main" />\r
+                <module name="org.jboss.resteasy.resteasy-jackson2-provider" services="import" />\r
+                <!-- This module contain the ProviderBase class: -->\r
+                <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" export="true" />\r
                </dependencies>\r
        </deployment>\r
-</jboss-deployment-structure>
\ No newline at end of file
+</jboss-deployment-structure>\r
index 0c198de..cd97471 100644 (file)
        </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>
@@ -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>
index 719385f..7f1a6da 100644 (file)
@@ -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;
   }
 
index 6c2ab4d..ef3c1b7 100644 (file)
@@ -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();
+    }
 }
index fed6d5e..e3297ff 100644 (file)
@@ -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);
index 8b259e9..214451b 100644 (file)
@@ -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;
     }
 
index f88a11d..1f16606 100644 (file)
  */
 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 "";
+        }
+    }
 }
index e4d6d66..23bf36f 100644 (file)
@@ -17,6 +17,7 @@
  * limitations under the License.\r
  * ============LICENSE_END=========================================================\r
  */\r
+\r
 package org.openecomp.mso.adapters.vfc.model;\r
 \r
 /**\r
@@ -26,20 +27,20 @@ package org.openecomp.mso.adapters.vfc.model;
  * </p>\r
  * \r
  * @author\r
- * @version     ONAP Amsterdam Release  2017-09-15\r
+ * @version ONAP Amsterdam Release 2017-09-15\r
  */\r
 public class NsOperationKey {\r
-    \r
+\r
     /**\r
      * The subscriber id\r
      */\r
     private String globalSubscriberId;\r
-    \r
+\r
     /**\r
      * The serviceType\r
      */\r
     private String serviceType;\r
-    \r
+\r
     /**\r
      * The service ID\r
      */\r
@@ -49,15 +50,12 @@ public class NsOperationKey {
      * The Operation ID\r
      */\r
     private String operationId;\r
-    \r
+\r
     /**\r
      * the NS template uuid\r
      */\r
     private String nodeTemplateUUID;\r
 \r
-    \r
-    \r
-    \r
     /**\r
      * @return Returns the globalSubscriberId.\r
      */\r
@@ -65,14 +63,13 @@ public class NsOperationKey {
         return globalSubscriberId;\r
     }\r
 \r
-    \r
     /**\r
      * @param globalSubscriberId The globalSubscriberId to set.\r
      */\r
     public void setGlobalSubscriberId(String globalSubscriberId) {\r
         this.globalSubscriberId = globalSubscriberId;\r
     }\r
-    \r
+\r
     /**\r
      * @return Returns the serviceType.\r
      */\r
@@ -80,8 +77,6 @@ public class NsOperationKey {
         return serviceType;\r
     }\r
 \r
-\r
-    \r
     /**\r
      * @param serviceType The serviceType to set.\r
      */\r
@@ -89,9 +84,7 @@ public class NsOperationKey {
         this.serviceType = serviceType;\r
     }\r
 \r
-\r
     /**\r
-     * \r
      * <br>\r
      * \r
      * @return\r
@@ -102,7 +95,6 @@ public class NsOperationKey {
     }\r
 \r
     /**\r
-     *     \r
      * <br>\r
      * \r
      * @param serviceId\r
@@ -113,7 +105,6 @@ public class NsOperationKey {
     }\r
 \r
     /**\r
-     * \r
      * <br>\r
      * \r
      * @return\r
@@ -124,7 +115,6 @@ public class NsOperationKey {
     }\r
 \r
     /**\r
-     * \r
      * <br>\r
      * \r
      * @param operationId\r
@@ -134,7 +124,6 @@ public class NsOperationKey {
         this.operationId = operationId;\r
     }\r
 \r
-    \r
     /**\r
      * @return Returns the nodeTemplateUUID.\r
      */\r
@@ -142,7 +131,6 @@ public class NsOperationKey {
         return nodeTemplateUUID;\r
     }\r
 \r
-    \r
     /**\r
      * @param nodeTemplateUUID The nodeTemplateUUID to set.\r
      */\r
index 79d770b..2a5c305 100644 (file)
@@ -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/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/VimLocation.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/VimLocation.java
new file mode 100644 (file)
index 0000000..3c07f9c
--- /dev/null
@@ -0,0 +1,50 @@
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * ONAP - SO\r
+ * ================================================================================\r
+ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+package org.openecomp.mso.adapters.vfc.model;\r
+\r
+/**\r
+ * \r
+ * <br>\r
+ * <p>\r
+ * </p>\r
+ * \r
+ * @author\r
+ * @version     ONAP Amsterdam Release  2017-10-18\r
+ */\r
+public class VimLocation {\r
+    private String vimId;\r
+\r
+    \r
+    /**\r
+     * @return Returns the vimId.\r
+     */\r
+    public String getVimId() {\r
+        return vimId;\r
+    }\r
+\r
+    \r
+    /**\r
+     * @param vimId The vimId to set.\r
+     */\r
+    public void setVimId(String vimId) {\r
+        this.vimId = vimId;\r
+    }\r
+    \r
+}\r
index 85065c0..fda95ac 100644 (file)
  * 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 = 60;
+
+    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;
+    // }
 
 }
index 84991d7..95d3bf6 100644 (file)
@@ -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;
-  }
 }
index 010b79d..796a3f9 100644 (file)
@@ -19,6 +19,7 @@
  */\r
 package org.openecomp.mso.requestsdb;\r
 \r
+import java.io.Serializable;\r
 import java.sql.Timestamp;\r
 \r
 /**\r
@@ -30,8 +31,13 @@ import java.sql.Timestamp;
  * @author\r
  * @version     ONAP Amsterdam Release  2017-08-28\r
  */\r
-public class OperationStatus {\r
+public class OperationStatus implements Serializable{\r
     \r
+    /**\r
+     * \r
+     */\r
+    private static final long serialVersionUID = 1L;\r
+\r
     private String serviceId;\r
     \r
     private String operationId;\r
@@ -152,4 +158,51 @@ public class OperationStatus {
         this.finishedAt = finishedAt;\r
     }\r
 \r
+\r
+    /**\r
+     * <br>\r
+     * \r
+     * @return\r
+     * @since   ONAP Amsterdam Release \r
+     */\r
+    @Override\r
+    public int hashCode() {\r
+        final int prime = 31;\r
+        int result = 1;\r
+        result = prime * result + ((operationId == null) ? 0 : operationId.hashCode());\r
+        result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());\r
+        return result;\r
+    }\r
+\r
+\r
+    /**\r
+     * <br>\r
+     * \r
+     * @param obj\r
+     * @return\r
+     * @since   ONAP Amsterdam Release \r
+     */\r
+    @Override\r
+    public boolean equals(Object obj) {\r
+        if(this == obj)\r
+            return true;\r
+        if(obj == null)\r
+            return false;\r
+        if(getClass() != obj.getClass())\r
+            return false;\r
+        OperationStatus other = (OperationStatus)obj;\r
+        if(operationId == null) {\r
+            if(other.operationId != null)\r
+                return false;\r
+        } else if(!operationId.equals(other.operationId))\r
+            return false;\r
+        if(serviceId == null) {\r
+            if(other.serviceId != null)\r
+                return false;\r
+        } else if(!serviceId.equals(other.serviceId))\r
+            return false;\r
+        return true;\r
+    }\r
+\r
+\r
 }\r
index b426c39..c6f0cea 100644 (file)
@@ -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());
index 298eb9c..2e91397 100644 (file)
@@ -19,6 +19,8 @@
  */\r
 package org.openecomp.mso.requestsdb;\r
 \r
+import java.io.Serializable;\r
+\r
 /**\r
  * The Resource operation status\r
  * <br>\r
@@ -28,7 +30,12 @@ package org.openecomp.mso.requestsdb;
  * @author\r
  * @version     ONAP Amsterdam Release  2017-08-28\r
  */\r
-public class ResourceOperationStatus {\r
+public class ResourceOperationStatus implements Serializable{\r
+\r
+    /**\r
+     * \r
+     */\r
+    private static final long serialVersionUID = 1L;\r
 \r
     private String serviceId;\r
     \r
@@ -161,6 +168,55 @@ public class ResourceOperationStatus {
     public void setOperType(String operType) {\r
         this.operType = operType;\r
     }\r
-    \r
+\r
+    /**\r
+     * <br>\r
+     * \r
+     * @return\r
+     * @since   ONAP Amsterdam Release \r
+     */\r
+    @Override\r
+    public int hashCode() {\r
+        final int prime = 31;\r
+        int result = 1;\r
+        result = prime * result + ((operationId == null) ? 0 : operationId.hashCode());\r
+        result = prime * result + ((resourceTemplateUUID == null) ? 0 : resourceTemplateUUID.hashCode());\r
+        result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * <br>\r
+     * \r
+     * @param obj\r
+     * @return\r
+     * @since   ONAP Amsterdam Release \r
+     */\r
+    @Override\r
+    public boolean equals(Object obj) {\r
+        if(this == obj)\r
+            return true;\r
+        if(obj == null)\r
+            return false;\r
+        if(getClass() != obj.getClass())\r
+            return false;\r
+        ResourceOperationStatus other = (ResourceOperationStatus)obj;\r
+        if(operationId == null) {\r
+            if(other.operationId != null)\r
+                return false;\r
+        } else if(!operationId.equals(other.operationId))\r
+            return false;\r
+        if(resourceTemplateUUID == null) {\r
+            if(other.resourceTemplateUUID != null)\r
+                return false;\r
+        } else if(!resourceTemplateUUID.equals(other.resourceTemplateUUID))\r
+            return false;\r
+        if(serviceId == null) {\r
+            if(other.serviceId != null)\r
+                return false;\r
+        } else if(!serviceId.equals(other.serviceId))\r
+            return false;\r
+        return true;\r
+    }   \r
     \r
 }\r
index f00c2da..8d80f76 100644 (file)
                <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>
index 87e2398..22d1474 100644 (file)
                <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"/>
index 531b771..edf8333 100644 (file)
@@ -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>