Add Operation Status DB info

Add Operation Status DB And Interfaces for create/delete progress rest

Change-Id: I1b93f219470b79b0b7e0bdcbb27a0a31408bbf5f
Issue-ID:SO-41
Signed-off-by: c00149107 <chenchuanyu@huawei.com>
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
new file mode 100644
index 0000000..010b79d
--- /dev/null
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/OperationStatus.java
@@ -0,0 +1,155 @@
+/*-

+ * ============LICENSE_START=======================================================

+ * ONAP - SO

+ * ================================================================================

+ * 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.requestsdb;

+

+import java.sql.Timestamp;

+

+/**

+ * The service operation status 

+ * <br>

+ * <p>

+ * </p>

+ * 

+ * @author

+ * @version     ONAP Amsterdam Release  2017-08-28

+ */

+public class OperationStatus {

+    

+    private String serviceId;

+    

+    private String operationId;

+    

+    private String operation;

+    

+    private String userId;

+    

+    private String result;

+    

+    private String operationContent;

+    

+    private String progress = "0";

+    

+    private String reason;

+

+    private Timestamp operateAt;

+    

+    private Timestamp finishedAt;

+

+    

+    public String getServiceId() {

+        return serviceId;

+    }

+

+    

+    public void setServiceId(String serviceId) {

+        this.serviceId = serviceId;

+    }

+

+    

+    public String getOperationId() {

+        return operationId;

+    }

+

+    

+    public void setOperationId(String operationId) {

+        this.operationId = operationId;

+    }

+

+    

+    public String getOperation() {

+        return operation;

+    }

+

+    

+    public void setOperation(String operation) {

+        this.operation = operation;

+    }

+

+    

+    public String getUserId() {

+        return userId;

+    }

+

+    

+    public void setUserId(String userId) {

+        this.userId = userId;

+    }

+

+    

+    public String getResult() {

+        return result;

+    }

+

+    

+    public void setResult(String result) {

+        this.result = result;

+    }

+

+    

+    public String getOperationContent() {

+        return operationContent;

+    }

+

+    

+    public void setOperationContent(String operationContent) {

+        this.operationContent = operationContent;

+    }

+

+    

+    public String getProgress() {

+        return progress;

+    }

+

+    

+    public void setProgress(String progress) {

+        this.progress = progress;

+    }

+

+    

+    public String getReason() {

+        return reason;

+    }

+

+    

+    public void setReason(String reason) {

+        this.reason = reason;

+    }

+

+    

+    public Timestamp getOperateAt() {

+        return operateAt;

+    }

+

+    

+    public void setOperateAt(Timestamp operateAt) {

+        this.operateAt = operateAt;

+    }

+

+    

+    public Timestamp getFinishedAt() {

+        return finishedAt;

+    }

+

+    

+    public void setFinishedAt(Timestamp finishedAt) {

+        this.finishedAt = finishedAt;

+    }

+

+}

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 3824df0..a08f7cb 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
@@ -23,7 +23,6 @@
 import java.sql.Timestamp;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
@@ -484,4 +483,205 @@
         }
     }
 
+    /**
+     * get the operation progress
+     * <br>
+     * 
+     * @param serviceId the serviceId
+     * @param operationId the operation id 
+     * @return current progress of the operation
+     * @since ONAP Amsterdam Release
+     */
+    public static OperationStatus getOperationStatus(String serviceId, String operationId) {
+
+        long startTime = System.currentTimeMillis();
+        msoLogger.debug("Execute query on infra active request table");
+
+        OperationStatus operStatus = null;
+        Session session = hibernateUtils.getSessionFactory().openSession();
+        try {
+            session.beginTransaction();
+            String hql = "FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id";
+            Query query = session.createQuery(hql);
+            query.setParameter("service_id", serviceId);
+            query.setParameter("operation_id", operationId);
+            operStatus = (OperationStatus)query.uniqueResult();
+
+        } finally {
+            if(session != null && session.isOpen()) {
+                session.close();
+            }
+            msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
+                    "Successfully", "RequestDB", "getOperationStatus", null);
+        }
+        return operStatus;
+    }
+    
+    /**
+     * update the operation status
+     * <br>
+     * 
+     * @param operstatus the operation object
+     * @since ONAP Amsterdam Release
+     */
+    public static void updateOperationStatus(OperationStatus operstatus) {
+        Session session = hibernateUtils.getSessionFactory().openSession();
+        session.beginTransaction();
+
+        long startTime = System.currentTimeMillis();
+        msoLogger.debug("Request database - save Operation Status with service Id:" + operstatus.getServiceId()
+                + ", operationId:" + operstatus.getOperationId());
+        try {
+            String hql =
+                    "FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id";
+            Query query = session.createQuery(hql);
+            query.setParameter("service_id", operstatus.getServiceId());
+            query.setParameter("operation_id", operstatus.getOperationId());
+            OperationStatus exsitingStatus = (OperationStatus)query.uniqueResult();
+            if(exsitingStatus == null) {
+                session.save(operstatus);
+            } else {
+                session.merge(operstatus);
+            }
+            session.getTransaction().commit();
+        } finally {
+            if(session != null && session.isOpen()) {
+                session.close();
+            }
+            msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
+                    "Successfully", "RequestDB", "updateOperationStatus", null);
+        }
+    }
+
+    /**
+     * get a operation status of a resource
+     * <br>
+     * 
+     * @param serviceId the service Id
+     * @param operationId the operation id
+     * @param resourceTemplateUUID the resource template uuid
+     * @return the progress status of a resource
+     * @since ONAP Amsterdam Release
+     */
+    public static ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId,
+            String resourceTemplateUUID) {
+        long startTime = System.currentTimeMillis();
+        msoLogger.debug("Execute query on infra active request table");
+
+        ResourceOperationStatus operStatus = null;
+        Session session = hibernateUtils.getSessionFactory().openSession();
+        try {
+            session.beginTransaction();
+            String hql =
+                    "FROM ResourceOperationStatus WHERE serviceId = :service_id and operationId = :operation_id and resourceTemplateUUID= :uuid";
+            Query query = session.createQuery(hql);
+            query.setParameter("service_id", serviceId);
+            query.setParameter("operation_id", operationId);
+            query.setParameter("uuid", resourceTemplateUUID);
+            operStatus = (ResourceOperationStatus)query.uniqueResult();
+
+        } finally {
+            if(session != null && session.isOpen()) {
+                session.close();
+            }
+            msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
+                    "Successfully", "RequestDB", "getOperationStatus", null);
+        }
+        return operStatus;
+    }
+
+    /**
+     * update the resource operation
+     * <br>
+     * 
+     * @param operstatus the resource operation object
+     * @since ONAP Amsterdam Release
+     */
+    public static void updateResOperStatus(ResourceOperationStatus operStatus) {
+        Session session = hibernateUtils.getSessionFactory().openSession();
+        session.beginTransaction();
+
+        long startTime = System.currentTimeMillis();
+        msoLogger.debug("Request database - save Resource Operation Status with service Id:" + operStatus.getServiceId()
+                + ", operationId:" + operStatus.getOperationId() + ", resourceUUId:"
+                + operStatus.getResourceTemplateUUID());
+        try {
+            String hql =
+                    "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());
+            query.setParameter("res_uuid", operStatus.getResourceTemplateUUID());
+            ResourceOperationStatus exsitingStatus = (ResourceOperationStatus)query.uniqueResult();
+            if(exsitingStatus == null) {
+                session.save(operStatus);
+            } else {
+                session.merge(operStatus);
+            }
+            session.getTransaction().commit();
+        } finally {
+            if(session != null && session.isOpen()) {
+                session.close();
+            }
+            msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
+                    "Successfully", "RequestDB", "updateResOperStatus", null);
+        }
+        updateOperationStatusBasedOnResourceStatus(operStatus);
+    }
+
+    /**
+     * update service operation status when a operation resource status updated
+     * <br>
+     * 
+     * @param operStatus the resource operation status
+     * @since ONAP Amsterdam Release
+     */
+    private static void updateOperationStatusBasedOnResourceStatus(ResourceOperationStatus operStatus) {
+        Session session = hibernateUtils.getSessionFactory().openSession();
+        session.beginTransaction();
+
+        long startTime = System.currentTimeMillis();
+        msoLogger.debug("Request database - query Resource Operation Status with service Id:"
+                + operStatus.getServiceId() + ", operationId:" + operStatus.getOperationId());
+        try {
+            // query all resources of the service
+            String hql = "FROM ResourceOperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id";
+            Query query = session.createQuery(hql);
+            query.setParameter("service_id", operStatus.getServiceId());
+            query.setParameter("operation_id", operStatus.getOperationId());
+            @SuppressWarnings("unchecked")
+            List<ResourceOperationStatus> lstResourceStatus = (List<ResourceOperationStatus>)query.list();
+            // count the total progress
+            int resourceCount = lstResourceStatus.size();
+            int progress = 0;
+            boolean isFinished = true;
+            for(int i = 0; i < resourceCount; i++) {
+                progress = progress + Integer.valueOf(lstResourceStatus.get(i).getProgress()) / resourceCount;
+                if(RequestsDbConstant.Status.PROCESSING.equals(lstResourceStatus.get(i).getStatus())) {
+                    isFinished = false;
+                }
+            }
+            OperationStatus serviceOperStatus =
+                    getOperationStatus(operStatus.getServiceId(), operStatus.getOperationId());
+            progress = progress > 100 ? 100 : progress;
+            serviceOperStatus.setProgress(String.valueOf(progress));
+            serviceOperStatus.setOperationContent(operStatus.getStatusDescription());
+            // if current resource failed. service failed.
+            if(RequestsDbConstant.Status.ERROR.equals(operStatus.getStatus())) {
+                serviceOperStatus.setResult(RequestsDbConstant.Status.ERROR);
+                serviceOperStatus.setReason(operStatus.getStatusDescription());
+            } else if(isFinished) {
+                // if finished
+                serviceOperStatus.setResult(RequestsDbConstant.Status.FINISHED);
+                serviceOperStatus.setProgress(RequestsDbConstant.Progress.ONE_HUNDRED);
+            }
+            updateOperationStatus(serviceOperStatus);
+        } finally {
+            if(session != null && session.isOpen()) {
+                session.close();
+            }
+            msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
+                    "Successfully", "RequestDB", "updateResOperStatus", null);
+        }
+    }
 }
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDbConstant.java b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDbConstant.java
new file mode 100644
index 0000000..18e51ce
--- /dev/null
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/RequestsDbConstant.java
@@ -0,0 +1,65 @@
+/*-

+ * ============LICENSE_START=======================================================

+ * ONAP - SO

+ * ================================================================================

+ * 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.requestsdb;

+

+/**

+ * The constants of the request db

+ * <br>

+ * <p>

+ * </p>

+ * 

+ * @author

+ * @version     ONAP Amsterdam Release  2017-08-28

+ */

+public class RequestsDbConstant {

+

+    public static class Progress {

+

+        public static final String ONE_HUNDRED = "100";

+

+        private Progress() {

+

+        }

+    }

+

+    public static class Status {

+

+        public static final String FINISHED = "finished";

+

+        public static final String PROCESSING = "processing";

+

+        public static final String ERROR = "error";

+

+        private Status() {

+

+        }

+    }

+

+    public static class OperationType {

+

+        public static final String CREATE = "create";

+

+        public static final String DELETE = "delete";

+

+        private OperationType() {

+

+        }

+    }

+}

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
new file mode 100644
index 0000000..298eb9c
--- /dev/null
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/openecomp/mso/requestsdb/ResourceOperationStatus.java
@@ -0,0 +1,166 @@
+/*-

+ * ============LICENSE_START=======================================================

+ * ONAP - SO

+ * ================================================================================

+ * 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.requestsdb;

+

+/**

+ * The Resource operation status

+ * <br>

+ * <p>

+ * </p>

+ * 

+ * @author

+ * @version     ONAP Amsterdam Release  2017-08-28

+ */

+public class ResourceOperationStatus {

+

+    private String serviceId;

+    

+    private String operationId;

+    

+    private String resourceTemplateUUID;

+    

+    private String operType;

+    

+    private String resourceInstanceID;

+    

+    private String jobId;

+    

+    private String status;

+    

+    private String progress = "0";

+    

+    private String errorCode;

+    

+    private String statusDescription;

+

+    public ResourceOperationStatus(){

+        

+    }

+    

+    public ResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID)

+    {

+        this.serviceId = serviceId;

+        this.operationId = operationId;

+        this.resourceTemplateUUID = resourceTemplateUUID;

+    }

+    

+    public String getServiceId() {

+        return serviceId;

+    }

+

+    

+    public void setServiceId(String serviceId) {

+        this.serviceId = serviceId;

+    }

+

+    

+    public String getOperationId() {

+        return operationId;

+    }

+

+    

+    public void setOperationId(String operationId) {

+        this.operationId = operationId;

+    }

+

+    

+    public String getResourceTemplateUUID() {

+        return resourceTemplateUUID;

+    }

+

+    

+    public void setResourceTemplateUUID(String resourceTemplateUUId) {

+        this.resourceTemplateUUID = resourceTemplateUUId;

+    }

+

+    

+    public String getJobId() {

+        return jobId;

+    }

+

+    

+    public void setJobId(String jobId) {

+        this.jobId = jobId;

+    }

+

+    

+    public String getStatus() {

+        return status;

+    }

+

+    

+    public void setStatus(String status) {

+        this.status = status;

+    }

+

+    

+    public String getProgress() {

+        return progress;

+    }

+

+    

+    public void setProgress(String progress) {

+        this.progress = progress;

+    }

+

+    

+    public String getErrorCode() {

+        return errorCode;

+    }

+

+    

+    public void setErrorCode(String errorCode) {

+        this.errorCode = errorCode;

+    }

+

+    

+    public String getStatusDescription() {

+        return statusDescription;

+    }

+

+    

+    public void setStatusDescription(String statusDescription) {

+        this.statusDescription = statusDescription;

+    }

+

+

+    

+    public String getResourceInstanceID() {

+        return resourceInstanceID;

+    }

+

+

+    

+    public void setResourceInstanceID(String resourceInstanceID) {

+        this.resourceInstanceID = resourceInstanceID;

+    }

+

+    

+    public String getOperType() {

+        return operType;

+    }

+

+    

+    public void setOperType(String operType) {

+        this.operType = operType;

+    }

+    

+    

+}

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
new file mode 100644
index 0000000..60fc359
--- /dev/null
+++ b/mso-api-handlers/mso-requests-db/src/main/resources/OperationStatus.hbm.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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=========================================================
+ */
+  -->
+
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.openecomp.mso.requestsdb">
+	<class name="OperationStatus" table="OPERATION_STATUS">
+		<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"/>
+		<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"/>
+		<property name="operationContent" column="OPERATION_CONTENT" type="string" length="256"/>
+		<property name="progress" column="PROGRESS" type="string" length="256"/>
+		<property name="reason" column="REASON" type="string" length="256"/>
+		<property name="operateAt" column="OPERATE_AT" type="timestamp" generated="insert" insert="false" update="false"/>
+		<property name="finishedAt" column="FINISHED_AT" type="timestamp" generated="update" 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
new file mode 100644
index 0000000..87e2398
--- /dev/null
+++ b/mso-api-handlers/mso-requests-db/src/main/resources/ResourceOperationStatus.hbm.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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=========================================================
+ */
+  -->
+
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.openecomp.mso.requestsdb">
+	<class name="ResourceOperationStatus" table="RESOURCE_OPERATION_STATUS">
+		<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"/>        
+        <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"/>
+		<property name="status" column="STATUS" type="string" length="256"/>
+		<property name="progress" column="PROGRESS" type="string" length="256"/>
+		<property name="errorCode" column="ERROR_CODE" type="string" length="256"/>
+		<property name="statusDescription" column="STATUS_DESCRIPOTION" type="string" length="256"/>	
+	</class>
+</hibernate-mapping>