From 105288860503984b133e22a32b15afbd76b092d3 Mon Sep 17 00:00:00 2001 From: inoshperera Date: Sun, 16 Sep 2018 17:37:25 +0530 Subject: [PATCH 01/10] Test Case for StorageManagementUtilTest (#4) * Adding unit test for StorageManagementUtilTest.java * formatting fixes --- .../StorageManagementUtilTest.java | 75 +++++++++++++++++++ .../src/test/resources/testng.xml | 1 + 2 files changed, 76 insertions(+) create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java new file mode 100644 index 00000000000..68817849cfb --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * WSO2 Inc. licenses this file to you 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. + * + */ + +package org.wso2.carbon.device.application.mgt.core; + +import org.junit.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; +import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class StorageManagementUtilTest { + private static final String TEMP_FOLDER = "src/test/resources/util/temp"; + private static final String APK_FILE = "src/test/resources/util/app-debug.apk"; + private static final String APK_FILE_NAME = "/app-debug.apk"; + + @BeforeMethod + public void before() throws IOException { + File file = new File(TEMP_FOLDER); + if (file.exists()) { + StorageManagementUtil.deleteDir(file); + } + } + + @Test + public void testCreateArtifactDirectory() { + try { + StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER); + } catch (ResourceManagementException e) { + e.printStackTrace(); + Assert.fail("Directory creation failed."); + } + } + + @Test + public void testSaveFile() throws IOException, ResourceManagementException { + StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER); + InputStream apk = new FileInputStream(APK_FILE); + StorageManagementUtil.saveFile(apk, TEMP_FOLDER + APK_FILE_NAME); + File file = new File(TEMP_FOLDER + APK_FILE_NAME); + if (!file.exists()) { + Assert.fail("File saving failed."); + } + } + + @AfterMethod + public void deleteFileTest() throws IOException, ResourceManagementException { + File file = new File(TEMP_FOLDER); + StorageManagementUtil.deleteDir(file); + if (file.exists()) { + Assert.fail("File deleting failed."); + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml index ca512950bcb..9a69c5a87fb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml @@ -23,6 +23,7 @@ + \ No newline at end of file From 6a9cec4c89e90d804d71e6aea60aa3515bd523b1 Mon Sep 17 00:00:00 2001 From: Milan Perera Date: Mon, 17 Sep 2018 19:28:26 +0530 Subject: [PATCH 02/10] Add scopes to publisher mgt API (#5) --- .../services/ApplicationManagementAPI.java | 44 ++++++------------- 1 file changed, 13 insertions(+), 31 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java index aee5a524e3b..6c1d633f518 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java @@ -73,32 +73,14 @@ import javax.ws.rs.core.Response; @Scope( name = "Get Application Details", description = "Get application details", - key = "perm:application:get", - permissions = {"/device-mgt/application/get"} - ), - @Scope( - name = "Create an Application", - description = "Create an application", - key = "perm:application:create", - permissions = {"/device-mgt/application/create"} + key = "perm:app:publisher:view", + permissions = {"/device-mgt/application/view"} ), @Scope( name = "Update an Application", description = "Update an application", - key = "perm:application:update", + key = "perm:app:publisher:update", permissions = {"/device-mgt/application/update"} - ), - @Scope( - name = "Login to Application Management", - description = "Login to Application Management", - key = "perm:application-mgt:login", - permissions = {"/device-mgt/application-mgt/login"} - ), - @Scope( - name = "Delete an Application", - description = "Delete an application", - key = "perm:application:delete", - permissions = {"/device-mgt/application/delete"} ) } ) @@ -122,7 +104,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:get") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view") }) } ) @@ -172,7 +154,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:get") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view") }) } ) @@ -215,7 +197,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:update") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) @@ -254,7 +236,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:create") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) @@ -313,7 +295,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:delete") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) @@ -349,7 +331,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:create") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) @@ -393,7 +375,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:create") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) @@ -436,7 +418,7 @@ public interface ApplicationManagementAPI { tags = "Application Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:application:update") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) @@ -475,7 +457,7 @@ public interface ApplicationManagementAPI { tags = "Lifecycle Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:lifecycle:get") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view") }) } ) @@ -507,7 +489,7 @@ public interface ApplicationManagementAPI { tags = "Lifecycle Management", extensions = { @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:lifecycle:add") + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") }) } ) From 000ce6ee540c09cdecf7dee97bfc4f921f38c5a1 Mon Sep 17 00:00:00 2001 From: Madawa Soysa Date: Tue, 18 Sep 2018 22:07:04 +0530 Subject: [PATCH 03/10] DB Scripts for App Manager (#6) MySQL and H2 DB Scripts --- .../dbscripts/cdm/application-mgt/h2.sql | 472 ++++++---------- .../dbscripts/cdm/application-mgt/mysql.sql | 513 +++++++----------- 2 files changed, 346 insertions(+), 639 deletions(-) diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index ad3d082962c..710182c632b 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -1,350 +1,206 @@ -- ----------------------------------------------------- --- Schema WSO2DM_APPM_DB --- ----------------------------------------------------- - --- ----------------------------------------------------- --- Table APPM_PLATFORM --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_PLATFORM ( -ID INT NOT NULL AUTO_INCREMENT UNIQUE, -IDENTIFIER VARCHAR (100) NOT NULL, -TENANT_ID INT NOT NULL , -NAME VARCHAR (255), -FILE_BASED BOOLEAN, -DESCRIPTION LONGVARCHAR, -IS_SHARED BOOLEAN, -IS_DEFAULT_TENANT_MAPPING BOOLEAN, -ICON_NAME VARCHAR (100), -PRIMARY KEY (ID) -); - - -CREATE TABLE IF NOT EXISTS APPM_PLATFORM_PROPERTIES ( -ID INT NOT NULL AUTO_INCREMENT, -PLATFORM_ID INT NOT NULL, -PROP_NAME VARCHAR (100) NOT NULL, -OPTIONAL BOOLEAN, -DEFAUL_VALUE VARCHAR (255), -FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE, -PRIMARY KEY (ID, PLATFORM_ID, PROP_NAME) -); - -CREATE TABLE IF NOT EXISTS APPM_PLATFORM_TENANT_MAPPING ( -ID INT NOT NULL AUTO_INCREMENT, -TENANT_ID INT NOT NULL , -PLATFORM_ID INT NOT NULL, -FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE, -PRIMARY KEY (ID, TENANT_ID, PLATFORM_ID) -); - -CREATE INDEX IF NOT EXISTS FK_PLATFROM_TENANT_MAPPING_PLATFORM ON APPM_PLATFORM_TENANT_MAPPING(PLATFORM_ID ASC); - --- ----------------------------------------------------- --- Table APPM_APPLICATION_CATEGORY --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_APPLICATION_CATEGORY ( - ID INT NOT NULL AUTO_INCREMENT, - NAME VARCHAR(100) NOT NULL UNIQUE, - DESCRIPTION TEXT NULL, +-- Table AP_APP +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_APP ( + ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(45) NOT NULL, + TYPE VARCHAR(200) NOT NULL, + TENANT_ID VARCHAR(45) NOT NULL, + APP_CATEGORY VARCHAR(45) NULL DEFAULT NULL, + RESTRICTED INT(11) NOT NULL, + STATUS VARCHAR(45) NOT NULL DEFAULT 'ACTIVE', + SUB_TYPE VARCHAR(45) NOT NULL, + CURRENCY VARCHAR(45) NULL DEFAULT '$', + DM_DEVICE_TYPE_ID INT(11) NOT NULL, PRIMARY KEY (ID)); -INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Sports', 'Applications that involve sports.'); -INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Education', 'Application related with education'); -INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('News', 'Applications involving news'); -- ----------------------------------------------------- --- Table `APPM_LIFECYCLE_STATE` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE ( - ID INT NOT NULL AUTO_INCREMENT UNIQUE, - NAME VARCHAR(100) NOT NULL, - IDENTIFIER VARCHAR(100) NOT NULL, - DESCRIPTION TEXT NULL, +-- Table AP_APP_RELEASE +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_APP_RELEASE ( + ID INT(11) NOT NULL AUTO_INCREMENT, + VERSION VARCHAR(10) NOT NULL, + TENANT_ID VARCHAR(45) NOT NULL, + UUID VARCHAR(200) NOT NULL, + RELEASE_TYPE VARCHAR(45) NOT NULL, + APP_PRICE DECIMAL(6,2) NULL DEFAULT NULL, + STORED_LOCATION VARCHAR(45) NOT NULL, + BANNER_LOCATION VARCHAR(45) NOT NULL, + SC_1_LOCATION VARCHAR(45) NOT NULL, + SC_2_LOCATION VARCHAR(45) NULL DEFAULT NULL, + SC_3_LOCATION VARCHAR(45) NULL DEFAULT NULL, + APP_HASH_VALUE VARCHAR(1000) NOT NULL, + SHARED_WITH_ALL_TENANTS INT(11) NULL DEFAULT NULL, + APP_META_INFO VARCHAR(20000) NULL DEFAULT NULL, + RATING DOUBLE NULL DEFAULT NULL, + RATED_USERS INT(11) NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID, AP_APP_ID), + CONSTRAINT fk_AP_APP_RELEASE_AP_APP1 + FOREIGN KEY (AP_APP_ID) + REFERENCES AP_APP (ID)); + +CREATE INDEX fk_AP_APP_RELEASE_AP_APP1_idx ON AP_APP_RELEASE (AP_APP_ID ASC); + + +-- ----------------------------------------------------- +-- Table AP_APP_REVIEW +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_APP_REVIEW ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + COMMENT VARCHAR(250) NOT NULL, + REPLY_COMMENT VARCHAR(250) NULL, + CREATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + MODEFIED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + RATING INT(11) NULL, + USERNAME VARCHAR(45) NOT NULL, + AP_APP_RELEASE_ID INT(11) NOT NULL, + AP_APP_ID INT(11) NOT NULL, PRIMARY KEY (ID), - UNIQUE INDEX APPM_LIFECYCLE_STATE_IDENTIFIER_UNIQUE (IDENTIFIER ASC)); - -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('CREATED', 'CREATED', 'Application creation -initial state'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('IN REVIEW', 'IN REVIEW', 'Application is in in-review state'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('APPROVED', 'APPROVED', 'State in which Application is approved after reviewing.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('REJECTED', 'REJECTED', 'State in which Application is rejected after reviewing.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,'); + CONSTRAINT fk_AP_APP_COMMENT_AP_APP_RELEASE1 + FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID) + REFERENCES AP_APP_RELEASE (ID , AP_APP_ID)); +CREATE INDEX fk_AP_APP_COMMENT_AP_APP_RELEASE1_idx ON AP_APP_REVIEW (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC); -CREATE TABLE IF NOT EXISTS APPM_LC_STATE_TRANSITION -( - ID INT NOT NULL AUTO_INCREMENT UNIQUE, - INITIAL_STATE INT, - NEXT_STATE INT, - PERMISSION VARCHAR(1024), - DESCRIPTION VARCHAR(2048), - PRIMARY KEY (INITIAL_STATE, NEXT_STATE), - FOREIGN KEY (INITIAL_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE, - FOREIGN KEY (NEXT_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE -); - -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (1, 2, null, 'Submit for review'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (2, 1, null, 'Revoke from review'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (2, 3, '/permission/admin/manage/device-mgt/application/review', 'APPROVE'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (2, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (3, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (3, 5, null, 'PUBLISH'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (5, 6, null, 'UN PUBLISH'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (6, 5, null, 'PUBLISH'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (4, 1, null, 'Return to CREATE STATE'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (6, 1, null, 'Return to CREATE STATE'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (6, 7, null, 'Retire'); -- ----------------------------------------------------- --- Table APPM_APPLICATION +-- Table AP_APP_LIFECYCLE_STATE -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_APPLICATION` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `UUID` VARCHAR(100) NOT NULL, - `NAME` VARCHAR(100) NOT NULL, - `SHORT_DESCRIPTION` VARCHAR(255) NULL, - `DESCRIPTION` TEXT NULL, - `SCREEN_SHOT_COUNT` INT DEFAULT 0, - `VIDEO_NAME` VARCHAR(100) NULL, - `CREATED_BY` VARCHAR(255) NULL, - `CREATED_AT` DATETIME NOT NULL, - `MODIFIED_AT` DATETIME NULL, - `IS_FREE` TINYINT(1) NULL, - `PAYMENT_CURRENCY` VARCHAR(45) NULL, - `PAYMENT_PRICE` DECIMAL(10,2) NULL, - `APPLICATION_CATEGORY_ID` INT NOT NULL, - `LIFECYCLE_STATE_ID` INT NOT NULL, - `LIFECYCLE_STATE_MODIFIED_BY` VARCHAR(255) NULL, - `LIFECYCLE_STATE_MODIFIED_AT` DATETIME NULL, - `TENANT_ID` INT NOT NULL, - `PLATFORM_ID` INT NOT NULL, - PRIMARY KEY (`ID`, `APPLICATION_CATEGORY_ID`, `LIFECYCLE_STATE_ID`, `PLATFORM_ID`), - UNIQUE INDEX `UUID_UNIQUE` (`UUID` ASC), - FOREIGN KEY (`APPLICATION_CATEGORY_ID`) - REFERENCES `APPM_APPLICATION_CATEGORY` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_APPLICATION_APPM_LIFECYCLE_STATE1` - FOREIGN KEY (`LIFECYCLE_STATE_ID`) - REFERENCES `APPM_LIFECYCLE_STATE` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_APPLICATION_APPM_PLATFORM1` - FOREIGN KEY (`PLATFORM_ID`) - REFERENCES `APPM_PLATFORM` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION); - -CREATE INDEX IF NOT EXISTS FK_APPLICATION_APPLICATION_CATEGORY ON APPM_APPLICATION(APPLICATION_CATEGORY_ID ASC); +CREATE TABLE IF NOT EXISTS AP_APP_LIFECYCLE_STATE ( + ID INT(11) NOT NULL AUTO_INCREMENT, + CURRENT_STATE VARCHAR(45) NOT NULL, + PREVIOUSE_STATE VARCHAR(45) NOT NULL, + TENANT_ID VARCHAR(45) NOT NULL, + UPDATED_BY VARCHAR(100) NOT NULL, + UPDATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + AP_APP_RELEASE_ID INT(11) NOT NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID, AP_APP_RELEASE_ID, AP_APP_ID), + CONSTRAINT fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1 + FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID) + REFERENCES AP_APP_RELEASE (ID , AP_APP_ID)); --- ----------------------------------------------------- --- Table APPM_APPLICATION_PROPERTY --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_APPLICATION_PROPERTY ( - PROP_KEY VARCHAR(255) NOT NULL, - PROP_VAL TEXT NULL, - APPLICATION_ID INT NOT NULL, - PRIMARY KEY (PROP_KEY, APPLICATION_ID), - CONSTRAINT FK_APPLICATION_PROPERTY_APPLICATION - FOREIGN KEY (APPLICATION_ID) - REFERENCES APPM_APPLICATION (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); +CREATE INDEX fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1_idx ON AP_APP_LIFECYCLE_STATE (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC); -CREATE INDEX FK_APPLICATION_PROPERTY_APPLICATION ON APPM_APPLICATION_PROPERTY(APPLICATION_ID ASC); -- ----------------------------------------------------- --- Table APPM_APPLICATION_RELEASE +-- Table AP_APP_TAG -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_APPLICATION_RELEASE ( - ID INT NOT NULL AUTO_INCREMENT, - VERSION_NAME VARCHAR(100) NOT NULL, - RELEASE_RESOURCE TEXT NULL, - RELEASE_CHANNEL VARCHAR(50) DEFAULT 'ALPHA', - RELEASE_DETAILS TEXT NULL, - CREATED_AT DATETIME NOT NULL, - APPM_APPLICATION_ID INT NOT NULL, - IS_DEFAULT TINYINT NULL, - PRIMARY KEY (APPM_APPLICATION_ID, VERSION_NAME), - CONSTRAINT FK_APPLICATION_VERSION_APPLICATION - FOREIGN KEY (APPM_APPLICATION_ID) - REFERENCES APPM_APPLICATION (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); - -CREATE INDEX FK_APPLICATION_VERSION_APPLICATION ON APPM_APPLICATION_RELEASE(APPM_APPLICATION_ID ASC); +CREATE TABLE IF NOT EXISTS AP_APP_TAG ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + TAG VARCHAR(45) NOT NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_AP_APP_TAGS_AP_APP1 + FOREIGN KEY (AP_APP_ID) + REFERENCES AP_APP (ID)); --- ----------------------------------------------------- --- Table APPM_RELEASE_PROPERTY --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_RELEASE_PROPERTY ( - PROP_KEY VARCHAR(255) NOT NULL, - PROP_VALUE TEXT NULL, - APPLICATION_RELEASE_ID INT NOT NULL, - PRIMARY KEY (PROP_KEY, APPLICATION_RELEASE_ID), - CONSTRAINT FK_RELEASE_PROPERTY_APPLICATION_RELEASE - FOREIGN KEY (APPLICATION_RELEASE_ID) - REFERENCES APPM_APPLICATION_RELEASE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); +CREATE INDEX fk_AP_APP_TAGS_AP_APP1_idx ON AP_APP_TAG (AP_APP_ID ASC); -CREATE INDEX FK_RELEASE_PROPERTY_APPLICATION_RELEASE ON APPM_RELEASE_PROPERTY(APPLICATION_RELEASE_ID ASC); -- ----------------------------------------------------- --- Table APPM_RESOURCE_TYPE +-- Table AP_DEVICE_SUBSCRIPTION -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_RESOURCE_TYPE ( - ID INT NOT NULL AUTO_INCREMENT, - NAME VARCHAR(45) NULL, - DESCRIPTION TEXT NULL, - PRIMARY KEY (ID)); +CREATE TABLE IF NOT EXISTS AP_DEVICE_SUBSCRIPTION ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + SUBSCRIBED_BY VARCHAR(100) NOT NULL, + SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNSUBSCRIBED INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + DM_ENROLMENT_ID INT(11) NOT NULL, + AP_APP_RELEASE_ID INT(11) NOT NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1 + FOREIGN KEY (AP_APP_ID , AP_APP_RELEASE_ID) + REFERENCES AP_APP_RELEASE (AP_APP_ID , ID)); -INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('PUBLIC', 'OPEN VISIBILITY, CAN BE VIEWED BY ALL LOGGED IN USERS'); -INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('ROLES', 'ROLE BASED RESTRICTION, CAN BE VIEWED BY ONLY GIVEN - SET OF USER WHO HAVE THE SPECIFIED ROLE'); -INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('DEVICE_GROUPS', 'DEVICE GROUP LEVEL RESTRICTION, -CAN BE VIEWED BY THE DEVICES/ROLES BELONG TO THE GROUP'); +CREATE INDEX fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_DEVICE_SUBSCRIPTION (AP_APP_ID ASC, AP_APP_RELEASE_ID ASC); -- ----------------------------------------------------- --- Table APPM_SUBSCRIPTION +-- Table AP_GROUP_SUBSCRIPTION -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_SUBSCRIPTION ( - ID INT NOT NULL AUTO_INCREMENT, - VALUE VARCHAR(255) NOT NULL, - CREATED_AT DATETIME NOT NULL, - RESOURCE_TYPE_ID INT NOT NULL, - APPLICATION_ID INT NOT NULL, - APPLICATION_RELEASE_ID INT NULL, - PRIMARY KEY (ID, APPLICATION_ID, RESOURCE_TYPE_ID), - CONSTRAINT fk_APPM_APPLICATION_SUBSCRIPTION_APPM_RESOURCE_TYPE1 - FOREIGN KEY (RESOURCE_TYPE_ID) - REFERENCES APPM_RESOURCE_TYPE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION1 - FOREIGN KEY (APPLICATION_ID) - REFERENCES APPM_APPLICATION (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION_RELEASE1 - FOREIGN KEY (APPLICATION_RELEASE_ID) - REFERENCES APPM_APPLICATION_RELEASE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); - -CREATE INDEX FK_APPLICATION_SUBSCRIPTION_RESOURCE_TYPE ON APPM_SUBSCRIPTION(RESOURCE_TYPE_ID ASC); -CREATE INDEX FK_APPLICATION_SUBSCRIPTION_APPLICATION ON APPM_SUBSCRIPTION(APPLICATION_ID ASC); -CREATE INDEX FK_APPLICATION_SUBSCRIPTION_APPLICATION_RELEASE ON APPM_SUBSCRIPTION(APPLICATION_RELEASE_ID ASC); +CREATE TABLE IF NOT EXISTS AP_GROUP_SUBSCRIPTION ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + SUBSCRIBED_BY VARCHAR(100) NOT NULL, + SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNSUBSCRIBED INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + DM_GROUP_ID INT(11) NOT NULL, + AP_APP_RELEASE_ID INT(11) NOT NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1 + FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID) + REFERENCES AP_APP_RELEASE (ID , AP_APP_ID)); --- ----------------------------------------------------- --- Table APPM_COMMENT --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_COMMENT ( - ID INT NOT NULL AUTO_INCREMENT, - APPLICATION_RELEASE_ID INT NOT NULL, - COMMENT_SUBJECT VARCHAR(255) NULL, - COMMENT_BODY TEXT NULL, - RATING INT NULL, - PARENT_ID INT NULL, - CREATED_AT DATETIME NOT NULL, - CREATED_BY VARCHAR(45) NULL, - MODIFIED_AT DATETIME NULL, - PUBLISHED TINYINT NULL, - APPROVED TINYINT NULL, - PRIMARY KEY (ID, APPLICATION_RELEASE_ID), - CONSTRAINT FK_APPLICATION_COMMENTS_APPLICATION_RELEASE - FOREIGN KEY (APPLICATION_RELEASE_ID) - REFERENCES APPM_APPLICATION_RELEASE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); +CREATE INDEX fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_GROUP_SUBSCRIPTION (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC); -CREATE INDEX FK_APPLICATION_COMMENTS_APPLICATION_RELEASE ON APPM_COMMENT(APPLICATION_RELEASE_ID ASC); -- ----------------------------------------------------- --- Table APPM_PLATFORM_TAG +-- Table AP_ROLE_SUBSCRIPTION -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_PLATFORM_TAG ( - NAME VARCHAR(100) NOT NULL, - PLATFORM_ID INT NOT NULL, - PRIMARY KEY (PLATFORM_ID, name), - CONSTRAINT fk_APPM_SUPPORTED_PLATFORM_TAGS_APPM_SUPPORTED_PLATFORM1 - FOREIGN KEY (PLATFORM_ID) - REFERENCES APPM_PLATFORM (ID) - ON DELETE CASCADE - ON UPDATE CASCADE); - -CREATE INDEX FK_PLATFORM_TAGS_PLATFORM ON APPM_PLATFORM_TAG(PLATFORM_ID ASC); +CREATE TABLE IF NOT EXISTS AP_ROLE_SUBSCRIPTION ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + ROLE_NAME VARCHAR(100) NOT NULL, + SUBSCRIBED_BY VARCHAR(100) NOT NULL, + SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNSUBSCRIBED INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + AP_APP_RELEASE_ID INT(11) NOT NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1 + FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID) + REFERENCES AP_APP_RELEASE (ID , AP_APP_ID)); --- ----------------------------------------------------- --- Table APPM_APPLICATION_TAG --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_APPLICATION_TAG ( - name VARCHAR(45) NOT NULL, - APPLICATION_ID INT NOT NULL, - PRIMARY KEY (APPLICATION_ID, name), - CONSTRAINT fk_APPM_APPLICATION_TAG_APPM_APPLICATION1 - FOREIGN KEY (APPLICATION_ID) - REFERENCES APPM_APPLICATION (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); +CREATE INDEX fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_ROLE_SUBSCRIPTION (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC); -CREATE INDEX FK_APPLICATION_TAG_APPLICATION ON APPM_APPLICATION_TAG(APPLICATION_ID ASC); -- ----------------------------------------------------- --- Table APPM_VISIBILITY +-- Table AP_UNRESTRICTED_ROLE -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_VISIBILITY ( - ID INT NOT NULL AUTO_INCREMENT, - VALUE VARCHAR(255), - RESOURCE_TYPE_ID INT NOT NULL, - APPLICATION_ID INT NULL, +CREATE TABLE IF NOT EXISTS AP_UNRESTRICTED_ROLE ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + ROLE VARCHAR(45) NOT NULL, + AP_APP_ID INT(11) NOT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_APPM_VISIBILITY_APPM_RESOURCE_TYPE1 - FOREIGN KEY (RESOURCE_TYPE_ID) - REFERENCES APPM_RESOURCE_TYPE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT fk_APPM_VISIBILITY_APPM_APPLICATION1 - FOREIGN KEY (APPLICATION_ID) - REFERENCES APPM_APPLICATION (ID) - ON DELETE CASCADE - ON UPDATE CASCADE); + CONSTRAINT fk_AP_APP_VISIBILITY_AP_APP1 + FOREIGN KEY (AP_APP_ID) + REFERENCES AP_APP (ID)); + +CREATE INDEX fk_AP_APP_VISIBILITY_AP_APP1_idx ON AP_UNRESTRICTED_ROLE (AP_APP_ID ASC); -CREATE INDEX FK_APPM_VISIBILITY_RESOURCE_TYPE ON APPM_VISIBILITY(RESOURCE_TYPE_ID ASC); -CREATE INDEX FK_VISIBILITY_APPLICATION ON APPM_VISIBILITY(APPLICATION_ID ASC); -- ----------------------------------------------------- --- Table APPM_SUBSCRIPTION_PROPERTIES +-- Table AP_USER_SUBSCRIPTION -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_SUBSCRIPTION_PROPERTIES ( - PROP_KEY VARCHAR(500) NOT NULL, - PROP_VALUE VARCHAR(500) NULL, - APPM_SUBSCRIPTION_ID INT NOT NULL, - PRIMARY KEY (PROP_KEY, APPM_SUBSCRIPTION_ID), - CONSTRAINT fk_APPM_SUBSCRIPTION_PROPERTIES_APPM_SUBSCRIPTION1 - FOREIGN KEY (APPM_SUBSCRIPTION_ID) - REFERENCES APPM_SUBSCRIPTION (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION); +CREATE TABLE IF NOT EXISTS AP_USER_SUBSCRIPTION ( + ID INT(11) NOT NULL AUTO_INCREMENT, + TENANT_ID VARCHAR(45) NOT NULL, + USER_NAME VARCHAR(100) NOT NULL, + SUBSCRIBED_BY VARCHAR(100) NOT NULL, + SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNSUBSCRIBED INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, + UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + AP_APP_RELEASE_ID INT(11) NOT NULL, + AP_APP_ID INT(11) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1 + FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID) + REFERENCES AP_APP_RELEASE (ID , AP_APP_ID)); -CREATE INDEX FK_SUBSCRIPTION_PROPERTIES_SUBSCRIPTION ON APPM_SUBSCRIPTION_PROPERTIES(APPM_SUBSCRIPTION_ID ASC); \ No newline at end of file +CREATE INDEX fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_USER_SUBSCRIPTION (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC); diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index 14b21ad7f8d..641c9946600 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -1,5 +1,5 @@ -- MySQL Script generated by MySQL Workbench --- 2017-06-14 12:46:43 +0530 +-- Tue 18 Sep 2018 17:40:45 +0530 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering @@ -7,401 +7,252 @@ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; --- ----------------------------------------------------- --- Schema WSO2DM_APPM_DB --- ----------------------------------------------------- - --- ----------------------------------------------------- --- Table `APPM_PLATFORM` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_PLATFORM ( -ID INT NOT NULL AUTO_INCREMENT UNIQUE, -IDENTIFIER VARCHAR (100) NOT NULL, -TENANT_ID INT NOT NULL , -NAME VARCHAR (255), -FILE_BASED BOOLEAN, -DESCRIPTION VARCHAR (2048), -IS_SHARED BOOLEAN, -IS_DEFAULT_TENANT_MAPPING BOOLEAN, -ICON_NAME VARCHAR (100), -PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS APPM_PLATFORM_PROPERTIES ( -ID INT NOT NULL AUTO_INCREMENT, -PLATFORM_ID INT NOT NULL, -PROP_NAME VARCHAR (100) NOT NULL, -OPTIONAL BOOLEAN, -DEFAUL_VALUE VARCHAR (255), -FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE, -PRIMARY KEY (ID, PLATFORM_ID, PROP_NAME) -); - -- ----------------------------------------------------- --- Table `APPM_PLATFORM_TENENT_MAPPING` +-- Table `AP_APP` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_PLATFORM_TENANT_MAPPING` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `PLATFORM_ID` INT NOT NULL, - `TENANT_ID` INT NOT NULL, - PRIMARY KEY (`ID`, `PLATFORM_ID`), - INDEX `FK_PLATFROM_TENANT_MAPPING_PLATFORM` (`PLATFORM_ID` ASC), - CONSTRAINT `fk_APPM_PLATFORM_TENANT_MAPPING_APPM_SUPPORTED_PLATFORM1` - FOREIGN KEY (`PLATFORM_ID`) - REFERENCES `APPM_PLATFORM` (`ID`) - ON DELETE CASCADE - ON UPDATE CASCADE ) - ENGINE = InnoDB - COMMENT = 'This table contains the data related relationship between application platofrm and appication mappings'; - --- ----------------------------------------------------- --- Table `APPM_APPLICATION_CATEGORY` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_CATEGORY` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `NAME` VARCHAR(100) NOT NULL UNIQUE, - `DESCRIPTION` TEXT NULL, +CREATE TABLE IF NOT EXISTS `AP_APP` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(45) NOT NULL, + `TYPE` VARCHAR(200) NOT NULL, + `TENANT_ID` VARCHAR(45) NOT NULL, + `APP_CATEGORY` VARCHAR(45) NULL DEFAULT NULL, + `RESTRICTED` INT(11) NOT NULL, + `STATUS` VARCHAR(45) NOT NULL DEFAULT 'ACTIVE', + `SUB_TYPE` VARCHAR(45) NOT NULL, + `CURRENCY` VARCHAR(45) NULL DEFAULT '$', + `DM_DEVICE_TYPE_ID` INT(11) NOT NULL, PRIMARY KEY (`ID`)) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the application category'; - -INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Sports', 'Applications that involve sports.'); -INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Education', 'Application related with education'); -INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('News', 'Applications involving news'); - --- ----------------------------------------------------- --- Table `APPM_LIFECYCLE_STATE` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE ( - ID INT NOT NULL AUTO_INCREMENT UNIQUE, - NAME VARCHAR(100) NOT NULL, - IDENTIFIER VARCHAR(100) NOT NULL, - DESCRIPTION TEXT NULL, - PRIMARY KEY (ID), - UNIQUE INDEX APPM_LIFECYCLE_STATE_IDENTIFIER_UNIQUE (IDENTIFIER ASC)); - -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('CREATED', 'CREATED', -'Application creation initial state'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('IN REVIEW', 'IN REVIEW', 'Application is in in-review state'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('APPROVED', 'APPROVED', 'State in which Application is approved after reviewing.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('REJECTED', 'REJECTED', 'State in which Application is rejected after reviewing.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.'); -INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,'); - - -CREATE TABLE IF NOT EXISTS APPM_LC_STATE_TRANSITION -( - ID INT NOT NULL AUTO_INCREMENT UNIQUE, - INITIAL_STATE INT, - NEXT_STATE INT, - PERMISSION VARCHAR(1024), - DESCRIPTION VARCHAR(2048), - PRIMARY KEY (INITIAL_STATE, NEXT_STATE), - FOREIGN KEY (INITIAL_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE, - FOREIGN KEY (NEXT_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE -); - -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (1, 2, null, 'Submit for review'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (2, 1, null, 'Revoke from review'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (2, 3, '/permission/admin/manage/device-mgt/application/review', 'APPROVE'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (2, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (3, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (3, 5, null, 'PUBLISH'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (5, 6, null, 'UN PUBLISH'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (6, 5, null, 'PUBLISH'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (4, 1, null, 'Return to CREATE STATE'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (6, 1, null, 'Return to CREATE STATE'); -INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES - (6, 7, null, 'Retire'); - --- ----------------------------------------------------- --- Table `APPM_APPLICATION` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_APPLICATION` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `UUID` VARCHAR(100) NOT NULL, - `NAME` VARCHAR(100) NOT NULL, - `SHORT_DESCRIPTION` VARCHAR(255) NULL, - `DESCRIPTION` TEXT NULL, - `VIDEO_NAME` VARCHAR(100) NULL, - `SCREEN_SHOT_COUNT` INT DEFAULT 0, - `CREATED_BY` VARCHAR(255) NULL, - `CREATED_AT` DATETIME NOT NULL, - `MODIFIED_AT` DATETIME NULL, - `IS_FREE` TINYINT(1) NULL, - `PAYMENT_CURRENCY` VARCHAR(45) NULL, - `PAYMENT_PRICE` DECIMAL(10,2) NULL, - `APPLICATION_CATEGORY_ID` INT NOT NULL, - `LIFECYCLE_STATE_ID` INT NOT NULL, - `LIFECYCLE_STATE_MODIFIED_BY` VARCHAR(255) NULL, - `LIFECYCLE_STATE_MODIFIED_AT` DATETIME NULL, - `TENANT_ID` INT NULL, - `PLATFORM_ID` INT NOT NULL, - PRIMARY KEY (`ID`, `APPLICATION_CATEGORY_ID`, `LIFECYCLE_STATE_ID`, `PLATFORM_ID`), - UNIQUE INDEX `UUID_UNIQUE` (`UUID` ASC), - INDEX `FK_APPLICATION_APPLICATION_CATEGORY` (`APPLICATION_CATEGORY_ID` ASC), - INDEX `FK_APPLICATION_LIFECYCLE_STATE` (`LIFECYCLE_STATE_ID` ASC), - INDEX `FK_APPM_APPLICATION_APPM_PLATFORM` (`PLATFORM_ID` ASC), - CONSTRAINT `FK_APPLICATION_APPLICATION_CATEGORY` - FOREIGN KEY (`APPLICATION_CATEGORY_ID`) - REFERENCES `APPM_APPLICATION_CATEGORY` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_APPLICATION_APPM_LIFECYCLE_STATE1` - FOREIGN KEY (`LIFECYCLE_STATE_ID`) - REFERENCES `APPM_LIFECYCLE_STATE` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_APPLICATION_APPM_PLATFORM1` - FOREIGN KEY (`PLATFORM_ID`) - REFERENCES `APPM_PLATFORM` (`ID`) + DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `AP_APP_RELEASE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `AP_APP_RELEASE` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `VERSION` VARCHAR(10) NOT NULL, + `TENANT_ID` VARCHAR(45) NOT NULL, + `UUID` VARCHAR(200) NOT NULL, + `RELEASE_TYPE` VARCHAR(45) NOT NULL, + `APP_PRICE` DECIMAL(6,2) NULL DEFAULT NULL, + `STORED_LOCATION` VARCHAR(45) NOT NULL, + `BANNER_LOCATION` VARCHAR(45) NOT NULL, + `SC_1_LOCATION` VARCHAR(45) NOT NULL, + `SC_2_LOCATION` VARCHAR(45) NULL DEFAULT NULL, + `SC_3_LOCATION` VARCHAR(45) NULL DEFAULT NULL, + `APP_HASH_VALUE` VARCHAR(1000) NOT NULL, + `SHARED_WITH_ALL_TENANTS` INT(11) NULL DEFAULT NULL, + `APP_META_INFO` VARCHAR(20000) NULL DEFAULT NULL, + `RATING` DOUBLE NULL DEFAULT NULL, + `RATED_USERS` INT(11) NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`, `AP_APP_ID`), + CONSTRAINT `fk_AP_APP_RELEASE_AP_APP1` + FOREIGN KEY (`AP_APP_ID`) + REFERENCES `AP_APP` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the applications'; + DEFAULT CHARACTER SET = utf8 + COMMENT = ' '; + +CREATE INDEX `fk_AP_APP_RELEASE_AP_APP1_idx` ON `AP_APP_RELEASE` (`AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_APPLICATION_PROPERTY` +-- Table `AP_APP_REVIEW` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_PROPERTY` ( - `PROP_KEY` VARCHAR(255) NOT NULL, - `PROP_VAL` TEXT NULL, - `APPLICATION_ID` INT NOT NULL, - PRIMARY KEY (`PROP_KEY`, `APPLICATION_ID`), - INDEX `FK_APPLICATION_PROPERTY_APPLICATION` (`APPLICATION_ID` ASC), - CONSTRAINT `FK_APPLICATION_PROPERTY_APPLICATION` - FOREIGN KEY (`APPLICATION_ID`) - REFERENCES `APPM_APPLICATION` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_APP_REVIEW` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `COMMENT` VARCHAR(250) NOT NULL, + `REPLY_COMMENT` VARCHAR(250) NULL, + `CREATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `MODEFIED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `RATING` INT(11) NULL, + `USERNAME` VARCHAR(45) NOT NULL, + `AP_APP_RELEASE_ID` INT(11) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + CONSTRAINT `fk_AP_APP_COMMENT_AP_APP_RELEASE1` + FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`) + REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the properties that related to the application'; + DEFAULT CHARACTER SET = utf8; + +CREATE INDEX `fk_AP_APP_COMMENT_AP_APP_RELEASE1_idx` ON `AP_APP_REVIEW` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_APPLICATION_RELEASE` +-- Table `AP_APP_LIFECYCLE_STATE` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_RELEASE` ( - `ID` INT NOT NULL AUTO_INCREMENT UNIQUE , - `VERSION_NAME` VARCHAR(100) NOT NULL, - `RELEASE_RESOURCE` TEXT NULL, - `RELEASE_CHANNEL` VARCHAR(50) DEFAULT 'ALPHA', - `RELEASE_DETAILS` TEXT NULL, - `CREATED_AT` DATETIME NOT NULL, - `APPM_APPLICATION_ID` INT NOT NULL, - `IS_DEFAULT` TINYINT(1) NULL, - PRIMARY KEY (`APPM_APPLICATION_ID`, `VERSION_NAME`), - INDEX `FK_APPLICATION_VERSION_APPLICATION` (`APPM_APPLICATION_ID` ASC), - CONSTRAINT `FK_APPLICATION_VERSION_APPLICATION` - FOREIGN KEY (`APPM_APPLICATION_ID`) - REFERENCES `APPM_APPLICATION` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_APP_LIFECYCLE_STATE` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `CURRENT_STATE` VARCHAR(45) NOT NULL, + `PREVIOUSE_STATE` VARCHAR(45) NOT NULL, + `TENANT_ID` VARCHAR(45) NOT NULL, + `UPDATED_BY` VARCHAR(100) NOT NULL, + `UPDATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `AP_APP_RELEASE_ID` INT(11) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`, `AP_APP_RELEASE_ID`, `AP_APP_ID`), + CONSTRAINT `fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1` + FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`) + REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the application releases'; + DEFAULT CHARACTER SET = utf8; + +CREATE INDEX `fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1_idx` ON `AP_APP_LIFECYCLE_STATE` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_RELEASE_PROPERTY` +-- Table `AP_APP_TAG` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_RELEASE_PROPERTY` ( - `PROP_KEY` VARCHAR(255) NOT NULL, - `PROP_VALUE` TEXT NULL, - `APPLICATION_RELEASE_ID` INT NOT NULL, - PRIMARY KEY (`PROP_KEY`, `APPLICATION_RELEASE_ID`), - INDEX `FK_RELEASE_PROPERTY_APPLICATION_RELEASE` (`APPLICATION_RELEASE_ID` ASC), - CONSTRAINT `FK_RELEASE_PROPERTY_APPLICATION_RELEASE` - FOREIGN KEY (`APPLICATION_RELEASE_ID`) - REFERENCES `APPM_APPLICATION_RELEASE` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_APP_TAG` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `TAG` VARCHAR(45) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + CONSTRAINT `fk_AP_APP_TAGS_AP_APP1` + FOREIGN KEY (`AP_APP_ID`) + REFERENCES `AP_APP` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the properties that related to the application release'; - - --- ----------------------------------------------------- --- Table `APPM_RESOURCE_TYPE` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_RESOURCE_TYPE` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `NAME` VARCHAR(45) NULL, - `DESCRIPTION` TEXT NULL, - PRIMARY KEY (`ID`)) - ENGINE = InnoDB; + DEFAULT CHARACTER SET = utf8; -INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('PUBLIC', 'OPEN VISIBILITY, CAN BE VIEWED BY ALL LOGGED IN USERS'); -INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('ROLES', 'ROLE BASED RESTRICTION, CAN BE VIEWED BY ONLY GIVEN - SET OF USER WHO HAVE THE SPECIFIED ROLE'); -INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('DEVICE_GROUPS', 'DEVICE GROUP LEVEL RESTRICTION, -CAN BE VIEWED BY THE DEVICES/ROLES BELONG TO THE GROUP'); +CREATE INDEX `fk_AP_APP_TAGS_AP_APP1_idx` ON `AP_APP_TAG` (`AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_SUBSCRIPTION` +-- Table `AP_DEVICE_SUBSCRIPTION` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_SUBSCRIPTION` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `VALUE` VARCHAR(255) NOT NULL, - `CREATED_AT` DATETIME NOT NULL, - `RESOURCE_TYPE_ID` INT NOT NULL, - `APPLICATION_ID` INT NOT NULL, - `APPLICATION_RELEASE_ID` INT NULL, - PRIMARY KEY (`ID`, `APPLICATION_ID`, `RESOURCE_TYPE_ID`), - INDEX `FK_APPLICATION_SUBSCRIPTION_RESOURCE_TYPE` (`RESOURCE_TYPE_ID` ASC), - INDEX `FK_APPLICATION_SUBSCRIPTION_APPLICATION` (`APPLICATION_ID` ASC), - INDEX `FK_APPLICATION_SUBSCRIPTION_APPLICATION_RELEASE` (`APPLICATION_RELEASE_ID` ASC), - CONSTRAINT `fk_APPM_APPLICATION_SUBSCRIPTION_APPM_RESOURCE_TYPE1` - FOREIGN KEY (`RESOURCE_TYPE_ID`) - REFERENCES `APPM_RESOURCE_TYPE` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION1` - FOREIGN KEY (`APPLICATION_ID`) - REFERENCES `APPM_APPLICATION` (`ID`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION_RELEASE1` - FOREIGN KEY (`APPLICATION_RELEASE_ID`) - REFERENCES `APPM_APPLICATION_RELEASE` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_DEVICE_SUBSCRIPTION` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `SUBSCRIBED_BY` VARCHAR(100) NOT NULL, + `SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `UNSUBSCRIBED` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL, + `DM_ENROLMENT_ID` INT(11) NOT NULL, + `AP_APP_RELEASE_ID` INT(11) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + CONSTRAINT `fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1` + FOREIGN KEY (`AP_APP_ID` , `AP_APP_RELEASE_ID`) + REFERENCES `AP_APP_RELEASE` (`AP_APP_ID` , `ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the application subscriptions'; + DEFAULT CHARACTER SET = utf8; + +CREATE INDEX `fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_DEVICE_SUBSCRIPTION` (`AP_APP_ID` ASC, `AP_APP_RELEASE_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_COMMENT` +-- Table `AP_GROUP_SUBSCRIPTION` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_COMMENT` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `APPLICATION_RELEASE_ID` INT NOT NULL, - `COMMENT_SUBJECT` VARCHAR(255) NULL, - `COMMENT_BODY` TEXT NULL, - `RATING` INT NULL, - `PARENT_ID` INT NULL, - `CREATED_AT` DATETIME NOT NULL, - `CREATED_BY` VARCHAR(45) NULL, - `MODIFIED_AT` DATETIME NULL, - `PUBLISHED` TINYINT(1) NULL, - `APPROVED` TINYINT(1) NULL, - PRIMARY KEY (`ID`, `APPLICATION_RELEASE_ID`), - INDEX `FK_APPLICATION_COMMENTS_APPLICATION_RELEASE` (`APPLICATION_RELEASE_ID` ASC), - CONSTRAINT `FK_APPLICATION_COMMENTS_APPLICATION_RELEASE` - FOREIGN KEY (`APPLICATION_RELEASE_ID`) - REFERENCES `APPM_APPLICATION_RELEASE` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_GROUP_SUBSCRIPTION` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `SUBSCRIBED_BY` VARCHAR(100) NOT NULL, + `SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `UNSUBSCRIBED` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL, + `DM_GROUP_ID` INT(11) NOT NULL, + `AP_APP_RELEASE_ID` INT(11) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + CONSTRAINT `fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1` + FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`) + REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the application comments'; + DEFAULT CHARACTER SET = utf8; - --- ----------------------------------------------------- --- Table `APPM_PLATFORM_TAG` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_PLATFORM_TAG` ( - `name` VARCHAR(100) NOT NULL, - `PLATFORM_ID` INT NOT NULL, - PRIMARY KEY (`PLATFORM_ID`, `name`), - INDEX `FK_PLATFORM_TAGS_PLATFORM` (`PLATFORM_ID` ASC), - CONSTRAINT `fk_APPM_SUPPORTED_PLATFORM_TAGS_APPM_SUPPORTED_PLATFORM1` - FOREIGN KEY (`PLATFORM_ID`) - REFERENCES `APPM_PLATFORM` (`ID`) - ON DELETE CASCADE - ON UPDATE CASCADE) - ENGINE = InnoDB - COMMENT = 'This table contains the data related to the app platform tag'; +CREATE INDEX `fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_GROUP_SUBSCRIPTION` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_APPLICATION_TAG` +-- Table `AP_ROLE_SUBSCRIPTION` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_TAG` ( - `NAME` VARCHAR(45) NOT NULL, - `APPLICATION_ID` INT NOT NULL, - PRIMARY KEY (`APPLICATION_ID`, `NAME`), - INDEX `FK_APPLICATION_TAG_APPLICATION` (`APPLICATION_ID` ASC), - CONSTRAINT `fk_APPM_APPLICATION_TAG_APPM_APPLICATION1` - FOREIGN KEY (`APPLICATION_ID`) - REFERENCES `APPM_APPLICATION` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_ROLE_SUBSCRIPTION` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `ROLE_NAME` VARCHAR(100) NOT NULL, + `SUBSCRIBED_BY` VARCHAR(100) NOT NULL, + `SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `UNSUBSCRIBED` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL, + `AP_APP_RELEASE_ID` INT(11) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + CONSTRAINT `fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1` + FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`) + REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB - COMMENT = 'This table contains the data related to the application tags'; + DEFAULT CHARACTER SET = utf8; + +CREATE INDEX `fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_ROLE_SUBSCRIPTION` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_VISIBILITY` +-- Table `AP_UNRESTRICTED_ROLE` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_VISIBILITY` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `VALUE` VARCHAR(255), - `RESOURCE_TYPE_ID` INT NOT NULL, - `APPLICATION_ID` INT NULL, +CREATE TABLE IF NOT EXISTS `AP_UNRESTRICTED_ROLE` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `ROLE` VARCHAR(45) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, PRIMARY KEY (`ID`), - INDEX `FK_APPM_VISIBILITY_RESOURCE_TYPE` (`RESOURCE_TYPE_ID` ASC), - INDEX `FK_VISIBILITY_APPLICATION` (`APPLICATION_ID` ASC), - CONSTRAINT `fk_APPM_VISIBILITY_APPM_RESOURCE_TYPE1` - FOREIGN KEY (`RESOURCE_TYPE_ID`) - REFERENCES `APPM_RESOURCE_TYPE` (`ID`) + CONSTRAINT `fk_AP_APP_VISIBILITY_AP_APP1` + FOREIGN KEY (`AP_APP_ID`) + REFERENCES `AP_APP` (`ID`) ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_APPM_VISIBILITY_APPM_APPLICATION1` - FOREIGN KEY (`APPLICATION_ID`) - REFERENCES `APPM_APPLICATION` (`ID`) - ON DELETE CASCADE - ON UPDATE CASCADE ) - ENGINE = InnoDB; + ON UPDATE NO ACTION) + ENGINE = InnoDB + DEFAULT CHARACTER SET = utf8; + +CREATE INDEX `fk_AP_APP_VISIBILITY_AP_APP1_idx` ON `AP_UNRESTRICTED_ROLE` (`AP_APP_ID` ASC); -- ----------------------------------------------------- --- Table `APPM_SUBSCRIPTION_PROPERTIES` +-- Table `AP_USER_SUBSCRIPTION` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_SUBSCRIPTION_PROPERTIES` ( - `PROP_KEY` VARCHAR(255) NOT NULL, - `PROP_VALUE` TEXT NULL, - `APPM_SUBSCRIPTION_ID` INT NOT NULL, - PRIMARY KEY (`PROP_KEY`, `APPM_SUBSCRIPTION_ID`), - INDEX `FK_SUBSCRIPTION_PROPERTIES_SUBSCRIPTION` (`APPM_SUBSCRIPTION_ID` ASC), - CONSTRAINT `fk_APPM_SUBSCRIPTION_PROPERTIES_APPM_SUBSCRIPTION1` - FOREIGN KEY (`APPM_SUBSCRIPTION_ID`) - REFERENCES `APPM_SUBSCRIPTION` (`ID`) +CREATE TABLE IF NOT EXISTS `AP_USER_SUBSCRIPTION` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `TENANT_ID` VARCHAR(45) NOT NULL, + `USER_NAME` VARCHAR(100) NOT NULL, + `SUBSCRIBED_BY` VARCHAR(100) NOT NULL, + `SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `UNSUBSCRIBED` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL, + `UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL, + `AP_APP_RELEASE_ID` INT(11) NOT NULL, + `AP_APP_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + CONSTRAINT `fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1` + FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`) + REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) - ENGINE = InnoDB; + ENGINE = InnoDB + DEFAULT CHARACTER SET = utf8; --- ----------------------------------------------------- --- Table `APPM_DEVICE_APPLICATION_MAPPING` --- ----------------------------------------------------- --- CREATE TABLE IF NOT EXISTS `APPM_DEVICE_APPLICATION_MAPPING` ( --- `ID` INT AUTO_INCREMENT NOT NULL, --- `DEVICE_IDENTIFIER` VARCHAR(255) NOT NULL, --- `APPLICATION_UUID` VARCHAR(100) NOT NULL, --- `INSTALLED` BOOLEAN NOT NULL, --- `SENT_AT` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, --- PRIMARY KEY (ID), --- CONSTRAINT `fk_appm_application` FOREIGN KEY (`APPLICATION_UUID`) REFERENCES --- APPM_APPLICATION (`UUID`) ON DELETE NO ACTION ON UPDATE NO ACTION, --- UNIQUE KEY `device_app_mapping` (`DEVICE_IDENTIFIER`, `APPLICATION_UUID`) --- ) ENGINE = InnoDB; +CREATE INDEX `fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_USER_SUBSCRIPTION` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC); SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; From 6066d93edd8e173ecd54d9e3a15c70314dbf1e3e Mon Sep 17 00:00:00 2001 From: lasanthaDLPDS Date: Wed, 19 Sep 2018 07:27:49 +0530 Subject: [PATCH 04/10] Add review management --- .../application/mgt/common/Comment.java | 110 ----- .../mgt/common/LifecycleState.java | 2 +- .../device/application/mgt/common/Rating.java | 66 +++ .../device/application/mgt/common/Review.java | 114 +++++ .../mgt/common/services/CommentsManager.java | 120 ----- .../mgt/common/services/ReviewManager.java | 89 ++++ .../mgt/core/dao/ApplicationReleaseDAO.java | 13 +- .../dao/{CommentDAO.java => ReviewDAO.java} | 68 +-- .../ApplicationManagementDAOFactory.java | 6 +- ...CommentDAOImpl.java => ReviewDAOImpl.java} | 416 ++++++++++-------- .../GenericApplicationDAOImpl.java | 2 +- .../GenericApplicationReleaseDAOImpl.java | 50 ++- .../mgt/core/impl/CommentsManagerImpl.java | 289 ------------ .../mgt/core/impl/ReviewManagerImpl.java | 398 +++++++++++++++++ .../mgt/core/internal/DataHolder.java | 12 +- .../mgt/core/internal/ServiceComponent.java | 8 +- .../core/util/ApplicationManagementUtil.java | 6 +- .../src/test/resources/application-mgt.xml | 2 +- .../application/mgt/store/api/APIUtil.java | 14 +- .../api/services/ReviewManagementAPI.java | 146 ++---- .../impl/ReviewManagementAPIImpl.java | 142 +++--- ...Test.java => ReviewManagementAPITest.java} | 175 +++----- .../services/util/CommentMgtTestHelper.java | 30 +- .../src/test/resources/testng.xml | 2 +- 24 files changed, 1171 insertions(+), 1109 deletions(-) delete mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Rating.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java delete mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java rename components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/{CommentDAO.java => ReviewDAO.java} (86%) rename components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/{CommentDAOImpl.java => ReviewDAOImpl.java} (71%) delete mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java rename components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/{CommentManagementAPITest.java => ReviewManagementAPITest.java} (59%) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java deleted file mode 100644 index a01176a8cca..00000000000 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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. - * - */ -package org.wso2.carbon.device.application.mgt.common; - -import java.sql.Timestamp; - -/** - * Represents a commentText for an {@link Application}. - */ -public class Comment { - - private int id; - - private String commentText; - - //TODO: Pagination, commentText ID for child - private int parent; - - private int tenantId; - - private String createdBy; - - private Timestamp createdAt; - - private String modifiedBy; - - private Timestamp modifiedAt; - - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getCommentText() { - return commentText; - } - - public void setCommentText(String commentText) { - this.commentText = commentText; - } - - public int getParent() { - return parent; - } - - public void setParent(int parent) { - this.parent = parent; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Timestamp getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Timestamp createdAt) { - this.createdAt = createdAt; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Timestamp getModifiedAt() { - return modifiedAt; - } - - public void setModifiedAt(Timestamp modifiedAt) { - this.modifiedAt = modifiedAt; - } - -} - diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java index 2c0dc8349bb..0fcec128374 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java @@ -24,7 +24,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.List; -@ApiModel(value = "LifecycleState", description = "LifecycleState represents the an Lifecycle state for an application release") +@ApiModel(value = "LifecycleState", description = "LifecycleState represents the Lifecycle state for an application release") public class LifecycleState { @ApiModelProperty(name = "id", diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Rating.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Rating.java new file mode 100644 index 00000000000..51caf0c52f5 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Rating.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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. + * + */ +package org.wso2.carbon.device.application.mgt.common; + +import java.util.TreeMap; + +/** + * Rating represents the an overall rating value and number of users who has rated for an application release. + */ +public class Rating { + + /** + * Rating value of the application release. + */ + private double ratingValue; + + /** + * Number of users who has rated for the application release. + */ + private int noOfUsers; + + /** + * Represent the rating variety for the application release + */ + private TreeMap ratingVariety; + + public double getRatingValue() { + return ratingValue; + } + + public void setRatingValue(double ratingValue) { + this.ratingValue = ratingValue; + } + + public int getNoOfUsers() { + return noOfUsers; + } + + public void setNoOfUsers(int noOfUsers) { + this.noOfUsers = noOfUsers; + } + + public TreeMap getRatingVariety() { + return ratingVariety; + } + + public void setRatingVariety(TreeMap ratingVariety) { + this.ratingVariety = ratingVariety; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java new file mode 100644 index 00000000000..2a1b33976a2 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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. + * + */ +package org.wso2.carbon.device.application.mgt.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.sql.Timestamp; + +@ApiModel(value = "Review", description = "Review represents the user's review for an application release") +public class Review { + + @ApiModelProperty(name = "id", + value = "The Id given to the comment when it store to the App manager") + private int id; + + @ApiModelProperty(name = "comment", + value = "Comment of the review") + private String comment; + + @ApiModelProperty(name = "replyComment", + value = "Reply comment of the review") + private String replyComment; + + @ApiModelProperty(name = "username", + value = "Username odf the Review creator", + required = true) + private String username; + + @ApiModelProperty(name = "createdAt", + value = "Timestamp fo the review is created") + private Timestamp createdAt; + + @ApiModelProperty(name = "modifiedAt", + value = "Timestamp of the review is modified") + private Timestamp modifiedAt; + + @ApiModelProperty(name = "rating", + value = "Rating value of the application release") + private int rating; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Timestamp getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Timestamp createdAt) { + this.createdAt = createdAt; + } + + public Timestamp getModifiedAt() { + return modifiedAt; + } + + public void setModifiedAt(Timestamp modifiedAt) { + this.modifiedAt = modifiedAt; + } + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } + + public String getReplyComment() { + return replyComment; + } + + public void setReplyComment(String replyComment) { + this.replyComment = replyComment; + } +} + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java deleted file mode 100644 index 9a5269e2369..00000000000 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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. - * - */ -package org.wso2.carbon.device.application.mgt.common.services; - -import org.wso2.carbon.device.application.mgt.common.Comment; -import org.wso2.carbon.device.application.mgt.common.PaginationRequest; -import org.wso2.carbon.device.application.mgt.common.PaginationResult; -import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; - -import java.util.List; - -/** - * CommentsManager is responsible for handling all the add/update/delete/get operations related with - */ -public interface CommentsManager { - - /** - * To add a comment to a application - * - * @param comment comment of the application. - * @param uuid uuid of the application release\ - * @return {@link Comment} Comment added - * @throws CommentManagementException Exceptions of the comment management. - */ - Comment addComment(Comment comment, String uuid) throws CommentManagementException; - - /** - * To validate the pre-request of the comment - * - * @param commentId ID of the comment. - * @param comment comment needed to be validate. - * @return validated the comment. - * @throws CommentManagementException Exceptions of the comment management. - */ - Boolean validateComment(int commentId, String comment) throws CommentManagementException; - - /** - * Get all comments to pagination - * - * @param request Pagination request - * @param uuid uuid of the application release - * @return {@link PaginationResult} pagination result with starting offSet and limit - * @throws CommentManagementException Exceptions of the comment management. - */ - PaginationResult getAllComments(PaginationRequest request, String uuid) throws CommentManagementException; - - /** - * To get the comment with id. - * - * @param commentId id of the comment - * @return {@link Comment}Comment of the comment id - * @throws CommentManagementException Exceptions of the comment management. - */ - Comment getComment(int commentId) throws CommentManagementException; - - /** - * To delete comment using comment id. - * - * @param commentId id of the comment - * @throws CommentManagementException Exceptions of the comment management - */ - void deleteComment(int commentId) throws CommentManagementException; - - /** - * To update a comment. - * - * @param comment comment of the application. - * @param commentId id of the comment - * @return {@link Comment}updated comment - * @throws CommentManagementException Exceptions of the comment management - */ - Comment updateComment(Comment comment, int commentId) throws CommentManagementException; - - /** - * To get number of rated users - * - * @param uuid uuid of the application - * @return number of rated users - * @throws CommentManagementException Exceptions of the comment management - * @throws ApplicationManagementException Application Management Exception. - */ - int getRatedUser(String uuid) throws CommentManagementException, ApplicationManagementException; - - /** - * To get the average of stars - * - * @param uuid uuid of the comment - * @return value of the stars of an application - * @throws CommentManagementException Exceptions of the comment management - * @throws ApplicationManagementException Application Management Exception. - */ - int getStars(String uuid) throws CommentManagementException, ApplicationManagementException; - - /** - * To update rating stars - * - * @param stars amount of stars - * @param uuid uuid of the application - * @return value of the added stars - * @throws ApplicationManagementException Application Management Exception. - */ - int updateStars(int stars, String uuid) throws ApplicationManagementException; -} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java new file mode 100644 index 00000000000..d9e62337efc --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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. + * + */ +package org.wso2.carbon.device.application.mgt.common.services; + +import org.wso2.carbon.device.application.mgt.common.Rating; +import org.wso2.carbon.device.application.mgt.common.Review; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.PaginationResult; +import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; + +/** + * ReviewManager is responsible for handling all the add/update/delete/get operations related with + */ +public interface ReviewManager { + + /** + * To add a review to a application + * + * @param review review of the application. + * @param appId id of the application. + * @param appReleaseId id of the application release + * @return {@link Review} Review added + * @throws CommentManagementException Exceptions of the review management. + */ + boolean addReview(Review review,int appId, int appReleaseId) throws CommentManagementException; + + /** + * Get all comments to pagination + * + * @param request Pagination request + * @param uuid uuid of the application release + * @return {@link PaginationResult} pagination result with starting offSet and limit + * @throws CommentManagementException Exceptions of the comment management. + */ + PaginationResult getAllReviews(PaginationRequest request, String uuid) throws CommentManagementException; + + /** + * To get the comment with id. + * + * @param commentId id of the comment + * @return {@link Review}Review of the comment id + * @throws CommentManagementException Exceptions of the comment management. + */ + Review getReview(int commentId) throws CommentManagementException; + + /** + * To delete review using review id. + * + * @param commentId id of the comment + * @throws CommentManagementException Exceptions of the comment management + */ + void deleteReview(String loggedInUser, int commentId) throws CommentManagementException; + + /** + * To update a review. + * + * @param review review of the application. + * @param reviewId id of the review + * @return {@link Review}updated review + * @throws CommentManagementException Exceptions of the review management + */ + boolean updateReview(Review review, int reviewId, boolean checkExistence) throws CommentManagementException; + + /** + * To get the overall rating for a application release + * + * @param appReleaseUuuid UUID of the application release. + * @return {@link Review}updated review + * @throws CommentManagementException Exceptions of the review management + */ + Rating getRating(String appReleaseUuuid) throws CommentManagementException; +} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java index 4d40ca52021..e3bcfecad2e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.application.mgt.core.dao; import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; +import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import java.util.List; @@ -80,10 +81,18 @@ public interface ApplicationReleaseDAO { /** * To update an Application release. * @param id id of the ApplicationRelease that need to be updated. - * @param stars given stars for the application. + * @param rating given stars for the application. + * @param ratedUsers number of users who has rated for the application release. * @throws ApplicationManagementDAOException Application Management DAO Exception */ - void updateStars(int id, int stars) throws ApplicationManagementDAOException; + int updateRatingValue(int id, double rating, int ratedUsers) throws ApplicationManagementDAOException; + + /** + * To retrieve rating of an application release. + * @param id Id of the application Release. + * @throws ApplicationManagementDAOException Application Management DAO Exception. + */ + Rating getRating(int id) throws ApplicationManagementDAOException; /** diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java similarity index 86% rename from components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java rename to components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java index 429635bf10c..009823af99c 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java @@ -18,7 +18,7 @@ */ package org.wso2.carbon.device.application.mgt.core.dao; -import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; @@ -32,35 +32,40 @@ import java.util.List; * This interface specifies the database access operations performed for comments. */ - public interface CommentDAO { + public interface ReviewDAO { /** - * To add a comment to a application. + * To add a review to a application. * * @param tenantId tenantId of the commented application. - * @param comment comment of the application. + * @param review review of the application. * @param createdBy Username of the created person. - * @param parentId parent id of the parent comment. + * @param parentId parent id of the parent review. * @param uuid uuid of the application - * @return If comment is added successfully, it return true otherwise false - * @throws CommentManagementException Exceptions of the comment management. + * @return If review is added successfully, it return true otherwise false + * @throws CommentManagementException Exceptions of the review management. * @throws DBConnectionException db connection exception. */ - boolean addComment(int tenantId, Comment comment, String createdBy, int parentId, String uuid) + boolean addReview(Review review, int appId, int appReleaseId, int tenantId) throws CommentManagementException, DBConnectionException, SQLException; + + Review isExistReview(int appId, int appReleaseId, String username, int tenantId) + throws DBConnectionException, SQLException; + + /** - * To add a comment to a application. + * To add a review to a application. * - * @param comment comment of the application. + * @param review review of the application. * @param createdBy Username of the created person. * @param appType type of the commented application. * @param appName name of the commented application. * @param version version of the commented application. - * @return comment id - * @throws CommentManagementException Exceptions of the comment management. + * @return review id + * @throws CommentManagementException Exceptions of the review management. */ - int addComment(int tenantId, Comment comment, String createdBy, String appType, String appName, String version) + int addReview(int tenantId, Review review, String createdBy, String appType, String appName, String version) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -70,12 +75,12 @@ import java.util.List; * @param updatedComment comment after updated * @param modifiedBy Username of the modified person. * @param modifiedAt time of the modification. - * @return {@link Comment}Updated comment + * @return {@link Review}Updated comment * @throws CommentManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception * @throws SQLException sql exception */ - Comment updateComment(int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) + boolean updateReview(Review review, int reviewId, int tenantId) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -86,24 +91,24 @@ import java.util.List; * @param updatedComment comment after updated * @param modifiedBy Username of the modified person. * @param modifiedAt time of the modification. - * @return {@link Comment}Updated comment + * @return {@link Review}Updated comment * @throws CommentManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception * @throws SQLException sql exception */ - Comment updateComment(String uuid, int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) + Review updateReview(String uuid, int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException; /** * To get the comment with id. * * @param commentId id of the comment - * @return {@link Comment}Comment + * @return {@link Review}Review * @throws CommentManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception * @throws SQLException sql exception */ - Comment getComment(int commentId) throws CommentManagementException, SQLException, DBConnectionException; + Review getComment(int commentId) throws CommentManagementException, SQLException, DBConnectionException; /** * To get the comment with id. @@ -114,7 +119,7 @@ import java.util.List; * @throws DBConnectionException db connection exception * @throws SQLException sql exception */ - List getComment(String uuid) throws CommentManagementException, SQLException, DBConnectionException; + List getComment(String uuid) throws CommentManagementException, SQLException, DBConnectionException; /** * To get all the comments @@ -125,7 +130,7 @@ import java.util.List; * @throws DBConnectionException db connection exception * @throws SQLException sql exception **/ - List getAllComments(String uuid, PaginationRequest request) throws SQLException, DBConnectionException; + List getAllComments(String uuid, PaginationRequest request) throws SQLException, DBConnectionException; /** * To get list of comments using release id and application id. @@ -135,7 +140,10 @@ import java.util.List; * @return {@link List}List of comments * @throws CommentManagementException Exceptions of the comment management. */ - List getComments(int appReleasedId, int appId) throws CommentManagementException; + + List getAllRatingValues(String uuid)throws SQLException, DBConnectionException; + + List getComments(int appReleasedId, int appId) throws CommentManagementException; /** * To get list of comments using application type, application name and version of the application. @@ -148,7 +156,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getComments(String appType, String appName, String version) + List getComments(String appType, String appName, String version) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -160,7 +168,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getComments(int tenantId) throws CommentManagementException, DBConnectionException, SQLException; + List getComments(int tenantId) throws CommentManagementException, DBConnectionException, SQLException; /** * To get list of comments by created user. @@ -171,7 +179,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getCommentsByUser(String createdBy) + List getCommentsByUser(String createdBy) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -184,7 +192,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getCommentsByUser(String createdBy, Timestamp createdAt) + List getCommentsByUser(String createdBy, Timestamp createdAt) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -196,7 +204,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getCommentsByModifiedUser(String modifiedBy) + List getCommentsByModifiedUser(String modifiedBy) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -209,7 +217,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) + List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -224,7 +232,7 @@ import java.util.List; * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - List getComments(String appType, String appName, String version, int parentId) + List getComments(String appType, String appName, String version, int parentId) throws CommentManagementException, DBConnectionException, SQLException; /** @@ -398,7 +406,7 @@ import java.util.List; * * @param request * @param uuid - * @return Comment count + * @return Review count * @throws CommentManagementException */ int getCommentCount(PaginationRequest request, String uuid) throws CommentManagementException; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java index 0ab4126a1e7..368111b9e08 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java @@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; import org.wso2.carbon.device.application.mgt.core.dao.*; -import org.wso2.carbon.device.application.mgt.core.dao.impl.Comment.CommentDAOImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.Comment.ReviewDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.application.release.GenericApplicationReleaseDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.application.OracleApplicationDAOImpl; @@ -162,13 +162,13 @@ public class ApplicationManagementDAOFactory { throw new IllegalStateException("Database engine has not initialized properly."); } - public static CommentDAO getCommentDAO() { + public static ReviewDAO getCommentDAO() { if (databaseEngine != null) { switch (databaseEngine) { case Constants.DataBaseTypes.DB_TYPE_H2: case Constants.DataBaseTypes.DB_TYPE_MYSQL: case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: - return new CommentDAOImpl(); + return new ReviewDAOImpl(); default: throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/CommentDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java similarity index 71% rename from components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/CommentDAOImpl.java rename to components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java index 497e10c395d..80b8c03b152 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/CommentDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java @@ -22,11 +22,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; -import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.core.dao.CommentDAO; +import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.Util; import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; @@ -40,20 +40,21 @@ import java.util.ArrayList; import java.util.List; /** - * This handles CommentDAO related operations. + * This handles ReviewDAO related operations. */ -public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { +public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { - private static final Log log = LogFactory.getLog(CommentDAOImpl.class); + private static final Log log = LogFactory.getLog(ReviewDAOImpl.class); private String sql; @Override - public boolean addComment(int tenantId, Comment comment, String createdBy, int parentId, String uuid) + public boolean addReview(Review review, int appId, int appReleaseId, int tenantId) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to add comment for application release (" + uuid + ")"); + log.debug("Request received in DAO Layer to add review for application release. Application id: " + appId + + "Application Release id: " + appReleaseId); } Connection conn = this.getDBConnection(); PreparedStatement statement = null; @@ -64,11 +65,11 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { try { statement = conn.prepareStatement(sql, new String[] { "id" }); statement.setInt(1, tenantId); - statement.setString(2, comment.getCommentText()); - statement.setString(3, createdBy); - statement.setInt(4, parentId); - statement.setString(5, uuid); - statement.setString(6, uuid); + statement.setString(2, review.getComment()); +// statement.setString(3, createdBy); +// statement.setInt(4, parentId); +// statement.setString(5, uuid); +// statement.setString(6, uuid); statement.executeUpdate(); rs = statement.getGeneratedKeys(); return rs.next(); @@ -78,7 +79,47 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { } @Override - public int addComment(int tenantId, Comment comment, String createdBy, String appType, String appName, + public Review isExistReview(int appId, int appReleaseId, String username, int tenantId) + throws DBConnectionException, SQLException { + if (log.isDebugEnabled()) { + log.debug( + "Request received in DAO Layer to check whether review exist or not rein the IoTS APPM. Application id: " + + appId + " Application release id: " + appReleaseId + " comment owner: " + username); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs = null; + Review review = null; + sql = "SELECT ID, COMMENT, REPLY_COMMENT, CREATED_AT, MODEFIED_AT, USERNAME, PARENT_ID, RATING FROM AP_APP_REVIEW " + + "WHERE AP_APP_ID = ? AND AP_APP_RELEASE_ID = ? AND USERNAME = ? AND TENANT_ID = ?;"; + try { + conn = this.getDBConnection(); + statement = conn.prepareStatement(sql); + statement.setInt(1, appId); + statement.setInt(2, appReleaseId); + statement.setString(3, username); + statement.setInt(4, tenantId); + + rs = statement.executeQuery(); + if (rs.next()){ + review = new Review(); + review.setId(rs.getInt("ID")); + review.setComment(rs.getString("COMMENT")); + review.setReplyComment(rs.getString("REPLY_COMMENT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setModifiedAt(rs.getTimestamp("MODIFIED_AT")); + review.setUsername(rs.getString("USERNAME")); + review.setRating(rs.getInt("RATING")); + } + return review; + } finally { + Util.cleanupResources(statement, rs); + } + } + + + @Override + public int addReview(int tenantId, Review review, String createdBy, String appType, String appName, String version) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { @@ -95,7 +136,7 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { try { statement = conn.prepareStatement(sql, new String[] { "id" }); statement.setInt(1, tenantId); - statement.setString(2, comment.getCommentText()); + statement.setString(2, review.getComment()); statement.setString(3, createdBy); statement.setString(4, version); statement.setString(5, appType); @@ -114,11 +155,10 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { } @Override - public Comment updateComment(int commentId, String updatedComment, String modifiedBy, - Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException { + public boolean updateReview(Review review, int reviewId, int tenantId) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to update the comment with ID (" + commentId + ")"); + log.debug("Request received in DAO Layer to update the comment with ID (" + reviewId + ")"); } Connection connection; PreparedStatement statement = null; @@ -127,19 +167,20 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { try { connection = this.getDBConnection(); statement = connection.prepareStatement(sql); - statement.setString(1, updatedComment); - statement.setString(2, modifiedBy); - statement.setInt(3, commentId); +// statement.setString(1, updatedComment); +// statement.setString(2, modifiedBy); + statement.setInt(3, reviewId); statement.executeUpdate(); rs = statement.executeQuery(); } finally { Util.cleanupResources(statement, rs); } - return getComment(commentId); + // todo + return false; } @Override - public Comment updateComment(String uuid, int commentId, String updatedComment, String modifiedBy, + public Review updateReview(String uuid, int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { @@ -165,15 +206,15 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { } @Override - public Comment getComment(int commentId) throws CommentManagementException { + public Review getComment(int commentId) throws CommentManagementException { if (log.isDebugEnabled()) { - log.debug("Getting comment with the comment id(" + commentId + ") from the database"); + log.debug("Getting review with the review id(" + commentId + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - Comment comment = new Comment(); + Review review = new Review(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE ID=?;"; @@ -181,30 +222,28 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setInt(1, commentId); rs = statement.executeQuery(); if (rs.next()) { - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("MODEFIED_AT")); - comment.setParent(rs.getInt("PARENT_ID")); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); Util.cleanupResources(statement, rs); - return comment; + return review; } } catch (SQLException e) { throw new CommentManagementException( - "SQL Error occurred while retrieving information of the comment " + commentId, e); + "SQL Error occurred while retrieving information of the review " + commentId, e); } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while retrieving information of the comment " + commentId, e); + log.error("DB Connection Exception occurred while retrieving information of the review " + commentId, e); } finally { Util.cleanupResources(statement, null); } - return comment; + return review; } @Override - public List getComment(String uuid) throws CommentManagementException { + public List getComment(String uuid) throws CommentManagementException { if (log.isDebugEnabled()) { log.debug("Getting comment with the application release(" + uuid + ") from the database"); @@ -212,7 +251,7 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE (SELECT ID FROM AP_APP_RELEASE where UUID=?)AND " @@ -222,29 +261,27 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setString(2, uuid); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("MODEFIED_AT")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while retrieving comments", e); + log.error("DB Connection Exception occurred while retrieving reviews", e); } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurred while retrieving comments", e); + throw new CommentManagementException("SQL Error occurred while retrieving reviews", e); } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getAllComments(String uuid, PaginationRequest request) + public List getAllComments(String uuid, PaginationRequest request) throws SQLException, DBConnectionException { if (log.isDebugEnabled()) { @@ -253,36 +290,61 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { Connection conn; PreparedStatement statement = null; ResultSet rs = null; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); - sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS COMMENT_TEXT, " - + "AP_APP_COMMENT.CREATED_AT AS CREATED_AT, AP_APP_COMMENT.CREATED_BY AS CREATED_BY, " - + "AP_APP_COMMENT.MODIFIED_AT AS MODIFIED_AT, AP_APP_COMMENT.MODIFIED_BY AS MODIFIED_BY, " - + "AP_APP_COMMENT.PARENT_ID AS PARENT_ID, AP_APP_COMMENT.TENANT_ID AS TENANT_ID FROM" - + " AP_APP_COMMENT, AP_APP_RELEASE WHERE AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID " - + "AND AP_APP_RELEASE.UUID =? LIMIT ? OFFSET ?;"; + sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS " + + "COMMENT_TEXT, AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS " + + "MODIFIED_BY, AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE " + + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND " + + "AP_APP_COMMENT.TENANT_ID = ? AND AP_APP_COMMENT.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + + "LIMIT ? OFFSET ?;"; statement = conn.prepareStatement(sql); statement.setString(1, uuid); statement.setInt(2, request.getLimit()); statement.setInt(3, request.getOffSet()); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODIFIED_AT")); - comment.setModifiedBy(rs.getString("MODIFIED_BY")); - comment.setParent(rs.getInt("PARENT_ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setUsername(rs.getString("CREATED_BY")); + reviews.add(review); + } + } finally { + Util.cleanupResources(statement, rs); + } + return reviews; + } + + @Override + public List getAllRatingValues(String uuid)throws SQLException, DBConnectionException { + + if (log.isDebugEnabled()) { + log.debug("Getting comment of the application release (" + uuid + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs = null; + List reviews = new ArrayList<>(); + try { + conn = this.getDBConnection(); +// todo + sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS " + + "COMMENT_TEXT, AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS " + + "MODIFIED_BY, AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE " + + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND " + + "AP_APP_COMMENT.TENANT_ID = ? AND AP_APP_COMMENT.TENANT_ID = AP_APP_RELEASE.TENANT_ID;"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + rs = statement.executeQuery(); + while (rs.next()) { + reviews.add(rs.getInt("RATING")); } } finally { Util.cleanupResources(statement, rs); } - return comments; + return reviews; } @Override @@ -320,16 +382,16 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { } @Override - public List getComments(int appReleasedId, int appId) throws CommentManagementException { + public List getComments(int appReleasedId, int appId) throws CommentManagementException { if (log.isDebugEnabled()) { - log.debug("Getting comments with the application release id(" + appReleasedId + ") and " + "application id(" + log.debug("Getting reviews with the application release id(" + appReleasedId + ") and " + "application id(" + appId + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? AND AP_APP_ID=?;"; @@ -338,39 +400,37 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setInt(2, appId); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while retrieving information of comments", e); + log.error("DB Connection Exception occurred while retrieving information of reviews", e); } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurred while retrieving information of comments", e); + throw new CommentManagementException("SQL Error occurred while retrieving information of reviews", e); } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getComments(String appType, String appName, String version) + public List getComments(String appType, String appName, String version) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Getting comments with the application name(" + appName + "),application type(" + appType + ") " + log.debug("Getting reviews with the application name(" + appName + "),application type(" + appType + ") " + "and application version (" + version + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID FROM AP_APP_COMMENT C ," @@ -384,34 +444,32 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setString(3, appType); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getComments(int tenantId) + public List getComments(int tenantId) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Getting comments with the tenant_id(" + tenantId + ") from the database"); + log.debug("Getting reviews with the tenant_id(" + tenantId + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE TENANT_ID='?';"; @@ -419,34 +477,32 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setInt(1, tenantId); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getCommentsByUser(String createdBy) + public List getCommentsByUser(String createdBy) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Getting comments with the created by(" + createdBy + ") from the database"); + log.debug("Getting reviews with the created by(" + createdBy + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT ,PARENT_ID,TENANT_ID,CREATED_AT FROM AP_APP_COMMENT WHERE CREATED_BY= ?" @@ -455,35 +511,33 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setString(1, createdBy); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getCommentsByUser(String createdBy, Timestamp createdAt) + public List getCommentsByUser(String createdBy, Timestamp createdAt) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { log.debug( - "Getting comments with the created by(" + createdBy + ") at (" + createdAt + ") from the database"); + "Getting reviews with the created by(" + createdBy + ") at (" + createdAt + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID FROM AP_APP_COMMENT WHERE CREATED_BY=?" @@ -493,34 +547,32 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setTimestamp(2, createdAt); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getCommentsByModifiedUser(String modifiedBy) + public List getCommentsByModifiedUser(String modifiedBy) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Getting comments with the modified by(" + modifiedBy + ") from the database"); + log.debug("Getting reviews with the modified by(" + modifiedBy + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID,CREATED_AT,MODEFIED_AT FROM AP_APP_COMMENT " @@ -529,35 +581,33 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setString(1, modifiedBy); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) + public List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { - log.debug("Getting comments with the modified by(" + modifiedBy + ") at (" + modifiedAt + ") from the " + log.debug("Getting reviews with the modified by(" + modifiedBy + ") at (" + modifiedAt + ") from the " + "database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID,CREATED_AT FROM AP_APP_COMMENT WHERE MODEFIED_BY= ?," @@ -567,36 +617,34 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setTimestamp(2, modifiedAt); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override - public List getComments(String appType, String appName, String version, int parentId) + public List getComments(String appType, String appName, String version, int parentId) throws CommentManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { log.debug( - "Getting comments with the application name(" + appName + "),application type(" + appType + ") and" + "Getting reviews with the application name(" + appName + "),application type(" + appType + ") and" + "application version (" + version + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; - List comments = new ArrayList<>(); + List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT,TENANT_ID FROM AP_APP_COMMENT C ," @@ -611,21 +659,19 @@ public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { statement.setInt(4, parentId); rs = statement.executeQuery(); while (rs.next()) { - Comment comment = new Comment(); - comment.setId(rs.getInt("ID")); - comment.setTenantId(rs.getInt("TENANT_ID")); - comment.setCommentText(rs.getString("COMMENT_TEXT")); - comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); - comment.setCreatedBy(rs.getString("CREATED_BY")); - comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - comment.setModifiedBy(rs.getString("modifiedBy")); - comment.setParent(rs.getInt("PARENT_ID")); - comments.add(comment); + Review review = new Review(); + review.setId(rs.getInt("ID")); +// review.setTenantId(rs.getInt("TENANT_ID")); + review.setComment(rs.getString("COMMENT_TEXT")); + review.setCreatedAt(rs.getTimestamp("CREATED_AT")); + review.setUsername(rs.getString("CREATED_BY")); + review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + reviews.add(review); } } finally { Util.cleanupResources(statement, null); } - return comments; + return reviews; } @Override diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index e5e2153261c..12c80c4c525 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -380,7 +380,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - Boolean isAppExist = false; + boolean isAppExist = false; try { conn = this.getDBConnection(); String sql = diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java index f15c091863e..c86e7f86849 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application.release; import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; +import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.Util; @@ -268,20 +269,21 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements * To Update starts of an application release. * * @param id Id of the application Release. - * @param stars given stars for the application release. + * @param rating given stars for the application release. * @throws ApplicationManagementDAOException Application Management DAO Exception. */ @Override - public void updateStars(int id, int stars) throws ApplicationManagementDAOException { + public int updateRatingValue(int id, double rating, int ratedUsers) throws ApplicationManagementDAOException { Connection connection; PreparedStatement statement = null; - String sql = "UPDATE AP_APP_RELEASE SET STARS = ? WHERE ID = ?;"; + String sql = "UPDATE AP_APP_RELEASE SET RATING = ? AND RATED_USERS = ? WHERE ID = ?;"; try { connection = this.getDBConnection(); statement = connection.prepareStatement(sql); - statement.setInt(1, stars); + statement.setDouble(1, rating); + statement.setInt(2, ratedUsers); statement.setInt(2, id); - statement.executeUpdate(); + return statement.executeUpdate(); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException( "Database connection exception while trying to update the application release", e); @@ -293,6 +295,42 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements } } + /** + * To retrieve rating of an application release. + * + * @param id Id of the application Release. + * @throws ApplicationManagementDAOException Application Management DAO Exception. + */ + @Override + public Rating getRating(int id) throws ApplicationManagementDAOException { + Connection connection; + PreparedStatement statement = null; + ResultSet resultSet = null; + Rating rating = null; + String sql = "SELECT RATING, RATED_USERS FROM AP_APP_RELEASE WHERE ID = ?;"; + try { + connection = this.getDBConnection(); + statement = connection.prepareStatement(sql); + statement.setInt(1, id); + resultSet = statement.executeQuery(); + + if (resultSet.next()){ + rating = new Rating(); + rating.setRatingValue(resultSet.getDouble("RATING")); + rating.setNoOfUsers(resultSet.getInt("RATED_USERS")); + } + return rating; + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException( + "Database connection exception while trying to update the application release", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "SQL exception while updating the release ,while executing the query " + sql, e); + } finally { + Util.cleanupResources(statement, resultSet); + } + } + /** * To insert the application release properties. * @@ -369,7 +407,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements } /** - * This method is capable to construct {@ApplicationRelease} and return the object + * This method is capable to construct {@link ApplicationRelease} and return the object * @param resultSet result set obtained from the query executing. * @throws SQLException SQL exception while accessing result set data. */ diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java deleted file mode 100644 index e42245db50c..00000000000 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java +++ /dev/null @@ -1,289 +0,0 @@ -/* -* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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. -* -*/ -package org.wso2.carbon.device.application.mgt.core.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.application.mgt.common.Comment; -import org.wso2.carbon.device.application.mgt.common.PaginationRequest; -import org.wso2.carbon.device.application.mgt.common.PaginationResult; -import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException; -import org.wso2.carbon.device.application.mgt.common.services.*; -import org.wso2.carbon.device.application.mgt.core.dao.CommentDAO; -import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; -import org.wso2.carbon.device.application.mgt.core.dao.common.Util; -import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; -import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; - -import java.sql.SQLException; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; - -/** - * This class is the default implementation for the Managing the comments. - */ -public class CommentsManagerImpl implements CommentsManager { - - private static final Log log = LogFactory.getLog(CommentsManagerImpl.class); - private CommentDAO commentDAO; - - public CommentsManagerImpl() { - initDataAccessObjects(); - } - - private void initDataAccessObjects() { - this.commentDAO = ApplicationManagementDAOFactory.getCommentDAO(); - } - - @Override - public Comment addComment(Comment comment, String uuid) throws CommentManagementException { - - if (log.isDebugEnabled()) { - log.debug("Request for comment is received for uuid" + uuid); - } - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - comment.setCreatedAt(Timestamp.from(Instant.now())); - try { - ConnectionManagerUtil.beginDBTransaction(); - if (commentDAO.addComment(tenantId, comment, comment.getCreatedBy(), comment.getParent(), uuid)) { - ConnectionManagerUtil.commitDBTransaction(); - return comment; - } else { - ConnectionManagerUtil.rollbackDBTransaction(); - return null; - } - } catch (DBConnectionException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( - "DB Connection error occurs ,Comment for application with UUID " + uuid + "cannot add.", e); - } catch (SQLException e) { - throw new CommentManagementException( - "SQL Exception occurs,Comment for application with UUID " + uuid + "cannot add.", e); - } catch (TransactionManagementException e) { - throw new CommentManagementException( - "Transaction Management Exception occurs,Comment for application with UUID " + uuid + "cannot add.", - e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - } - - /** - * To validate the pre-request of the comment - * - * @param commentId ID of the comment. - * @param comment comment needed to be validate. - * @return Application related with the UUID. - * @throws CommentManagementException Exceptions of the comment management. - */ - - public Boolean validateComment(int commentId, String comment) throws CommentManagementException { - - if (commentId <= 0) { - throw new CommentManagementException( - "Comment ID is null or negative. Comment id is a required parameter to get the " - + "relevant comment."); - } - if (comment == null) { - log.error("Comment can not be null, but Comment at comment id " + commentId + " is null."); - return false; - } - return true; - } - - @Override - public PaginationResult getAllComments(PaginationRequest request, String uuid) throws CommentManagementException { - - PaginationResult paginationResult = new PaginationResult(); - int numOfComments; - List comments; - if (log.isDebugEnabled()) { - log.debug("get all comments of the application release" + uuid); - } - try { - ConnectionManagerUtil.openDBConnection(); - comments = commentDAO.getAllComments(uuid, Util.validateCommentListPageSize(request)); - numOfComments = comments.size(); - paginationResult.setData(comments); - if (numOfComments > 0) { - paginationResult.setRecordsFiltered(numOfComments); - paginationResult.setRecordsTotal(numOfComments); - } else { - paginationResult.setRecordsFiltered(0); - paginationResult.setRecordsTotal(0); - } - return paginationResult; - } catch (DBConnectionException e) { - throw new CommentManagementException( - "DB Connection error occurs , while getting comments of application release UUID: " + uuid, e); - } catch (SQLException e) { - throw new CommentManagementException( - "SQL Exception occurs, while getting comments of application release UUID: " + uuid, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - } - - @Override - public Comment getComment(int commentId) throws CommentManagementException { - - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - Comment comment; - if (log.isDebugEnabled()) { - log.debug("Comment retrieval request is received for the comment id " + commentId); - } - try { - ConnectionManagerUtil.openDBConnection(); - comment = commentDAO.getComment(commentId); - } catch (DBConnectionException e) { - throw new CommentManagementException( - "DB Connection error occurs ,Comment with comment id " + commentId + "cannot get.", e); - } catch (SQLException e) { - throw new CommentManagementException( - "SQL Exception occurs,Comment with comment id " + commentId + "cannot get.", e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - return comment; - } - - @Override - public void deleteComment(int commentId) throws CommentManagementException { - - Comment comment; - comment = getComment(commentId); - if (comment == null) { - throw new CommentManagementException( - "Cannot delete a non-existing comment for the application with comment id" + commentId); - } - try { - ConnectionManagerUtil.beginDBTransaction(); - commentDAO.deleteComment(commentId); - ConnectionManagerUtil.commitDBTransaction(); - } catch (DBConnectionException e) { - throw new CommentManagementException( - "DB Connection error occurs deleting comment with comment id " + commentId + ".", e); - } catch (SQLException e) { - throw new CommentManagementException("SQL error occurs deleting comment with comment id " + commentId + ".", - e); - } catch (TransactionManagementException e) { - throw new CommentManagementException( - "Transaction Management Exception occurs deleting comment with comment id " + commentId + ".", e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - } - - @Override - public Comment updateComment(Comment comment, int commentId) throws CommentManagementException { - - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - validateComment(commentId, comment.getCommentText()); - if (log.isDebugEnabled()) { - log.debug("Comment retrieval request is received for the comment id " + commentId); - } - comment.setModifiedAt(Timestamp.from(Instant.now())); - try { - ConnectionManagerUtil.openDBConnection(); - commentDAO.getComment(commentId); - return commentDAO - .updateComment(commentId, comment.getCommentText(), comment.getModifiedBy(), comment.getModifiedAt()); - } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurs updating comment with comment id " + commentId + ".", - e); - } catch (DBConnectionException e) { - throw new CommentManagementException( - "DB Connection error occurs updating comment with comment id " + commentId + ".", e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - } - - @Override - public int getRatedUser(String uuid) throws ApplicationManagementException { - - int ratedUsers; - if (log.isDebugEnabled()) { - log.debug("Get the rated users for the application release number" + uuid); - } - try { - ConnectionManagerUtil.openDBConnection(); - ratedUsers = commentDAO.getRatedUser(uuid); - } catch (ApplicationManagementDAOException e) { - throw new ApplicationManagementException( - "Rated Users of the Application with UUID " + uuid + " can not get.", e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - return ratedUsers; - } - - @Override - public int getStars(String uuid) throws ApplicationManagementException { - - int stars; - if (log.isDebugEnabled()) { - log.debug("Get the average of rated stars for the application " + uuid); - } - try { - ConnectionManagerUtil.openDBConnection(); - stars = commentDAO.getStars(uuid); - } catch (ApplicationManagementDAOException e) { - throw new ApplicationManagementException( - "Average stars of the Application with UUID " + uuid + " can not get.", e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - return stars; - } - - @Override - public int updateStars(int stars, String uuid) throws ApplicationManagementException { - - if (log.isDebugEnabled()) { - log.debug("Stars are received for the application " + uuid); - } - int newStars; - try { - ConnectionManagerUtil.beginDBTransaction(); - int ratedUsers = commentDAO.getRatedUser(uuid); - int oldStars = commentDAO.getStars(uuid); - if (ratedUsers == 0) { - newStars = commentDAO.updateStars(stars, uuid); - return newStars; - } else { - int avgStars = ((oldStars * ratedUsers) + stars) / (ratedUsers + 1); - newStars = commentDAO.updateStars(avgStars, uuid); - ConnectionManagerUtil.commitDBTransaction(); - return newStars; - } - } catch (ApplicationManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Updated average stars of the Application with UUID " + uuid + " can not get.", e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - } -} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java new file mode 100644 index 00000000000..f742fd5c57b --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java @@ -0,0 +1,398 @@ +/* +* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* WSO2 Inc. licenses this file to you 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. +* +*/ +package org.wso2.carbon.device.application.mgt.core.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.application.mgt.common.Rating; +import org.wso2.carbon.device.application.mgt.common.Review; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.PaginationResult; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; +import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException; +import org.wso2.carbon.device.application.mgt.common.services.*; +import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; +import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO; +import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; +import org.wso2.carbon.device.application.mgt.core.dao.common.Util; +import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; +import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import java.sql.SQLException; +import java.util.List; +import java.util.TreeMap; + +/** + * This class is the default implementation for the Managing the comments. + */ +public class ReviewManagerImpl implements ReviewManager { + + private static final Log log = LogFactory.getLog(ReviewManagerImpl.class); + private ReviewDAO reviewDAO; + private ApplicationReleaseDAO applicationReleaseDAO; + + public ReviewManagerImpl() { + initDataAccessObjects(); + } + + private void initDataAccessObjects() { + this.reviewDAO = ApplicationManagementDAOFactory.getCommentDAO(); + this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO(); + } + + @Override + public boolean addReview(Review review, int appId, int appReleaseId) throws CommentManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + boolean isSuccess; + try { + ConnectionManagerUtil.beginDBTransaction(); + Review existingReview = reviewDAO.isExistReview(appId, appReleaseId, username, tenantId); + if (existingReview != null && review.getRating() > 0 && review.getRating() != existingReview.getRating()) { + Runnable task = () -> { + try { + if (calculateRating(review.getRating(), existingReview.getRating()) <= 0.0) { + log.error("Application release rating updating task is failed"); + } + } catch (CommentManagementException e) { + // todo + log.error("comment management error occured"); + } + }; + new Thread(task).start(); + isSuccess = updateReview(review, existingReview.getId(), false); + if (isSuccess) { + ConnectionManagerUtil.commitDBTransaction(); + } else { + ConnectionManagerUtil.rollbackDBTransaction(); + } + } else { + if (review.getRating()>0){ + Runnable task = () -> { + try { + if (calculateRating(review.getRating(), -12345) <= 0.0) { + log.error("Application release rating inserting task is failed"); + } + } catch (CommentManagementException e) { + // todo + log.error("comment management error occured"); + } + }; + new Thread(task).start(); + } + review.setUsername(username); + isSuccess = this.reviewDAO.addReview(review, appId, appReleaseId, tenantId); + if (isSuccess) { + ConnectionManagerUtil.commitDBTransaction(); + } else { + ConnectionManagerUtil.rollbackDBTransaction(); + } + } + return isSuccess; + } catch (DBConnectionException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "DB Connection error occurs ,Review for application with app id: " + appId + " and app release id: " + + appReleaseId + " is failed", e); + } catch (SQLException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "SQL Exception occurs,Review for application with app id:" + appId + " and app release id:" + + appReleaseId + " is failed", e); + } catch (TransactionManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "Transaction Management Exception occurs,Review for application with app id:" + appId + + " and app release id:" + appReleaseId + " is failed ", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public boolean updateReview(Review review, int reviewId, boolean checkExistence) + throws CommentManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + Review existingReview; + boolean isSuccess; + if (log.isDebugEnabled()) { + log.debug("Review updating request is received for the review id " + reviewId); + } + try { + ConnectionManagerUtil.openDBConnection(); + if (!username.equals(review.getUsername())) { + throw new CommentManagementException( + "User " + review.getUsername() + "doesn't match with the logged in user: " + username); + } + if (checkExistence) { + existingReview = this.reviewDAO.getComment(reviewId); + if (existingReview != null) { + if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) { + Runnable task = () -> { + try { + if (calculateRating(review.getRating(), existingReview.getRating()) <= 0.0) { + log.error("Application release review updating task is failed"); + } + } catch (CommentManagementException e) { + // todo + log.error("error"); + } + }; + new Thread(task).start(); + } + } else { + throw new CommentManagementException("Couldn't find a review for review id: " + reviewId); + } + } + ConnectionManagerUtil.beginDBTransaction(); + isSuccess = this.reviewDAO.updateReview(review, reviewId, tenantId); + if (isSuccess) { + ConnectionManagerUtil.commitDBTransaction(); + } else { + ConnectionManagerUtil.rollbackDBTransaction(); + } + return isSuccess; + } catch (SQLException e) { + throw new CommentManagementException("SQL Error occurs updating review with review id " + reviewId + ".", + e); + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs updating review with review id " + reviewId + ".", e); + } catch (TransactionManagementException e) { + throw new CommentManagementException( + "Transaction management error occurs when updating review with review id " + reviewId + ".", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public PaginationResult getAllReviews(PaginationRequest request, String uuid) throws CommentManagementException { + PaginationResult paginationResult = new PaginationResult(); + int numOfComments; + List reviews; + if (log.isDebugEnabled()) { + log.debug("get all reviews of the application release" + uuid); + } + try { + ConnectionManagerUtil.openDBConnection(); + reviews = this.reviewDAO.getAllComments(uuid, Util.validateCommentListPageSize(request)); + numOfComments = reviews.size(); + paginationResult.setData(reviews); + if (numOfComments > 0) { + paginationResult.setRecordsFiltered(numOfComments); + paginationResult.setRecordsTotal(numOfComments); + } else { + paginationResult.setRecordsFiltered(0); + paginationResult.setRecordsTotal(0); + } + return paginationResult; + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs , while getting reviews of application release UUID: " + uuid, e); + } catch (SQLException e) { + throw new CommentManagementException( + "Error occured in the data layer, while getting reviews of application release UUID: " + uuid, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Review getReview(int commentId) throws CommentManagementException { + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + Review review; + if (log.isDebugEnabled()) { + log.debug("Review retrieval request is received for the review id " + commentId); + } + try { + ConnectionManagerUtil.openDBConnection(); + review = this.reviewDAO.getComment(commentId); + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs ,Review with review id " + commentId + "cannot get.", e); + } catch (SQLException e) { + throw new CommentManagementException( + "SQL Exception occurs,Review with review id " + commentId + "cannot get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + return review; + } + + @Override + public void deleteReview(String loggedInUser, int commentId) throws CommentManagementException { + Review existingReview; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + try { + if (!loggedInUser.equals(username) && !isAdminUser(username, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)){ + throw new CommentManagementException( + "You don't have permission to delete the review. Please contact the administrator. Review Id: " + + commentId); + } + existingReview = getReview(commentId); + if (existingReview == null) { + throw new CommentManagementException( + "Cannot delete a non-existing review for the application with review id" + commentId); + } + Runnable task = () -> { + try { + if (calculateRating(0, existingReview.getRating()) <= 0.0) { + log.error("Application release review updating task is failed"); + } + } catch (CommentManagementException e) { + // todo + log.error("error occured"); + } + }; + new Thread(task).start(); + ConnectionManagerUtil.beginDBTransaction(); + this.reviewDAO.deleteComment(commentId); + ConnectionManagerUtil.commitDBTransaction(); + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs deleting review with review id " + commentId + ".", e); + } catch (SQLException e) { + throw new CommentManagementException("SQL error occurs deleting review with review id " + commentId + ".", + e); + } catch (TransactionManagementException e) { + throw new CommentManagementException( + "Transaction Management Exception occurs deleting review with review id " + commentId + ".", e); + } catch (UserStoreException e) { + throw new CommentManagementException( + "User-store exception while checking whether the user " + username + " of tenant " + tenantId + + " has the publisher permission"); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Rating getRating(String appReleaseUuuid) throws CommentManagementException{ + //todo + int appReleaseId = 0; + try { + ConnectionManagerUtil.openDBConnection(); + Rating rating = this.applicationReleaseDAO.getRating(appReleaseId); + if (rating == null) { + throw new CommentManagementException("Couldn't find rating for application release id: " + appReleaseId + + ". Please check the existence of the application relese"); + } + + List ratingValues = this.reviewDAO.getAllRatingValues(appReleaseUuuid); + TreeMap ratingVariety = rating.getRatingVariety(); + for (Integer ratingVal : ratingValues) { + if (ratingVariety.containsKey(ratingVal)) { + ratingVariety.replace(ratingVal, ratingVariety.get(ratingVal) + 1); + } else { + ratingVariety.put(ratingVal, 1); + } + } + rating.setRatingVariety(ratingVariety); + return rating; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "Error occured while updated the rating value of the application release id: " + appReleaseId + + " can not get.", e); + } catch (DBConnectionException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "DB Connection error occured while updated the rating value of the application release id: " + appReleaseId + + " can not get.", e); + } catch (SQLException e) { + throw new CommentManagementException( + "DB Connection error occured while updated the rating value of the application release id: " + appReleaseId + + " can not get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + private double calculateRating(int newRatingVal, int oldRatingVal) throws CommentManagementException { + // todo need to pass app release id + int appReleaseId = 0; + try { + ConnectionManagerUtil.beginDBTransaction(); + Rating rating = this.applicationReleaseDAO.getRating(appReleaseId); + if (rating == null) { + throw new CommentManagementException( + "Couldn't find rating for application release id: " + appReleaseId); + } + double updatedRating; + int numOfUsers = rating.getNoOfUsers(); + double currentRating = rating.getRatingValue() * numOfUsers; + if (oldRatingVal == -12345) { + updatedRating = (currentRating + newRatingVal) / (numOfUsers + 1); + this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers + 1); + } else if ( newRatingVal == 0){ + updatedRating = (currentRating - newRatingVal) / (numOfUsers - 1); + this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers - 1); + } else{ + double tmpVal; + tmpVal = currentRating - oldRatingVal; + updatedRating = (tmpVal + newRatingVal) / numOfUsers; + this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers ); + } + ConnectionManagerUtil.commitDBTransaction(); + return updatedRating; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "Error occured while updated the rating value of the application release id: " + appReleaseId + + " can not get.", e); + } catch (TransactionManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "Transaction Management Exception occured while updated the rating value of the application release id: " + appReleaseId + + " can not get.", e); + } catch (DBConnectionException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "DB Connection error occured while updated the rating value of the application release id: " + appReleaseId + + " can not get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + /** + * To check whether current user has the permission to do some secured operation. + * + * @param username Name of the User. + * @param tenantId ID of the tenant. + * @param permission Permission that need to be checked. + * @return true if the current user has the permission, otherwise false. + * @throws UserStoreException UserStoreException + */ + private boolean isAdminUser(String username, int tenantId, String permission) throws UserStoreException { + UserRealm userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + return userRealm != null && userRealm.getAuthorizationManager() != null && userRealm.getAuthorizationManager() + .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission, + CarbonConstants.UI_PERMISSION_ACTION); + } +} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java index 65392952c04..4f74582336b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.internal; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; +import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -37,7 +37,7 @@ public class DataHolder { private ApplicationManager applicationManager; - private CommentsManager commentsManager; + private ReviewManager reviewManager; private SubscriptionManager subscriptionManager; @@ -71,12 +71,12 @@ public class DataHolder { this.applicationManager = applicationManager; } - public CommentsManager getCommentsManager() { - return commentsManager; + public ReviewManager getReviewManager() { + return reviewManager; } - public void setCommentsManager(CommentsManager commentsManager) { - this.commentsManager = commentsManager; + public void setReviewManager(ReviewManager reviewManager) { + this.reviewManager = reviewManager; } public SubscriptionManager getSubscriptionManager() { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java index 9e5eeee881d..7a2fd489ed8 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java @@ -25,7 +25,7 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; +import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; @@ -74,9 +74,9 @@ public class ServiceComponent { DataHolder.getInstance().setApplicationManager(applicationManager); bundleContext.registerService(ApplicationManager.class.getName(), applicationManager, null); - CommentsManager commentsManager = ApplicationManagementUtil.getCommentsManagerInstance(); - DataHolder.getInstance().setCommentsManager(commentsManager); - bundleContext.registerService(CommentsManager.class.getName(), commentsManager, null); + ReviewManager reviewManager = ApplicationManagementUtil.getCommentsManagerInstance(); + DataHolder.getInstance().setReviewManager(reviewManager); + bundleContext.registerService(ReviewManager.class.getName(), reviewManager, null); SubscriptionManager subscriptionManager = ApplicationManagementUtil.getSubscriptionManagerInstance(); DataHolder.getInstance().setSubscriptionManager(subscriptionManager); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java index a4b905749fa..4127696e30c 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java @@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; +import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; @@ -45,10 +45,10 @@ public class ApplicationManagementUtil { return getInstance(extension, ApplicationManager.class); } - public static CommentsManager getCommentsManagerInstance() throws InvalidConfigurationException { + public static ReviewManager getCommentsManagerInstance() throws InvalidConfigurationException { ConfigurationManager configurationManager = ConfigurationManager.getInstance(); Extension extension = configurationManager.getExtension(Extension.Name.CommentsManager); - return getInstance(extension, CommentsManager.class); + return getInstance(extension, ReviewManager.class); } public static UnrestrictedRoleManager getVisibilityManagerInstance() throws InvalidConfigurationException { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml index 974cd4df3a8..71ebffdd6bf 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml @@ -39,7 +39,7 @@ org.wso2.carbon.device.application.mgt.core.impl.CategoryManagerImpl - org.wso2.carbon.device.application.mgt.core.impl.CommentsManagerImpl + org.wso2.carbon.device.application.mgt.core.impl.ReviewManagerImpl org.wso2.carbon.device.application.mgt.core.impl.LifecycleStateManagerImpl diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java index ce939df4617..b82802b85d1 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java @@ -21,7 +21,7 @@ package org.wso2.carbon.device.application.mgt.store.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; +import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; @@ -87,20 +87,20 @@ public class APIUtil { } /** - * To get the Comment Manager from the osgi context. + * To get the Review Manager from the osgi context. * - * @return CommentsManager instance in the current osgi context. + * @return ReviewManager instance in the current osgi context. */ - public static CommentsManager getCommentsManager() { + public static ReviewManager getCommentsManager() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - CommentsManager commentsManager = (CommentsManager) ctx.getOSGiService(CommentsManager.class, null); - if (commentsManager == null) { + ReviewManager reviewManager = (ReviewManager) ctx.getOSGiService(ReviewManager.class, null); + if (reviewManager == null) { String msg = "Comments Manager service has not initialized."; log.error(msg); throw new IllegalStateException(msg); } - return commentsManager; + return reviewManager; } public static Response getResponse(Exception ex, Response.Status status) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java index fcd5d6ea42e..a86d0d79011 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java @@ -31,7 +31,7 @@ import io.swagger.annotations.ApiResponses; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.application.mgt.publisher.api.beans.ErrorResponse; -import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.Review; import javax.validation.Valid; import javax.ws.rs.Path; import javax.ws.rs.Consumes; @@ -62,7 +62,7 @@ import java.util.List; } ), tags = { - @Tag(name = "store_management", description = "Comment Management related " + @Tag(name = "store_management", description = "Review Management related " + "APIs") } ) @@ -75,20 +75,20 @@ import java.util.List; permissions = {"/device-mgt/comment/get"} ), @Scope( - name = "Add a Comment", + name = "Add a Review", description = "Add a comment", key = "perm:comment:add", permissions = {"/device-mgt/comment/add"} ), @Scope( - name = "Update a Comment", - description = "Update a Comment", + name = "Update a Review", + description = "Update a Review", key = "perm:comment:update", permissions = {"/device-mgt/comment/update"} ), @Scope( - name = "Delete a Comment", + name = "Delete a Review", description = "Delete a comment", key = "perm:comment:delete", permissions = {"/device-mgt/comment/delete"} @@ -96,7 +96,7 @@ import java.util.List; } ) -@Path("/reviews") +@Path("/review") @Api(value = "Comments Management", description = "This API carries all comments management related operations " + "such as get all the comments, add comment, etc.") @Produces(MediaType.APPLICATION_JSON) @@ -137,7 +137,7 @@ public interface ReviewManagementAPI { response = ErrorResponse.class) }) - Response getAllComments( + Response getAllReviews( @ApiParam( name="uuid", value="uuid of the released version of application.", @@ -165,8 +165,8 @@ public interface ReviewManagementAPI { consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "Add a comment", - notes = "This will add a new comment", + value = "Add a review", + notes = "This will add a new review", tags = "Store Management", extensions = { @Extension(properties = { @@ -179,24 +179,23 @@ public interface ReviewManagementAPI { value = { @ApiResponse( code = 201, - message = "OK. \n Successfully add a comment.", - response = Comment.class), + message = "OK. \n Successfully add a review.", + response = Review.class), @ApiResponse( code = 400, message = "Bad Request. \n"), @ApiResponse( code = 500, - message = "Internal Server Error. \n Error occurred adding a comment.", + message = "Internal Server Error. \n Error occurred adding a review.", response = ErrorResponse.class) }) - Response addComment( + Response addReview( @ApiParam( - name = "comment", - value = "Comment details", - required = true) - Comment comment, + name = "review", + value = "Review details", + required = true) Review review, @ApiParam( name="uuid", value="uuid of the release version of the application", @@ -212,8 +211,8 @@ public interface ReviewManagementAPI { consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "PUT", - value = "Edit a comment", - notes = "This will edit the comment", + value = "Edit a review", + notes = "This will edit the review", tags = "Store Management", extensions = { @Extension(properties = { @@ -225,8 +224,8 @@ public interface ReviewManagementAPI { value = { @ApiResponse( code = 201, - message = "OK. \n Successfully updated comment.", - response = Comment.class), + message = "OK. \n Successfully updated review.", + response = Review.class), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error."), @@ -236,24 +235,24 @@ public interface ReviewManagementAPI { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server Error. \n Error occurred while updating the new comment.", + message = "Internal Server Error. \n Error occurred while updating the new review.", response = ErrorResponse.class) }) Response updateComment( @ApiParam( - name = "comment", - value = "The comment that need to be updated.", + name = "review", + value = "The review that need to be updated.", required = true) - @Valid Comment comment, + @Valid Review review, @ApiParam( name="commentId", - value = "comment id of the updating comment.", + value = "review id of the updating review.", required = true) @QueryParam("commentId") int commentId); @DELETE - @Path("/{CommentId}") + @Path("/{commentId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( @@ -291,7 +290,12 @@ public interface ReviewManagementAPI { value="Id of the comment.", required = true) @PathParam("commentId") - int commentId); + int commentId, + @ApiParam( + name="username", + value="logged in username", + required = true) + @QueryParam("username") String username); @GET @Path("/{uuid}/{stars}") @@ -329,88 +333,4 @@ public interface ReviewManagementAPI { required = true) @PathParam("uuid") String uuid); - - @GET - @Path("/{uuid}/{stars}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "get rated users", - notes = "Get all users", - tags = "Store Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:user:get") - }) - } - ) - - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully retrieved user.", - response = List.class, - responseContainer = "List"), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Error occurred while getting the comment list.", - response = ErrorResponse.class) - }) - - Response getNumOfRatedUsers( - @ApiParam( - name = "uuid", - value = "uuid of the application release", - required = true) - @PathParam("uuid") - String uuid); - - @POST - @Path("/uuid/{uuid}") - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - produces = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add a star value", - notes = "This will add star value", - tags = "Store Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = SCOPE, value = "perm:stars:add") - }) - } - ) - - @ApiResponses( - value = { - @ApiResponse( - code = 201, - message = "OK. \n Successfully rated to the application.", - response = Comment.class), - @ApiResponse( - code = 304, - message = "Not Modified. \n " + - "Empty body because the client already has the latest rating of the requested resource."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Error occurred rating for the application.", - response = ErrorResponse.class) - }) - - Response updateRatings( - @ApiParam( - name = "stars", - value = "ratings for the application", - required = true) - int stars, - @ApiParam( - name="uuid", - value="uuid of the release version of the application", - required=true) - @PathParam("uuid") - String uuid); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java index db2f0b803a3..6ee1fc018d8 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java @@ -21,14 +21,18 @@ package org.wso2.carbon.device.application.mgt.store.api.services.impl; import io.swagger.annotations.ApiParam; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.application.mgt.common.Application; +import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.PaginationResult; +import org.wso2.carbon.device.application.mgt.common.Rating; +import org.wso2.carbon.device.application.mgt.common.Review; +import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; +import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.store.api.APIUtil; import org.wso2.carbon.device.application.mgt.store.api.services.ReviewManagementAPI; -import org.wso2.carbon.device.application.mgt.common.Comment; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; import javax.ws.rs.Path; import javax.ws.rs.Consumes; @@ -39,11 +43,9 @@ import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; /** - * Comment Management related jax-rs APIs. + * Review Management related jax-rs APIs. */ @Path("/review") public class ReviewManagementAPIImpl implements ReviewManagementAPI { @@ -52,16 +54,16 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @Override @GET - @Path("/application/{uuid}/comments") - public Response getAllComments( + @Path("/{uuid}") + public Response getAllReviews( @PathParam("uuid") String uuid, @QueryParam("offset") int offSet, @QueryParam("limit") int limit) { - CommentsManager commentsManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getCommentsManager(); PaginationRequest request = new PaginationRequest(offSet, limit); try { - PaginationResult paginationResult = commentsManager.getAllComments(request, uuid); + PaginationResult paginationResult = reviewManager.getAllReviews(request, uuid); return Response.status(Response.Status.OK).entity(paginationResult).build(); } catch (CommentManagementException e) { String msg = "Error occurred while retrieving comments."; @@ -74,48 +76,60 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @Override @POST @Consumes("application/json") - @Path("/application/{uuid}/comment") - public Response addComment( - @ApiParam Comment comment, + @Path("/{uuid}") + public Response addReview( + @ApiParam Review review, @PathParam("uuid") String uuid) { - CommentsManager commentsManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getCommentsManager(); + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + Application application; + ApplicationRelease applicationRelease; try { - if (commentsManager.addComment(comment, uuid) != null) { - return Response.status(Response.Status.CREATED).entity(comment).build(); + application = applicationManager.getApplicationByRelease(uuid); + applicationRelease = applicationManager.getAppReleaseIfExists(application.getId(), uuid); + boolean abc = reviewManager.addReview(review, application.getId(), applicationRelease.getId()); + if (abc) { + return Response.status(Response.Status.CREATED).entity(review).build(); } else { - String msg = "Given comment is not valid "; + String msg = "Given review is not valid "; log.error(msg); return Response.status(Response.Status.BAD_REQUEST).build(); } } catch (CommentManagementException e) { - String msg = "Error occurred while creating the comment"; + String msg = "Error occurred while creating the review"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(msg).build(); + } catch (ApplicationManagementException e) { +// todo + log.error(""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("").build(); } } @Override @PUT @Consumes("application/json") - @Path("/comment/{commentId}") + @Path("/review/{commentId}") public Response updateComment( - @ApiParam Comment comment, + @ApiParam Review review, @PathParam("commentId") int commentId) { - CommentsManager commentsManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getCommentsManager(); try { if (commentId == 0) { return Response.status(Response.Status.NOT_FOUND) - .entity("Comment not found").build(); - } else if (comment == null) { - String msg = "Given comment is not valid "; + .entity("Review not found").build(); + } else if (review == null) { + String msg = "Given review is not valid "; log.error(msg); return Response.status(Response.Status.BAD_REQUEST).build(); + } else if (reviewManager.updateReview(review, commentId, true)) { + return Response.status(Response.Status.OK).entity(review).build(); } else { - comment = commentsManager.updateComment(comment, commentId); - return Response.status(Response.Status.OK).entity(comment).build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("").build(); } } catch (CommentManagementException e) { String msg = "Error occurred while retrieving comments."; @@ -129,14 +143,15 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @DELETE @Path("/comment/{commentId}") public Response deleteComment( - @PathParam("commentId") int commentId) { + @PathParam("commentId") int commentId, + @QueryParam("username") String username) { - CommentsManager commentsManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getCommentsManager(); try { if (commentId == 0) { - return Response.status(Response.Status.NOT_FOUND).entity("Comment not found").build(); + return Response.status(Response.Status.NOT_FOUND).entity("Review not found").build(); } else { - commentsManager.deleteComment(commentId); + reviewManager.deleteReview(username, commentId); } } catch (CommentManagementException e) { String msg = "Error occurred while deleting the comment."; @@ -144,79 +159,24 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg) .build(); } - return Response.status(Response.Status.OK).entity("Comment is deleted successfully.").build(); + return Response.status(Response.Status.OK).entity("Review is deleted successfully.").build(); } @Override @GET - @Path("/application/{uuid}/rating") + @Path("/{uuid}/rating") public Response getRating( @PathParam("uuid") String uuid) { - CommentsManager commentsManager = APIUtil.getCommentsManager(); - int stars; + ReviewManager reviewManager = APIUtil.getCommentsManager(); + Rating rating; try { - stars = commentsManager.getStars(uuid); + rating = reviewManager.getRating(uuid); } catch (CommentManagementException e) { - log.error("Comment Management Exception occurs", e); + log.error("Review Management Exception occurs", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (ApplicationManagementException e) { - String msg="Application Management Exception occurs"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(msg).build(); } - return Response.status(Response.Status.OK).entity(stars).build(); + return Response.status(Response.Status.OK).entity(rating).build(); } - @Override - @GET - @Path("/application/{uuid}/total-rated-users") - public Response getNumOfRatedUsers( - @PathParam("uuid") String uuid) { - - CommentsManager commentsManager = APIUtil.getCommentsManager(); - int ratedUsers; - try { - ratedUsers = commentsManager.getRatedUser(uuid); - } catch (CommentManagementException e) { - String msg="Comment Management Exception occurs"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(msg).build(); - } catch (ApplicationManagementException e) { - String msg="Application Management Exception occurs"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity("Application with UUID" + uuid + " Internal server error occurs").build(); - } - return Response.status(Response.Status.OK).entity(ratedUsers).build(); - } - - @Override - @PUT - @Consumes("application/json") - @Path("/application/{uuid}/rating") - public Response updateRatings( - @ApiParam int stars, - @PathParam("uuid") String uuid) { - - CommentsManager commentsManager = APIUtil.getCommentsManager(); - int newStars; - try { - newStars = commentsManager.updateStars(stars, uuid); - if (stars != 0) { - return Response.status(Response.Status.CREATED).entity(newStars).build(); - } else { - String msg = "Given star value is not valid "; - log.error(msg); - return Response.status(Response.Status.BAD_REQUEST).build(); - } - } catch (ApplicationManagementException e) { - String msg="Application Management Exception occurs"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(msg).build(); - } - } } \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/CommentManagementAPITest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java similarity index 59% rename from components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/CommentManagementAPITest.java rename to components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java index ec802303259..c59db2a67db 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/CommentManagementAPITest.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java @@ -32,10 +32,10 @@ import org.testng.IObjectFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; +import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.store.api.APIUtil; import org.wso2.carbon.device.application.mgt.store.api.services.impl.ReviewManagementAPIImpl; import org.wso2.carbon.device.application.mgt.store.api.services.util.CommentMgtTestHelper; @@ -47,14 +47,15 @@ import static org.mockito.MockitoAnnotations.initMocks; @PowerMockIgnore("javax.ws.rs.*") @SuppressStaticInitializationFor({ "org.wso2.carbon.device.application.mgt.api.APIUtil" }) -@PrepareForTest({ APIUtil.class, CommentsManager.class, - CommentManagementAPITest.class}) -@Ignore("Since comment manager logic is invalid temporarily added Ignore annotation to skip running comment management test cases") public class CommentManagementAPITest extends +@PrepareForTest({ APIUtil.class, ReviewManager.class, + ReviewManagementAPITest.class}) +@Ignore("Since comment manager logic is invalid temporarily added Ignore annotation to skip running comment management test cases") public class ReviewManagementAPITest + extends TestCase { private static final Log log = LogFactory.getLog(ReviewManagementAPI.class); private ReviewManagementAPI commentManagementAPI; - private CommentsManager commentsManager; + private ReviewManager reviewManager; @ObjectFactory public IObjectFactory getObjectFactory() { @@ -66,81 +67,81 @@ import static org.mockito.MockitoAnnotations.initMocks; log.info("Initializing ReviewManagementAPI tests"); initMocks(this); - this.commentsManager = Mockito.mock(CommentsManager.class, Mockito.RETURNS_DEFAULTS); + this.reviewManager = Mockito.mock(ReviewManager.class, Mockito.RETURNS_DEFAULTS); this.commentManagementAPI = new ReviewManagementAPIImpl(); } @Test public void testGetAllCommentsWithValidDetails() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.getAllComments("a", 1, 2); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.getAllReviews("a", 1, 2); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The response status should be 200."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testGetAllCommentsInternalError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.doThrow(new CommentManagementException()).when(this.commentsManager) - .getAllComments(Mockito.any(), Mockito.anyString()); - Response response = this.commentManagementAPI.getAllComments("a", 1, 4); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Mockito.doThrow(new CommentManagementException()).when(this.reviewManager) + .getAllReviews(Mockito.any(), Mockito.anyString()); + Response response = this.commentManagementAPI.getAllReviews("a", 1, 4); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testGetAllCommentsNotFoundError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.getAllComments(null, 1, 3); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.getAllReviews(null, 1, 3); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), "The response status should be 404."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testAddComments() throws Exception { - Comment comment = CommentMgtTestHelper.getDummyComment("a", "a"); - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.addComment(comment, "a"); + Review review = CommentMgtTestHelper.getDummyComment("a", "a"); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.addReview(review, "a"); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), "The response status should be 201."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testAddNullComment() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.addComment(null, "a"); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.addReview(null, "a"); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), "The response status should be 400."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testAddCommentsInternalError() throws Exception { - Comment comment = CommentMgtTestHelper.getDummyComment("a", "a"); - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.when(this.commentManagementAPI.addComment(Mockito.any(), Mockito.anyString())) + Review review = CommentMgtTestHelper.getDummyComment("a", "a"); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Mockito.when(this.commentManagementAPI.addReview(Mockito.any(), Mockito.anyString())) .thenThrow(new CommentManagementException()); - Response response = this.commentManagementAPI.addComment(comment, null); + Response response = this.commentManagementAPI.addReview(review, null); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testUpdateComment() throws Exception { - Comment comment = CommentMgtTestHelper.getDummyComment("a", "a"); - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.updateComment(comment, 1); + Review review = CommentMgtTestHelper.getDummyComment("a", "a"); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.updateComment(review, 1); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The response status should be 200."); @@ -148,7 +149,7 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testUpdateNullComment() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Response response = this.commentManagementAPI.updateComment(null, 1); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), @@ -157,9 +158,9 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testUpdateCommentWhenNullCommentId() throws Exception { - Comment comment = CommentMgtTestHelper.getDummyComment("a", "a"); - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.updateComment(comment, 0); + Review review = CommentMgtTestHelper.getDummyComment("a", "a"); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.updateComment(review, 0); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), "The response status should be 404."); @@ -167,10 +168,10 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testUpdateCommentInternalServerError() throws Exception { - Comment comment = CommentMgtTestHelper.getDummyComment("a", "a"); - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.doThrow(new CommentManagementException()).when(this.commentsManager).updateComment(comment, 9); - Response response = this.commentManagementAPI.updateComment(comment, 9); + Review review = CommentMgtTestHelper.getDummyComment("a", "a"); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Mockito.doThrow(new CommentManagementException()).when(this.reviewManager).updateReview(review, 9, true); + Response response = this.commentManagementAPI.updateComment(review, 9); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); @@ -178,8 +179,8 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testDeleteComment() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.deleteComment(1); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.deleteComment(1,""); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The response status should be 200."); @@ -187,9 +188,9 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testDeleteCommentInternalError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.when(this.commentManagementAPI.deleteComment(1)).thenThrow(new CommentManagementException()); - Response response = this.commentManagementAPI.deleteComment(1); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Mockito.when(this.commentManagementAPI.deleteComment(1,"")).thenThrow(new CommentManagementException()); + Response response = this.commentManagementAPI.deleteComment(1,""); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); @@ -197,8 +198,8 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testDeleteCommentNotFoundError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.deleteComment(0); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); + Response response = this.commentManagementAPI.deleteComment(0,""); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), "The response status should be 404."); @@ -206,101 +207,35 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testGetStars() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Response response = this.commentManagementAPI.getRating("a"); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The response status should be 200."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testGetStarsCommentError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString())) .thenThrow(new CommentManagementException()); Response response = this.commentManagementAPI.getRating("a"); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } @Test public void testGetStarsApplicationError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); + PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString())) .thenThrow(new ApplicationManagementException()); Response response = this.commentManagementAPI.getRating("a"); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); - Mockito.reset(commentsManager); - } - - @Test - public void testGetRatedUser() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.getNumOfRatedUsers("a"); - Assert.assertNotNull(response, "The response object is null."); - Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), - "The response status should be 200."); - Mockito.reset(commentsManager); - } - - @Test - public void testGetRatedUserCommentError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.when(this.commentManagementAPI.getNumOfRatedUsers(Mockito.anyString())) - .thenThrow(new CommentManagementException()); - Response response = this.commentManagementAPI.getNumOfRatedUsers("a"); - Assert.assertNotNull(response, "The response object is null."); - Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), - "The response status should be 500."); - Mockito.reset(commentsManager); - } - - @Test - public void testGetRatedUserApplicationError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.when(this.commentManagementAPI.getNumOfRatedUsers(Mockito.anyString())) - .thenThrow(new ApplicationManagementException()); - Response response = this.commentManagementAPI.getNumOfRatedUsers("a"); - Assert.assertNotNull(response, "The response object is null."); - Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), - "The response status should be 500."); - Mockito.reset(commentsManager); - } - - @Test - public void testUpdateStars() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.updateRatings(3, "a"); - Assert.assertNotNull(response, "The response object is null."); - Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), - "The response status should be 201."); - Mockito.reset(commentsManager); - } - - @Test - public void testUpdateInvalidStars() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Response response = this.commentManagementAPI.updateRatings(0, "a"); - Assert.assertNotNull(response, "The response object is null."); - Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), - "The response status should be 400."); - Mockito.reset(commentsManager); - } - - @Test - public void testUpdateStarsApplicationError() throws Exception { - PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager); - Mockito.doThrow(new ApplicationManagementException()).when(this.commentsManager) - .updateStars(Mockito.anyInt(), Mockito.anyString()); - Response response = this.commentManagementAPI.updateRatings(3, "a"); - Assert.assertNotNull(response, "The response object is null."); - Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), - "The response status should be 500."); - Mockito.reset(commentsManager); + Mockito.reset(reviewManager); } } \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/util/CommentMgtTestHelper.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/util/CommentMgtTestHelper.java index 636c22b40bf..5cd0418f1eb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/util/CommentMgtTestHelper.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/util/CommentMgtTestHelper.java @@ -17,36 +17,34 @@ */ package org.wso2.carbon.device.application.mgt.store.api.services.util; -import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.Review; /** - * Helper class for Comment Management API test cases. + * Helper class for Review Management API test cases. */ public class CommentMgtTestHelper { - private static final String COMMENT_TEXT = "Dummy Comment"; + private static final String COMMENT_TEXT = "Dummy Review"; private static final String CREATED_BY = "TEST_CREATED_BY"; private static final String MODIFIED_BY = "TEST_MODIFIED_BY"; private static final int PARENT_ID = 123; private static final int COMMENT_ID = 1; /** - * Creates a Comment with given text and given uuid. - * If the text is null, the COMMENT_TEXT will be used as the Dummy Comment. + * Creates a Review with given text and given uuid. + * If the text is null, the COMMENT_TEXT will be used as the Dummy Review. * - * @param commentText : Text of the Comment - * @return Comment + * @param commentText : Text of the Review + * @return Review */ - public static Comment getDummyComment(String commentText, String uuid) { - Comment comment = new Comment(); - comment.setId(COMMENT_ID); - comment.setCreatedBy(CREATED_BY); - comment.setModifiedBy(MODIFIED_BY); - comment.setParent(PARENT_ID); - comment.setCommentText(commentText != null ? commentText : COMMENT_TEXT); - - return comment; + public static Review getDummyComment(String commentText, String uuid) { + Review review = new Review(); + review.setId(COMMENT_ID); + review.setUsername(CREATED_BY); + review.setComment(commentText != null ? commentText : COMMENT_TEXT); + + return review; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/resources/testng.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/resources/testng.xml index ab33c9c4105..947e329fbd4 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/resources/testng.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/resources/testng.xml @@ -23,7 +23,7 @@ - + From 7d59c342b277e7ee69502c18a70ba3e2e81473a3 Mon Sep 17 00:00:00 2001 From: Milan Perera Date: Wed, 19 Sep 2018 11:21:40 +0530 Subject: [PATCH 05/10] Application mgt new (#7) * Improve lifecycle state management * Add unit tests for lifecycle management * Add class level comments to lifecycle management --- .../common/services/ApplicationManager.java | 2 +- .../mgt/core/config/Configuration.java | 15 +++ .../mgt/core/impl/ApplicationManagerImpl.java | 121 +++--------------- .../mgt/core/internal/DataHolder.java | 11 ++ .../mgt/core/internal/ServiceComponent.java | 9 ++ .../core/lifecycle/LifecycleStateManger.java | 34 +++++ .../application/mgt/core/lifecycle/State.java | 30 +++++ .../core/lifecycle/config/LifecycleState.java | 35 +++++ .../ConfigurationTest.java | 23 ++-- .../InitTest.java | 20 +++ .../LifecycleManagementTest.java | 57 +++++++++ .../src/test/resources/application-mgt.xml | 43 +++++++ .../src/test/resources/testng.xml | 3 + .../impl/ApplicationManagementAPIImpl.java | 2 +- .../main/resources/conf/application-mgt.xml | 57 +++++++++ 15 files changed, 348 insertions(+), 114 deletions(-) create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManger.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/State.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/config/LifecycleState.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/InitTest.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java index 1335c6d9dc8..4df7b50d33a 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java @@ -150,7 +150,7 @@ public interface ApplicationManager { * @param applicationUuid UUID of the Application Release. * @throws ApplicationManagementException Application Management Exception. */ - void addLifecycleState(int applicationId, String applicationUuid, LifecycleState state) throws ApplicationManagementException; + void changeLifecycleState(int applicationId, String applicationUuid, LifecycleState state) throws ApplicationManagementException; /** * Get the application if application is an accessible one. diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java index 3ef617ff0ee..99f1aa1c566 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java @@ -18,6 +18,8 @@ */ package org.wso2.carbon.device.application.mgt.core.config; +import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; + import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; @@ -37,6 +39,8 @@ public class Configuration { private PaginationConfiguration paginationConfiguration; + private List lifecycleStates; + @XmlElement(name = "DatasourceName", required = true) public String getDatasourceName() { return datasourceName; @@ -60,6 +64,17 @@ public class Configuration { public PaginationConfiguration getPaginationConfiguration() { return paginationConfiguration; } + + @XmlElementWrapper(name = "LifecycleStates") + @XmlElement(name = "LifecycleState") + public List getLifecycleStates() { + return lifecycleStates; + } + + public void setLifecycleStates( + List lifecycleStates) { + this.lifecycleStates = lifecycleStates; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java index b4540d23bd3..dc6d240b192 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java @@ -37,7 +37,6 @@ import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole; import org.wso2.carbon.device.application.mgt.common.User; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; @@ -49,6 +48,7 @@ import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagement import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.ValidationException; import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; +import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; @@ -73,10 +73,12 @@ public class ApplicationManagerImpl implements ApplicationManager { private ApplicationDAO applicationDAO; private ApplicationReleaseDAO applicationReleaseDAO; private LifecycleStateDAO lifecycleStateDAO; + private LifecycleStateManger lifecycleStateManger; public ApplicationManagerImpl() { initDataAccessObjects(); + lifecycleStateManger = DataHolder.getInstance().getLifecycleStateManager(); } private void initDataAccessObjects() { @@ -139,7 +141,7 @@ public class ApplicationManagerImpl implements ApplicationManager { LifecycleState lifecycleState = new LifecycleState(); lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString()); lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString()); - addLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState); + changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState); applicationRelease.setLifecycleState(lifecycleState); applicationReleases.add(applicationRelease); @@ -216,7 +218,7 @@ public class ApplicationManagerImpl implements ApplicationManager { LifecycleState lifecycleState = new LifecycleState(); lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString()); lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString()); - addLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState); + changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState); ConnectionManagerUtil.commitDBTransaction(); return applicationRelease; @@ -406,7 +408,7 @@ public class ApplicationManagerImpl implements ApplicationManager { LifecycleState newAppLifecycleState = new LifecycleState(); newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState()); newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString()); - addLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState); + changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState); storedLocations.add(applicationRelease.getAppHashValue()); } ConnectionManagerUtil.openDBConnection(); @@ -437,7 +439,7 @@ public class ApplicationManagerImpl implements ApplicationManager { LifecycleState newAppLifecycleState = new LifecycleState(); newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState()); newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString()); - addLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState); + changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState); }else{ throw new ApplicationManagementException("Can't delete the application release, You have to move the " + "lifecycle state from "+ currentState + " to acceptable " + @@ -689,7 +691,8 @@ public class ApplicationManagerImpl implements ApplicationManager { + applicationUuid); } - lifecycleState.setNextStates(getNextLifecycleStates(lifecycleState.getCurrentState())); + lifecycleState.setNextStates(new ArrayList<>(lifecycleStateManger. + getNextLifecycleStates(lifecycleState.getCurrentState()))); } catch (ApplicationManagementDAOException e) { throw new ApplicationManagementException("Failed to get lifecycle state", e); } catch (ApplicationManagementException e) { @@ -701,7 +704,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public void addLifecycleState(int applicationId, String applicationUuid, LifecycleState state) + public void changeLifecycleState(int applicationId, String applicationUuid, LifecycleState state) throws ApplicationManagementException { try { ConnectionManagerUtil.openDBConnection(); @@ -712,9 +715,14 @@ public class ApplicationManagerImpl implements ApplicationManager { state.setUpdatedBy(userName); if (state.getCurrentState() != null && state.getPreviousState() != null) { - validateLifecycleState(state); - this.lifecycleStateDAO - .addLifecycleState(state, application.getId(), applicationRelease.getId(), tenantId); + if (lifecycleStateManger.isValidStateChange(state.getPreviousState(), state.getCurrentState())) { + this.lifecycleStateDAO + .addLifecycleState(state, application.getId(), applicationRelease.getId(), tenantId); + } else { + log.error("Invalid lifecycle state transition from '" + state.getPreviousState() + "'" + + " to '" + state.getCurrentState() + "'"); + throw new ApplicationManagementException("Lifecycle State Validation failed"); + } } } catch (LifeCycleManagementDAOException | DBConnectionException e) { throw new ApplicationManagementException("Failed to add lifecycle state", e); @@ -725,99 +733,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - private List getNextLifecycleStates(String currentLifecycleState) { - List nextLifecycleStates = new ArrayList<>(); - if (AppLifecycleState.CREATED.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.IN_REVIEW.toString()); - } - if (AppLifecycleState.IN_REVIEW.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.APPROVED.toString()); - nextLifecycleStates.add(AppLifecycleState.REJECTED.toString()); - } - if (AppLifecycleState.REJECTED.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.IN_REVIEW.toString()); - nextLifecycleStates.add(AppLifecycleState.REMOVED.toString()); - } - if (AppLifecycleState.APPROVED.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.PUBLISHED.toString()); - } - if (AppLifecycleState.PUBLISHED.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.UNPUBLISHED.toString()); - nextLifecycleStates.add(AppLifecycleState.DEPRECATED.toString()); - } - if (AppLifecycleState.UNPUBLISHED.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.PUBLISHED.toString()); - nextLifecycleStates.add(AppLifecycleState.REMOVED.toString()); - } - if (AppLifecycleState.DEPRECATED.toString().equals(currentLifecycleState)) { - nextLifecycleStates.add(AppLifecycleState.REMOVED.toString()); - } - return nextLifecycleStates; - } - - private void validateLifecycleState(LifecycleState state) throws LifecycleManagementException { - - if (AppLifecycleState.CREATED.toString().equals(state.getCurrentState())) { - throw new LifecycleManagementException("Current State Couldn't be " + state.getCurrentState()); - } - if (AppLifecycleState.IN_REVIEW.toString().equals(state.getCurrentState()) && !AppLifecycleState.CREATED - .toString().equals(state.getPreviousState()) && !AppLifecycleState.REJECTED.toString() - .equals(state.getPreviousState())) { - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be either " - + AppLifecycleState.CREATED.toString() + " or " + AppLifecycleState.REJECTED.toString()); - - } - if (AppLifecycleState.APPROVED.toString().equals(state.getCurrentState()) && !AppLifecycleState.IN_REVIEW - .toString().equals(state.getPreviousState())) { - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be " - + AppLifecycleState.IN_REVIEW.toString()); - - } - if (AppLifecycleState.PUBLISHED.toString().equals(state.getCurrentState()) && !AppLifecycleState.APPROVED - .toString().equals(state.getPreviousState()) && !AppLifecycleState.UNPUBLISHED.toString() - .equals(state.getPreviousState())) { - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be either " - + AppLifecycleState.APPROVED.toString() + " or " + AppLifecycleState.UNPUBLISHED - .toString()); - - } - if (AppLifecycleState.UNPUBLISHED.toString().equals(state.getCurrentState()) && !AppLifecycleState.PUBLISHED - .toString().equals(state.getPreviousState())) { - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be " - + AppLifecycleState.PUBLISHED.toString()); - - } - if (AppLifecycleState.REJECTED.toString().equals(state.getCurrentState()) && !AppLifecycleState.IN_REVIEW - .toString().equals(state.getPreviousState())) { - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be " - + AppLifecycleState.IN_REVIEW.toString()); - - } - if (AppLifecycleState.DEPRECATED.toString().equals(state.getCurrentState()) && !AppLifecycleState.PUBLISHED - .toString().equals(state.getPreviousState())) { - - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be " - + AppLifecycleState.PUBLISHED.toString()); - - } - if (AppLifecycleState.REMOVED.toString().equals(state.getCurrentState()) && !AppLifecycleState.DEPRECATED - .toString().equals(state.getPreviousState()) && !AppLifecycleState.REJECTED.toString() - .equals(state.getPreviousState()) && !AppLifecycleState.UNPUBLISHED.toString() - .equals(state.getPreviousState())) { - - throw new LifecycleManagementException( - "If Current State is " + state.getCurrentState() + "Previous State should be either " - + AppLifecycleState.DEPRECATED.toString() + " or " + AppLifecycleState.REJECTED.toString() - + " or " + AppLifecycleState.UNPUBLISHED.toString()); - } - } - @Override public Application updateApplication(Application application) throws ApplicationManagementException { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java index 4f74582336b..68cfce54cd1 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java @@ -23,6 +23,7 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorage import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager; +import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.user.core.service.RealmService; @@ -45,6 +46,8 @@ public class DataHolder { private ApplicationStorageManager applicationStorageManager; + private LifecycleStateManger lifecycleStateManger; + private static final DataHolder applicationMgtDataHolder = new DataHolder(); private DataHolder() { @@ -110,4 +113,12 @@ public class DataHolder { public ApplicationStorageManager getApplicationStorageManager() { return applicationStorageManager; } + + public LifecycleStateManger getLifecycleStateManager() { + return lifecycleStateManger; + } + + public void setLifecycleStateManger(LifecycleStateManger lifecycleStateManger) { + this.lifecycleStateManger = lifecycleStateManger; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java index 7a2fd489ed8..e2224b2c30d 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java @@ -31,12 +31,15 @@ import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleMa import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger; +import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.user.core.service.RealmService; import javax.naming.NamingException; +import java.util.List; /** * @scr.component name="org.wso2.carbon.application.mgt.service" immediate="true" @@ -93,6 +96,12 @@ public class ServiceComponent { ApplicationManagementDAOFactory.init(datasourceName); ApplicationManagementDAOFactory.initDatabases(); + + List lifecycleStates = ConfigurationManager.getInstance(). + getConfiguration().getLifecycleStates(); + LifecycleStateManger lifecycleStateManger = new LifecycleStateManger(lifecycleStates); + DataHolder.getInstance().setLifecycleStateManger(lifecycleStateManger); + log.info("ApplicationManagement core bundle has been successfully initialized"); } catch (InvalidConfigurationException e) { log.error("Error while activating Application Management core component. ", e); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManger.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManger.java new file mode 100644 index 00000000000..1a0218b20b9 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManger.java @@ -0,0 +1,34 @@ +package org.wso2.carbon.device.application.mgt.core.lifecycle; + +import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * This class represents the activities related to lifecycle management + */ +public class LifecycleStateManger { + + private Map lifecycleStates; + + public LifecycleStateManger(List states) { + lifecycleStates = new HashMap<>(); + for (LifecycleState s : states) { + lifecycleStates.put(s.getName(), new State(s.getName(), s.getProceedingStates())); + } + } + + public Set getNextLifecycleStates(String currentLifecycleState) { + return lifecycleStates.get(currentLifecycleState).getProceedingStates(); + } + + public boolean isValidStateChange(String currentState, String nextState) { + if (lifecycleStates.get(currentState).getProceedingStates().contains(nextState)) { + return true; + } + return false; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/State.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/State.java new file mode 100644 index 00000000000..e09b070c19f --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/State.java @@ -0,0 +1,30 @@ +package org.wso2.carbon.device.application.mgt.core.lifecycle; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * This class represents the state of the lifecycle + */ +public class State { + + private Set proceedingStates; + private String stateName; + + public State(String stateName, List states) { + this.stateName = stateName; + if (states != null && !states.isEmpty()) { + proceedingStates = new HashSet<>(states); + } + } + + public String getState() { + return stateName; + } + + public Set getProceedingStates() { + return proceedingStates; + } + +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/config/LifecycleState.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/config/LifecycleState.java new file mode 100644 index 00000000000..c6682e93e90 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/config/LifecycleState.java @@ -0,0 +1,35 @@ +package org.wso2.carbon.device.application.mgt.core.lifecycle.config; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +/** + * This class represents the lifecycle state config + */ +public class LifecycleState { + + private String name; + + private List proceedingStates; + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElementWrapper(name = "ProceedingStates") + @XmlElement(name = "State") + public List getProceedingStates() { + return proceedingStates; + } + + public void setProceedingStates(List proceedingStates) { + this.proceedingStates = proceedingStates; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/ConfigurationTest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/ConfigurationTest.java index 4040237b078..cd6803a1cbf 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/ConfigurationTest.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/ConfigurationTest.java @@ -17,25 +17,30 @@ */ package org.wso2.carbon.device.application.mgt.core; -import org.junit.BeforeClass; -import org.junit.Test; -import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException; +import org.junit.Assert; +import org.testng.annotations.Test; import org.wso2.carbon.device.application.mgt.core.config.Configuration; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; +import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; -import java.io.File; +import java.util.List; public class ConfigurationTest { - @BeforeClass - public static void init() throws InvalidConfigurationException { - File configPath = new File("src/test/resources/application-mgt.xml"); - ConfigurationManager.setConfigLocation(configPath.getAbsolutePath()); + @Test + public void validateConfiguration() { + ConfigurationManager configurationManager = ConfigurationManager.getInstance(); + Configuration configuration = configurationManager.getConfiguration(); + Assert.assertNotNull("Invalid app manager configuration", configuration); } @Test - public void validateConfiguration() { + public void validateLifecycleStateConfiguration() { ConfigurationManager configurationManager = ConfigurationManager.getInstance(); Configuration configuration = configurationManager.getConfiguration(); + List lifecycleStates = configuration.getLifecycleStates(); + Assert.assertNotNull("Invalid lifecycle states configuration", lifecycleStates); + Assert.assertTrue("Invalid lifecycle states configuration. Lifecycle states cannot be empty", + !lifecycleStates.isEmpty()); } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/InitTest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/InitTest.java new file mode 100644 index 00000000000..fae842e8b03 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/InitTest.java @@ -0,0 +1,20 @@ +package org.wso2.carbon.device.application.mgt.core; + +import org.testng.annotations.BeforeSuite; +import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException; +import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; + +import java.io.File; + +/** + * This class initializes the required configurations prior running the tests + */ +public class InitTest { + + @BeforeSuite + public void init() throws InvalidConfigurationException { + File configPath = new File("src/test/resources/application-mgt.xml"); + ConfigurationManager.setConfigLocation(configPath.getAbsolutePath()); + } + +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java new file mode 100644 index 00000000000..4b644debac6 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java @@ -0,0 +1,57 @@ +package org.wso2.carbon.device.application.mgt.core; + +import org.junit.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.device.application.mgt.core.config.Configuration; +import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; +import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger; +import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; + +import java.util.List; +import java.util.Set; + +public class LifecycleManagementTest { + + private List lifecycleStates; + private LifecycleStateManger lifecycleStateManger; + + private final String CURRENT_STATE = "Approved"; + private final String NEXT_STATE = "Published"; + private final String BOGUS_STATE = "Removed"; + + @BeforeClass + public void init() { + ConfigurationManager configurationManager = ConfigurationManager.getInstance(); + Configuration configuration = configurationManager.getConfiguration(); + lifecycleStates = configuration.getLifecycleStates(); + lifecycleStateManger = new LifecycleStateManger(lifecycleStates); + } + + @Test + public void checkValidNextLifecycleState() { + Set proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE); + Assert.assertTrue("Invalid proceeding state of: " + CURRENT_STATE, + proceedingStates.contains(NEXT_STATE)); + } + + @Test + public void checkInvalidNextLifecycleState() { + Set proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE); + Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE, + proceedingStates.contains(BOGUS_STATE)); + } + + @Test + public void checkValidStateChange() { + Assert.assertTrue("Invalid state transition from: " + CURRENT_STATE + " to: " + NEXT_STATE, + lifecycleStateManger.isValidStateChange(CURRENT_STATE, NEXT_STATE)); + } + + @Test + public void checkInvalidStateChange() { + Assert.assertFalse("Invalid state transition from: " + CURRENT_STATE + " to: " + BOGUS_STATE, + lifecycleStateManger.isValidStateChange(CURRENT_STATE, BOGUS_STATE)); + } + +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml index 71ebffdd6bf..b764b9e53e5 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml @@ -58,4 +58,47 @@ + + + + In-Review + + + + + Rejected + Approved + + + + + Published + + + + + In-Review + Removed + + + + + Unpublished + Deprecated + + + + + Removed + + + + + Removed + + + + + + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml index 9a69c5a87fb..8733d4f3361 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/testng.xml @@ -22,8 +22,11 @@ + + + \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java index f212747cef4..f57b2185dfc 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java @@ -448,7 +448,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { LifecycleState state) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); try { - applicationManager.addLifecycleState(applicationId, applicationUuid, state); + applicationManager.changeLifecycleState(applicationId, applicationUuid, state); } catch (ApplicationManagementException e) { String msg = "Error occurred while adding lifecycle state."; log.error(msg, e); diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml index 26a011de639..cfe2145e561 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml @@ -60,4 +60,61 @@ + + + + + + + In-Review + + + + + Rejected + Approved + + + + + Published + + + + + In-Review + Removed + + + + + Unpublished + Deprecated + + + + + Removed + + + + + Removed + + + + + + From 4ded86a1348ddc10a82244cb06cf5c6d12aee743 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 19 Sep 2018 15:55:11 +0530 Subject: [PATCH 06/10] Add app manager osgi fixes --- .../pom.xml | 8 +++---- .../mgt/core/config/Extension.java | 2 +- .../core/impl/SubscriptionManagerImpl.java | 10 ++++---- ...pplicationManagementServiceComponent.java} | 24 +++++++++---------- .../core/util/ApplicationManagementUtil.java | 4 ++-- .../DeviceManagementServiceComponent.java | 3 +++ .../pom.xml | 22 +++++++++++++++++ .../main/resources/conf/application-mgt.xml | 4 ++-- pom.xml | 2 +- 9 files changed, 51 insertions(+), 28 deletions(-) rename components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/{ServiceComponent.java => ApplicationManagementServiceComponent.java} (89%) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml index 932265189f6..bd2a14ba47e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml @@ -42,7 +42,6 @@ org.apache.felix maven-bundle-plugin - 3.0.1 true @@ -50,9 +49,7 @@ ${project.artifactId} ${carbon.device.mgt.version} Application Management Core Bundle - - org.wso2.carbon.device.application.mgt.core.internal - + org.wso2.carbon.device.application.mgt.core.internal org.osgi.framework, org.osgi.service.component, @@ -81,7 +78,8 @@ org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}", org.wso2.carbon.base, - net.dongliu.apk.parser.* + com.dd.*, + org.apache.commons.validator.routines apk-parser;scope=compile|runtime;inline=false diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Extension.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Extension.java index 07e3b09a851..593ecd4a99c 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Extension.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Extension.java @@ -81,7 +81,7 @@ public class Extension { ApplicationManager, ApplicationReleaseManager, CategoryManager, - CommentsManager, + ReviewManager, LifecycleStateManager, PlatformManager, VisibilityTypeManager, diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java index b82057447f7..1717be58c6f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -27,7 +27,7 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.core.dao.SubscriptionDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; -import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil; +import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.HelperUtil; import org.wso2.carbon.device.mgt.common.Device; @@ -68,7 +68,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (log.isDebugEnabled()) { log.debug("Install application: " + applicationUUID + " to " + deviceList.size() + "devices."); } - ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); Application application = applicationManager.getApplicationByRelease(applicationUUID); return installApplication(application, deviceList); @@ -80,7 +80,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (log.isDebugEnabled()) { log.debug("Install application: " + applicationUUID + " to " + userList.size() + " users."); } - ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); Application application = applicationManager.getApplicationByRelease(applicationUUID); List deviceList = new ArrayList<>(); for (String user : userList) { @@ -121,7 +121,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (log.isDebugEnabled()) { log.debug("Install application: " + applicationUUID + " to " + roleList.size() + " roles."); } - ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); Application application = applicationManager.getApplicationByRelease(applicationUUID); List deviceList = new ArrayList<>(); for (String role : roleList) { @@ -162,7 +162,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (log.isDebugEnabled()) { log.debug("Install application: " + applicationUUID + " to " + deviceGroupList.size() + " groups."); } - ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); Application application = applicationManager.getApplicationByRelease(applicationUUID); GroupManagementProviderService groupManagementProviderService = HelperUtil.getGroupManagementProviderService(); List groupList = new ArrayList<>(); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ApplicationManagementServiceComponent.java similarity index 89% rename from components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java rename to components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ApplicationManagementServiceComponent.java index e2224b2c30d..cf891d5d1c7 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ApplicationManagementServiceComponent.java @@ -63,21 +63,26 @@ import java.util.List; * bind="setDataSourceService" * unbind="unsetDataSourceService" */ -public class ServiceComponent { +public class ApplicationManagementServiceComponent { - private static Log log = LogFactory.getLog(ServiceComponent.class); + private static Log log = LogFactory.getLog(ApplicationManagementServiceComponent.class); - protected void activate(ComponentContext componentContext) throws NamingException { + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + + log.info("CALLING ACTIVATE ............."); BundleContext bundleContext = componentContext.getBundleContext(); try { - String datasourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName(); + String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName(); + ApplicationManagementDAOFactory.init(dataSourceName); +// ApplicationManagementDAOFactory.initDatabases(); ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); DataHolder.getInstance().setApplicationManager(applicationManager); bundleContext.registerService(ApplicationManager.class.getName(), applicationManager, null); - ReviewManager reviewManager = ApplicationManagementUtil.getCommentsManagerInstance(); + ReviewManager reviewManager = ApplicationManagementUtil.getReviewManagerInstance(); DataHolder.getInstance().setReviewManager(reviewManager); bundleContext.registerService(ReviewManager.class.getName(), reviewManager, null); @@ -94,19 +99,14 @@ public class ServiceComponent { DataHolder.getInstance().setApplicationStorageManager(applicationStorageManager); bundleContext.registerService(ApplicationStorageManager.class.getName(), applicationStorageManager, null); - ApplicationManagementDAOFactory.init(datasourceName); - ApplicationManagementDAOFactory.initDatabases(); - List lifecycleStates = ConfigurationManager.getInstance(). getConfiguration().getLifecycleStates(); LifecycleStateManger lifecycleStateManger = new LifecycleStateManger(lifecycleStates); DataHolder.getInstance().setLifecycleStateManger(lifecycleStateManger); log.info("ApplicationManagement core bundle has been successfully initialized"); - } catch (InvalidConfigurationException e) { - log.error("Error while activating Application Management core component. ", e); - } catch (ApplicationManagementDAOException e) { - log.error("Error while activating Application Management core component.Failed to create the database ", e); + } catch (Throwable e) { + log.error("Error occurred while initializing app management core bundle", e); } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java index 4127696e30c..488f8147b57 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java @@ -45,9 +45,9 @@ public class ApplicationManagementUtil { return getInstance(extension, ApplicationManager.class); } - public static ReviewManager getCommentsManagerInstance() throws InvalidConfigurationException { + public static ReviewManager getReviewManagerInstance() throws InvalidConfigurationException { ConfigurationManager configurationManager = ConfigurationManager.getInstance(); - Extension extension = configurationManager.getExtension(Extension.Name.CommentsManager); + Extension extension = configurationManager.getExtension(Extension.Name.ReviewManager); return getInstance(extension, ReviewManager.class); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 65decec77f1..fccdc8a86c3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -149,6 +149,9 @@ public class DeviceManagementServiceComponent { @SuppressWarnings("unused") protected void activate(ComponentContext componentContext) { + + log.info("CALLING Crazy ............."); + try { if (log.isDebugEnabled()) { log.debug("Initializing device management core bundle"); diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml index f70e66d5425..ac05f5cac14 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml @@ -30,6 +30,7 @@ org.wso2.carbon.device.application.mgt.server.feature pom 3.1.40-SNAPSHOT + WSO2 Carbon - Application Management Server Feature http://wso2.org This feature contains the core bundles required for Back-end Application Management functionality @@ -44,6 +45,18 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.application.mgt.core + + com.googlecode.plist + dd-plist + ${googlecode.plist.version} + + + + commons-validator + commons-validator + ${commons-validator.version} + + @@ -122,6 +135,12 @@ org.wso2.carbon.devicemgt:org.wso2.carbon.device.application.mgt.core:${carbon.device.mgt.version} + + com.googlecode.plist:dd-plist:${googlecode.plist.version} + + + commons-validator:commons-validator:${commons-validator.version} + @@ -136,4 +155,7 @@ + + 1.6 + diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml index cfe2145e561..9bcbcf4fa49 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml @@ -31,8 +31,8 @@ org.wso2.carbon.device.application.mgt.core.impl.CategoryManagerImpl - - org.wso2.carbon.device.application.mgt.core.impl.CommentsManagerImpl + + org.wso2.carbon.device.application.mgt.core.impl.ReviewManagerImpl org.wso2.carbon.device.application.mgt.core.impl.LifecycleStateManagerImpl diff --git a/pom.xml b/pom.xml index de54d162441..b96ebfe0fc5 100644 --- a/pom.xml +++ b/pom.xml @@ -1840,7 +1840,7 @@ org.apache.felix maven-bundle-plugin - 2.3.5 + 2.5.3 true NONE From 6da8dada710bbab78fcbf42c44076681510ae436 Mon Sep 17 00:00:00 2001 From: lasanthaDLPDS Date: Wed, 19 Sep 2018 18:45:58 +0530 Subject: [PATCH 07/10] Improve comment management --- .../device/application/mgt/common/Review.java | 26 +- ...on.java => ReviewManagementException.java} | 8 +- .../mgt/common/services/ReviewManager.java | 29 +- .../application/mgt/core/dao/ReviewDAO.java | 319 +------ .../application/mgt/core/dao/common/Util.java | 6 +- .../core/dao/impl/Comment/ReviewDAOImpl.java | 829 ++---------------- .../ReviewManagementDAOException.java | 35 + .../mgt/core/impl/ReviewManagerImpl.java | 238 +++-- .../impl/ReviewManagementAPIImpl.java | 19 +- .../api/services/ReviewManagementAPITest.java | 14 +- 10 files changed, 290 insertions(+), 1233 deletions(-) rename components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/{CommentManagementException.java => ReviewManagementException.java} (82%) create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/ReviewManagementDAOException.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java index 2a1b33976a2..e2a488ce3e0 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Review.java @@ -34,9 +34,9 @@ public class Review { value = "Comment of the review") private String comment; - @ApiModelProperty(name = "replyComment", - value = "Reply comment of the review") - private String replyComment; + @ApiModelProperty(name = "parentId", + value = "Parent id of the review") + private int parentId; @ApiModelProperty(name = "username", value = "Username odf the Review creator", @@ -55,6 +55,10 @@ public class Review { value = "Rating value of the application release") private int rating; + @ApiModelProperty(name = "replyReview", + value = "Replying review") + private Review replyReview; + public int getId() { return id; } @@ -103,12 +107,20 @@ public class Review { this.rating = rating; } - public String getReplyComment() { - return replyComment; + public int getParentId() { + return parentId; + } + + public void setParentId(int parentId) { + this.parentId = parentId; + } + + public Review getReplyReview() { + return replyReview; } - public void setReplyComment(String replyComment) { - this.replyComment = replyComment; + public void setReplyReview(Review replyReview) { + this.replyReview = replyReview; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/CommentManagementException.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/ReviewManagementException.java similarity index 82% rename from components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/CommentManagementException.java rename to components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/ReviewManagementException.java index 2f81f5144a1..46255f6a853 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/CommentManagementException.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/ReviewManagementException.java @@ -18,20 +18,20 @@ */ package org.wso2.carbon.device.application.mgt.common.exception; -public class CommentManagementException extends Exception { +public class ReviewManagementException extends Exception { private String message; - public CommentManagementException(String message, Throwable throwable) { + public ReviewManagementException(String message, Throwable throwable) { super(message, throwable); setMessage(message); } - public CommentManagementException(String message) { + public ReviewManagementException(String message) { super(message); setMessage(message); } - public CommentManagementException() { + public ReviewManagementException() { } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java index d9e62337efc..c2ddf4784e9 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ReviewManager.java @@ -22,8 +22,7 @@ import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.PaginationResult; -import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; /** * ReviewManager is responsible for handling all the add/update/delete/get operations related with @@ -37,36 +36,36 @@ public interface ReviewManager { * @param appId id of the application. * @param appReleaseId id of the application release * @return {@link Review} Review added - * @throws CommentManagementException Exceptions of the review management. + * @throws ReviewManagementException Exceptions of the review management. */ - boolean addReview(Review review,int appId, int appReleaseId) throws CommentManagementException; + boolean addReview(Review review,int appId, int appReleaseId) throws ReviewManagementException; /** * Get all comments to pagination * - * @param request Pagination request + * @param request Pagination request {@link PaginationRequest} * @param uuid uuid of the application release * @return {@link PaginationResult} pagination result with starting offSet and limit - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. */ - PaginationResult getAllReviews(PaginationRequest request, String uuid) throws CommentManagementException; + PaginationResult getAllReviews(PaginationRequest request, String uuid) throws ReviewManagementException; /** * To get the comment with id. * * @param commentId id of the comment * @return {@link Review}Review of the comment id - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. */ - Review getReview(int commentId) throws CommentManagementException; + Review getReview(int commentId) throws ReviewManagementException; /** * To delete review using review id. * * @param commentId id of the comment - * @throws CommentManagementException Exceptions of the comment management + * @throws ReviewManagementException Exceptions of the comment management */ - void deleteReview(String loggedInUser, int commentId) throws CommentManagementException; + void deleteReview(String loggedInUser, int commentId) throws ReviewManagementException; /** * To update a review. @@ -74,16 +73,16 @@ public interface ReviewManager { * @param review review of the application. * @param reviewId id of the review * @return {@link Review}updated review - * @throws CommentManagementException Exceptions of the review management + * @throws ReviewManagementException Exceptions of the review management */ - boolean updateReview(Review review, int reviewId, boolean checkExistence) throws CommentManagementException; + boolean updateReview(Review review, int reviewId, boolean checkExistence) throws ReviewManagementException; /** * To get the overall rating for a application release * * @param appReleaseUuuid UUID of the application release. * @return {@link Review}updated review - * @throws CommentManagementException Exceptions of the review management + * @throws ReviewManagementException Exceptions of the review management */ - Rating getRating(String appReleaseUuuid) throws CommentManagementException; + Rating getRating(String appReleaseUuuid) throws ReviewManagementException; } \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java index 009823af99c..6bab98ef4d7 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ReviewDAO.java @@ -20,12 +20,11 @@ package org.wso2.carbon.device.application.mgt.core.dao; import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException; import java.sql.SQLException; -import java.sql.Timestamp; import java.util.List; /** @@ -39,263 +38,58 @@ import java.util.List; * * @param tenantId tenantId of the commented application. * @param review review of the application. - * @param createdBy Username of the created person. - * @param parentId parent id of the parent review. - * @param uuid uuid of the application * @return If review is added successfully, it return true otherwise false - * @throws CommentManagementException Exceptions of the review management. - * @throws DBConnectionException db connection exception. + * @throws ReviewManagementDAOException Exceptions of the review management DAO. */ - boolean addReview(Review review, int appId, int appReleaseId, int tenantId) - throws CommentManagementException, DBConnectionException, SQLException; + boolean addReview(Review review, int appId, int appReleaseId, int tenantId) throws ReviewManagementDAOException; Review isExistReview(int appId, int appReleaseId, String username, int tenantId) throws DBConnectionException, SQLException; - - /** - * To add a review to a application. - * - * @param review review of the application. - * @param createdBy Username of the created person. - * @param appType type of the commented application. - * @param appName name of the commented application. - * @param version version of the commented application. - * @return review id - * @throws CommentManagementException Exceptions of the review management. - */ - int addReview(int tenantId, Review review, String createdBy, String appType, String appName, String version) - throws CommentManagementException, DBConnectionException, SQLException; - /** * To update already added comment. * - * @param commentId id of the comment - * @param updatedComment comment after updated - * @param modifiedBy Username of the modified person. - * @param modifiedAt time of the modification. * @return {@link Review}Updated comment - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception * @throws SQLException sql exception */ boolean updateReview(Review review, int reviewId, int tenantId) - throws CommentManagementException, DBConnectionException, SQLException; + throws ReviewManagementException, DBConnectionException, SQLException; - /** - * To update already added comment. - * - * @param uuid uuid of the comment - * @param commentId id of the comment - * @param updatedComment comment after updated - * @param modifiedBy Username of the modified person. - * @param modifiedAt time of the modification. - * @return {@link Review}Updated comment - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception - * @throws SQLException sql exception - */ - Review updateReview(String uuid, int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) - throws CommentManagementException, DBConnectionException, SQLException; /** * To get the comment with id. * * @param commentId id of the comment * @return {@link Review}Review - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception * @throws SQLException sql exception */ - Review getComment(int commentId) throws CommentManagementException, SQLException, DBConnectionException; - - /** - * To get the comment with id. - * - * @param uuid uuid of the comment - * @return {@link List} List of comments in the application - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception - * @throws SQLException sql exception - */ - List getComment(String uuid) throws CommentManagementException, SQLException, DBConnectionException; + Review getComment(int commentId) throws ReviewManagementException, SQLException, DBConnectionException; /** * To get all the comments * * @param uuid uuid of the application * @param request {@link PaginationRequest}pagination request with offSet and limit + * @param tenantId Tenant id * @return {@link List}List of all the comments in an application - * @throws DBConnectionException db connection exception - * @throws SQLException sql exception + * @throws ReviewManagementDAOException Review management DAO exception **/ - List getAllComments(String uuid, PaginationRequest request) throws SQLException, DBConnectionException; + List getAllReviews(String uuid, PaginationRequest request, int tenantId) + throws ReviewManagementDAOException; /** * To get list of comments using release id and application id. * - * @param appReleasedId Id of the released version of the application. - * @param appId id of the commented application. * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. */ - List getAllRatingValues(String uuid)throws SQLException, DBConnectionException; - List getComments(int appReleasedId, int appId) throws CommentManagementException; - - /** - * To get list of comments using application type, application name and version of the application. - * - * @param appType type of the commented application. - * @param appName name of the commented application. - * @param version version of the commented application. - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getComments(String appType, String appName, String version) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get list of comments using tenant id. - * - * @param tenantId tenant id of the commented application - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getComments(int tenantId) throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get list of comments by created user. - * - * @param createdBy Username of the created person. - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getCommentsByUser(String createdBy) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get list of comments by created use and created time. - * - * @param createdBy Username of the created person. - * @param createdAt time of the comment created. - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getCommentsByUser(String createdBy, Timestamp createdAt) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get list of comments by modified users. - * - * @param modifiedBy Username of the modified person. - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getCommentsByModifiedUser(String modifiedBy) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get list of comments using modified user's name and modified time. - * - * @param modifiedBy Username of the modified person. - * @param modifiedAt time of the modification - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get list of comments using application type, application name , application version and parent id of the comment. - * - * @param appType type of the commented application. - * @param appName name of the commented application. - * @param version version of the commented application. - * @param parentId parent id of the parent comment. - * @return {@link List}List of comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - List getComments(String appType, String appName, String version, int parentId) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get a count of the comments by usernames. - * - * @param uuid uuid of the application - * @return Count of the comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - int getCommentCount(String uuid) throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get a count of the comments by usernames. - * - * @param createdBy Username of the created person. - * @return Count of the comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - int getCommentCountByUser(String createdBy) throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get the comment count by parent comment id. - * - * @param uuid uuid of the comment - * @param parentId id of the parent comment - * @return Count of the comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - int getCommentCountByParent(String uuid, int parentId) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get a count of comments by modification details. - * - * @param modifiedBy Username of the modified person. - * @param modifedAt time of the modification - * @return Count of the comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - int getCommentCountByUser(String modifiedBy, Timestamp modifedAt) - throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To get count of comments by application versions. - * - * @param appId id of the commented application. - * @param appReleaseId Id of the released version of the application. - * @return Count of the comments - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - int getCommentCountByApp(int appId, int appReleaseId) - throws CommentManagementException, DBConnectionException, SQLException; - /** * To get count of comments by application details. * @@ -303,44 +97,22 @@ import java.util.List; * @param appName name of the commented application. * @param version version of the commented application. * @return Count of the comments - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ int getCommentCountByApp(String appType, String appName, String version) - throws CommentManagementException, DBConnectionException, SQLException; + throws ReviewManagementException, DBConnectionException, SQLException; /** * To delete comment using comment id. * * @param commentId id of the comment - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - void deleteComment(int commentId) throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To delete comment using comment id. - * - * @param uuid uuid of the comment - * @throws CommentManagementException Exceptions of the comment management. + * @throws ReviewManagementException Exceptions of the comment management. * @throws DBConnectionException db connection exception. * @throws SQLException sql exception */ - void deleteComment(String uuid) throws CommentManagementException, DBConnectionException, SQLException; - - /** - * To delete comments using application details. - * - * @param appId id of the commented application. - * @param appReleaseID Id of the released version of the application. - * @throws CommentManagementException Exceptions of the comment management. - * @throws DBConnectionException db connection exception. - * @throws SQLException sql exception - */ - void deleteComments(int appId, int appReleaseID) - throws CommentManagementException, DBConnectionException, SQLException; + void deleteComment(int commentId) throws ReviewManagementException, DBConnectionException, SQLException; /** * To delete comments using application details. @@ -348,58 +120,9 @@ import java.util.List; * @param appType type of the commented application. * @param appName name of the commented application. * @param version version of the commented application. - * @throws CommentManagementException Exceptions of the comment management. - */ - void deleteComments(String appType, String appName, String version) throws CommentManagementException; - - /** - * To delete comments using users created and application details. - * - * @param appType type of the commented application. - * @param appName name of the commented application. - * @param version version of the commented application. - * @param createdBy Username of the created person. - * @throws CommentManagementException Exceptions of the comment management. - */ - void deleteComments(String appType, String appName, String version, String createdBy) - throws CommentManagementException; - - /** - * To delete comments by parent id of the comment. - * - * @param uuid uuid of the application - * @param parentId parent id of the parent comment. - * @throws CommentManagementException Exceptions of the comment management. - */ - void deleteComments(String uuid, int parentId) throws CommentManagementException; - - /** - * To add the star rating to the application. - * - * @param stars Star value - * @param uuid UUID of the application - * @return Star value - * @throws ApplicationManagementDAOException Application Management DAO Exception. - */ - int updateStars(int stars, String uuid) throws ApplicationManagementDAOException; - - /** - * To get the average star value of the application - * - * @param uuid uuid of the application - * @return Average of star values - * @throws ApplicationManagementDAOException Application Management DAO Exception. - */ - int getStars(String uuid) throws ApplicationManagementDAOException; - - /** - * To get number of rated users - * - * @param uuid uuid of the application - * @return Number of rated users - * @throws ApplicationManagementDAOException Application Management DAO Exception. + * @throws ReviewManagementException Exceptions of the comment management. */ - int getRatedUser(String uuid) throws ApplicationManagementDAOException; + void deleteComments(String appType, String appName, String version) throws ReviewManagementException; /** * To get comment count for pagination @@ -407,7 +130,7 @@ import java.util.List; * @param request * @param uuid * @return Review count - * @throws CommentManagementException + * @throws ReviewManagementException */ - int getCommentCount(PaginationRequest request, String uuid) throws CommentManagementException; + int getCommentCount(PaginationRequest request, String uuid) throws ReviewManagementException; } \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java index 697b30a9af8..a850452445f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java @@ -25,7 +25,7 @@ import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.core.config.Configuration; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; @@ -202,14 +202,14 @@ public class Util { } public static PaginationRequest validateCommentListPageSize(PaginationRequest paginationRequest) throws - CommentManagementException { + ReviewManagementException { if (paginationRequest.getLimit() == 0) { Configuration commentManagementConfig = ConfigurationManager.getInstance().getConfiguration(); if (commentManagementConfig != null) { paginationRequest.setLimit( commentManagementConfig.getPaginationConfiguration().getCommentListPageSize()); } else { - throw new CommentManagementException( + throw new ReviewManagementException( "Application Management configuration has not initialized. Please check the application-mgt.xml file."); } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java index 80b8c03b152..6afa5246cce 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/ReviewDAOImpl.java @@ -21,18 +21,17 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.Comment; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.Util; import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException; import java.sql.SQLException; -import java.sql.Timestamp; import java.sql.ResultSet; import java.sql.Connection; import java.sql.PreparedStatement; @@ -50,30 +49,37 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { @Override public boolean addReview(Review review, int appId, int appReleaseId, int tenantId) - throws CommentManagementException, DBConnectionException, SQLException { - + throws ReviewManagementDAOException { + //todo if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to add review for application release. Application id: " + appId + "Application Release id: " + appReleaseId); } - Connection conn = this.getDBConnection(); PreparedStatement statement = null; ResultSet rs = null; - sql = "INSERT INTO AP_APP_COMMENT (TENANT_ID, COMMENT_TEXT, CREATED_BY, PARENT_ID,AP_APP_RELEASE_ID," - + "AP_APP_ID) VALUES (?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?)," + sql = "INSERT INTO AP_APP_Review (TENANT_ID, COMMENT, PARENT_ID, USERNAME, AP_APP_RELEASE_ID, AP_APP_ID) " + + "VALUES (?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?)," + "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));"; try { + Connection conn = this.getDBConnection(); statement = conn.prepareStatement(sql, new String[] { "id" }); statement.setInt(1, tenantId); statement.setString(2, review.getComment()); -// statement.setString(3, createdBy); -// statement.setInt(4, parentId); -// statement.setString(5, uuid); -// statement.setString(6, uuid); + statement.setInt(3, review.getParentId()); + statement.setString(4, review.getUsername()); + statement.setString(5,""); + statement.setString(6,""); statement.executeUpdate(); rs = statement.getGeneratedKeys(); return rs.next(); - } finally { + } + catch (DBConnectionException e) { + throw new ReviewManagementDAOException("Error occurred while obtaining the DB connection while " + + "adding review for application UUID: "+ "Tenant Id: " + tenantId, e); + }catch (SQLException e) { + throw new ReviewManagementDAOException("Error occurred while getting application list for the tenant" + + " " + tenantId + ". While executing " + sql, e); + } finally { Util.cleanupResources(statement, rs); } } @@ -90,8 +96,8 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { PreparedStatement statement = null; ResultSet rs = null; Review review = null; - sql = "SELECT ID, COMMENT, REPLY_COMMENT, CREATED_AT, MODEFIED_AT, USERNAME, PARENT_ID, RATING FROM AP_APP_REVIEW " - + "WHERE AP_APP_ID = ? AND AP_APP_RELEASE_ID = ? AND USERNAME = ? AND TENANT_ID = ?;"; + sql = "SELECT ID, COMMENT, CREATED_AT, MODEFIED_AT, USERNAME, PARENT_ID, RATING FROM AP_APP_REVIEW WHERE " + + "AP_APP_ID = ? AND AP_APP_RELEASE_ID = ? AND USERNAME = ? AND TENANT_ID = ?;"; try { conn = this.getDBConnection(); statement = conn.prepareStatement(sql); @@ -105,7 +111,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { review = new Review(); review.setId(rs.getInt("ID")); review.setComment(rs.getString("COMMENT")); - review.setReplyComment(rs.getString("REPLY_COMMENT")); + review.setParentId(rs.getInt("PARENT_ID")); review.setCreatedAt(rs.getTimestamp("CREATED_AT")); review.setModifiedAt(rs.getTimestamp("MODIFIED_AT")); review.setUsername(rs.getString("USERNAME")); @@ -117,45 +123,8 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { } } - - @Override - public int addReview(int tenantId, Review review, String createdBy, String appType, String appName, - String version) throws CommentManagementException, DBConnectionException, SQLException { - - if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to add to application (" + appName + ") and version (" + version - + ")"); - } - Connection conn = this.getDBConnection(); - PreparedStatement statement = null; - ResultSet rs; - int commentId = -1; - sql = "INSERT INTO AP_APP_COMMENT ( TENANT_ID,COMMENT_TEXT, CREATED_BY,AP_APP_RELEASE_ID,AP_APP_ID) " - + "VALUES (?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE VERSION =? AND (SELECT ID FROM AP_APP WHERE " - + "TYPE=? AND NAME=?)),(SELECT ID FROM AP_APP WHERE TYPE=? AND NAME=?));"; - try { - statement = conn.prepareStatement(sql, new String[] { "id" }); - statement.setInt(1, tenantId); - statement.setString(2, review.getComment()); - statement.setString(3, createdBy); - statement.setString(4, version); - statement.setString(5, appType); - statement.setString(6, appName); - statement.setString(7, appType); - statement.setString(8, appName); - statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - commentId = rs.getInt(1); - } - } finally { - Util.cleanupResources(statement, null); - } - return commentId; - } - @Override - public boolean updateReview(Review review, int reviewId, int tenantId) throws CommentManagementException, DBConnectionException, SQLException { + public boolean updateReview(Review review, int reviewId, int tenantId) throws ReviewManagementException, DBConnectionException, SQLException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to update the comment with ID (" + reviewId + ")"); @@ -180,33 +149,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { } @Override - public Review updateReview(String uuid, int commentId, String updatedComment, String modifiedBy, - Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException { - - if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to update the comment with application (" + uuid + ") and " - + "comment id ( " + commentId + ")"); - } - Connection connection; - PreparedStatement statement = null; - ResultSet rs = null; - sql = "UPDATE AP_APP_COMMENT SET COMMENT_TEXT=?,MODEFIED_BY=? WHERE ID=?; "; - try { - connection = this.getDBConnection(); - statement = connection.prepareStatement(sql); - statement.setString(1, updatedComment); - statement.setString(2, modifiedBy); - statement.setInt(3, commentId); - statement.executeUpdate(); - rs = statement.getResultSet(); - } finally { - Util.cleanupResources(statement, rs); - } - return getComment(commentId); - } - - @Override - public Review getComment(int commentId) throws CommentManagementException { + public Review getComment(int commentId) throws ReviewManagementException { if (log.isDebugEnabled()) { log.debug("Getting review with the review id(" + commentId + ") from the database"); @@ -232,7 +175,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { return review; } } catch (SQLException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "SQL Error occurred while retrieving information of the review " + commentId, e); } catch (DBConnectionException e) { log.error("DB Connection Exception occurred while retrieving information of the review " + commentId, e); @@ -243,46 +186,8 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { } @Override - public List getComment(String uuid) throws CommentManagementException { - - if (log.isDebugEnabled()) { - log.debug("Getting comment with the application release(" + uuid + ") from the database"); - } - Connection conn; - PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); - try { - conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE (SELECT ID FROM AP_APP_RELEASE where UUID=?)AND " - + "(SELECT AP_APP_ID FROM AP_APP_RELEASE where UUID=?);"; - statement = conn.prepareStatement(sql); - statement.setString(1, uuid); - statement.setString(2, uuid); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } - } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while retrieving reviews", e); - } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurred while retrieving reviews", e); - } finally { - Util.cleanupResources(statement, null); - } - return reviews; - } - - @Override - public List getAllComments(String uuid, PaginationRequest request) - throws SQLException, DBConnectionException { + public List getAllReviews(String uuid, PaginationRequest request, int tenantId) + throws ReviewManagementDAOException { if (log.isDebugEnabled()) { log.debug("Getting comment of the application release (" + uuid + ") from the database"); @@ -293,16 +198,17 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); - sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS " - + "COMMENT_TEXT, AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS " - + "MODIFIED_BY, AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE " + sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS COMMENT_TEXT, " + + "AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS MODIFIED_BY, " + + "AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE " + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND " + "AP_APP_COMMENT.TENANT_ID = ? AND AP_APP_COMMENT.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + "LIMIT ? OFFSET ?;"; statement = conn.prepareStatement(sql); statement.setString(1, uuid); - statement.setInt(2, request.getLimit()); - statement.setInt(3, request.getOffSet()); + statement.setInt(2, tenantId); + statement.setInt(3, request.getLimit()); + statement.setInt(4, request.getOffSet()); rs = statement.executeQuery(); while (rs.next()) { Review review = new Review(); @@ -311,7 +217,12 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { review.setUsername(rs.getString("CREATED_BY")); reviews.add(review); } - } finally { + } catch (DBConnectionException e) { + throw new ReviewManagementDAOException( + "Error occurred while obtaining the DB connection when verifying application existence", e); + } catch (SQLException e) { + throw new ReviewManagementDAOException("Error occurred while adding unrestricted roles", e); + }finally { Util.cleanupResources(statement, rs); } return reviews; @@ -348,7 +259,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { } @Override - public int getCommentCount(PaginationRequest request, String uuid) throws CommentManagementException { + public int getCommentCount(PaginationRequest request, String uuid) throws ReviewManagementException { int commentCount = 0; Connection conn; @@ -372,7 +283,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { } } } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurred while retrieving count of comments", e); + throw new ReviewManagementException("SQL Error occurred while retrieving count of comments", e); } catch (DBConnectionException e) { log.error("DB Connection Exception occurred while retrieving count of comments", e); } finally { @@ -382,668 +293,74 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { } @Override - public List getComments(int appReleasedId, int appId) throws CommentManagementException { - - if (log.isDebugEnabled()) { - log.debug("Getting reviews with the application release id(" + appReleasedId + ") and " + "application id(" - + appId + ") from the database"); - } - Connection conn; - PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); - try { - conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? AND AP_APP_ID=?;"; - statement = conn.prepareStatement(sql); - statement.setInt(1, appReleasedId); - statement.setInt(2, appId); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } - } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while retrieving information of reviews", e); - } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurred while retrieving information of reviews", e); - } finally { - Util.cleanupResources(statement, null); - } - return reviews; - } - - @Override - public List getComments(String appType, String appName, String version) - throws CommentManagementException, DBConnectionException, SQLException { + public int getCommentCountByApp(String appType, String appName, String version) + throws ReviewManagementException, DBConnectionException, SQLException { - if (log.isDebugEnabled()) { - log.debug("Getting reviews with the application name(" + appName + "),application type(" + appType + ") " - + "and application version (" + version + ") from the database"); - } Connection conn; PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); + int commentCount = 0; try { conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID FROM AP_APP_COMMENT C ," - + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=?) R," - + "(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? AND TYPE=?)P" - + " WHERE AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND AP_APP_ID=RELEASE_AP_APP_ID" - + "ORDER BY CREATED_AT DESC;"; + sql = "SELECT COUNT(ID) AS COMMENT_COUNT FROM AP_APP_COMMENT C, " + + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=? )R," + + "(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? and TYPE=?)P " + + "WHERE AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND AP_APP_ID=RELEASE_AP_APP_ID;"; statement = conn.prepareStatement(sql); statement.setString(1, version); statement.setString(2, appName); statement.setString(3, appType); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } - } finally { - Util.cleanupResources(statement, null); - } - return reviews; - } - - @Override - public List getComments(int tenantId) - throws CommentManagementException, DBConnectionException, SQLException { - - if (log.isDebugEnabled()) { - log.debug("Getting reviews with the tenant_id(" + tenantId + ") from the database"); - } - Connection conn; - PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); - try { - conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE TENANT_ID='?';"; - statement = conn.prepareStatement(sql); - statement.setInt(1, tenantId); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } - } finally { - Util.cleanupResources(statement, null); - } - return reviews; - } - - @Override - public List getCommentsByUser(String createdBy) - throws CommentManagementException, DBConnectionException, SQLException { - - if (log.isDebugEnabled()) { - log.debug("Getting reviews with the created by(" + createdBy + ") from the database"); - } - Connection conn; - PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); - try { - conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT ,PARENT_ID,TENANT_ID,CREATED_AT FROM AP_APP_COMMENT WHERE CREATED_BY= ?" - + " ORDER BY CREATED_AT DESC;"; - statement = conn.prepareStatement(sql); - statement.setString(1, createdBy); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENT_COUNT"); } } finally { Util.cleanupResources(statement, null); } - return reviews; + return commentCount; } @Override - public List getCommentsByUser(String createdBy, Timestamp createdAt) - throws CommentManagementException, DBConnectionException, SQLException { + public void deleteComment(int commentId) + throws ReviewManagementException, DBConnectionException, SQLException { - if (log.isDebugEnabled()) { - log.debug( - "Getting reviews with the created by(" + createdBy + ") at (" + createdAt + ") from the database"); - } Connection conn; PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID FROM AP_APP_COMMENT WHERE CREATED_BY=?" - + "AND CREATED_AT= ? ORDER BY CREATED_AT DESC;"; + sql = "DELETE FROM AP_APP_COMMENT WHERE ID=?;"; statement = conn.prepareStatement(sql); - statement.setString(1, createdBy); - statement.setTimestamp(2, createdAt); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } + statement.setInt(1, commentId); + statement.executeUpdate(); } finally { Util.cleanupResources(statement, null); } - return reviews; } @Override - public List getCommentsByModifiedUser(String modifiedBy) - throws CommentManagementException, DBConnectionException, SQLException { + public void deleteComments(String appType, String appName, String version) + throws ReviewManagementException { - if (log.isDebugEnabled()) { - log.debug("Getting reviews with the modified by(" + modifiedBy + ") from the database"); - } Connection conn; PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); try { conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID,CREATED_AT,MODEFIED_AT FROM AP_APP_COMMENT " - + "WHERE MODEFIED_BY= ? ORDER BY CREATED_AT DESC;"; + sql = "DELETE FROM AP_APP_COMMENT WHERE " + + "(SELECT AP_APP_RELEASE_ID FROM AP_APP_RELEASE WHERE VERSION=? AND " + + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? AND TYPE=?)) AND " + + "(SELECT AP_APP_ID FROM AP_APP AND NAME=? AND TYPE=?);"; statement = conn.prepareStatement(sql); - statement.setString(1, modifiedBy); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } + statement.setString(1, version); + statement.setString(2, appName); + statement.setString(3, appType); + statement.setString(4, appName); + statement.setString(5, appType); + statement.executeUpdate(); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while deleting comments", e); + } catch (SQLException e) { + throw new ReviewManagementException("SQL Error occurred while deleting comments", e); } finally { Util.cleanupResources(statement, null); } - return reviews; - } - - @Override - public List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) - throws CommentManagementException, DBConnectionException, SQLException { - - if (log.isDebugEnabled()) { - log.debug("Getting reviews with the modified by(" + modifiedBy + ") at (" + modifiedAt + ") from the " - + "database"); - } - Connection conn; - PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); - try { - conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID,CREATED_AT FROM AP_APP_COMMENT WHERE MODEFIED_BY= ?," - + "MODEFIED_AT=? ORDER BY CREATED_AT DESC;"; - statement = conn.prepareStatement(sql); - statement.setString(1, modifiedBy); - statement.setTimestamp(2, modifiedAt); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } - } finally { - Util.cleanupResources(statement, null); - } - return reviews; - } - - @Override - public List getComments(String appType, String appName, String version, int parentId) - throws CommentManagementException, DBConnectionException, SQLException { - - if (log.isDebugEnabled()) { - log.debug( - "Getting reviews with the application name(" + appName + "),application type(" + appType + ") and" - + "application version (" + version + ") from the database"); - } - Connection conn; - PreparedStatement statement = null; - ResultSet rs; - List reviews = new ArrayList<>(); - try { - conn = this.getDBConnection(); - sql = "SELECT COMMENT_TEXT,TENANT_ID FROM AP_APP_COMMENT C ," - + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=? ) " - + "R,(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? AND TYPE=?)P " - + "WHERE PARENT_ID=? AND AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND " - + "AP_APP_ID=RELEASE_AP_APP_ID ORDER BY CREATED_AT DESC;"; - statement = conn.prepareStatement(sql); - statement.setString(1, version); - statement.setString(2, appName); - statement.setString(3, appType); - statement.setInt(4, parentId); - rs = statement.executeQuery(); - while (rs.next()) { - Review review = new Review(); - review.setId(rs.getInt("ID")); -// review.setTenantId(rs.getInt("TENANT_ID")); - review.setComment(rs.getString("COMMENT_TEXT")); - review.setCreatedAt(rs.getTimestamp("CREATED_AT")); - review.setUsername(rs.getString("CREATED_BY")); - review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); - reviews.add(review); - } - } finally { - Util.cleanupResources(statement, null); - } - return reviews; - } - - @Override - public int getCommentCount(String uuid) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - int commentCount = 0; - try { - conn = this.getDBConnection(); - sql = "SELECT COUNT(AP_APP_COMMENT.ID) FROM AP_APP_COMMENT,AP_APP_RELEASE WHERE " - + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_COMMENT.AP_APP_ID=" - + "AP_APP_RELEASE.AP_APP_ID AND AP_APP_RELEASE.UUID=?;"; - statement = conn.prepareStatement(sql); - statement.setString(1, uuid); - ResultSet rs = statement.executeQuery(); - if (rs.next()) { - commentCount = rs.getInt("ID"); - } - } finally { - Util.cleanupResources(statement, null); - return commentCount; - } - } - - @Override - public int getCommentCountByUser(String createdBy) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - int commentCount = 0; - try { - conn = this.getDBConnection(); - sql = "SELECT COUNT(ID) FROM AP_APP_COMMENT WHERE CREATED_BY= ?;"; - statement = conn.prepareStatement(sql); - statement.setString(1, createdBy); - ResultSet rs = statement.executeQuery(); - if (rs.next()) { - commentCount = rs.getInt("COMMENT_COUNT"); - } - } finally { - Util.cleanupResources(statement, null); - } - return commentCount; - } - - @Override - public int getCommentCountByUser(String modifiedBy, Timestamp modifedAt) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - int commentCount = 0; - try { - conn = this.getDBConnection(); - sql = "SELECT COUNT(ID) FROM AP_APP_COMMENT WHERE MODEFIED_BY= ? AND MODEFIED_AT=?;"; - statement = conn.prepareStatement(sql); - statement.setString(1, modifiedBy); - statement.setTimestamp(2, modifedAt); - ResultSet rs = statement.executeQuery(); - if (rs.next()) { - commentCount = rs.getInt("COMMENT_COUNT"); - } - } finally { - Util.cleanupResources(statement, null); - } - return commentCount; - } - - @Override - public int getCommentCountByApp(int appId, int appReleaseId) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - int commentCount = 0; - try { - conn = this.getDBConnection(); - sql = "SELECT COUNT(ID) FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? AND AP_APP_ID=?;"; - statement = conn.prepareStatement(sql); - statement.setInt(1, appReleaseId); - statement.setInt(2, appId); - ResultSet rs = statement.executeQuery(); - if (rs.next()) { - commentCount = rs.getInt("COMMENT_COUNT"); - } - } finally { - Util.cleanupResources(statement, null); - } - return commentCount; - } - - @Override - public int getCommentCountByApp(String appType, String appName, String version) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - int commentCount = 0; - try { - conn = this.getDBConnection(); - sql = "SELECT COUNT(ID) AS COMMENT_COUNT FROM AP_APP_COMMENT C, " - + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=? )R," - + "(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? and TYPE=?)P " - + "WHERE AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND AP_APP_ID=RELEASE_AP_APP_ID;"; - statement = conn.prepareStatement(sql); - statement.setString(1, version); - statement.setString(2, appName); - statement.setString(3, appType); - ResultSet rs = statement.executeQuery(); - if (rs.next()) { - commentCount = rs.getInt("COMMENT_COUNT"); - } - } finally { - Util.cleanupResources(statement, null); - } - return commentCount; - } - - public int getCommentCountByParent(String uuid, int parentId) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - int commentCount = 0; - try { - conn = this.getDBConnection(); - sql = "SELECT COUNT(AP_APP_COMMENT.ID) FROM AP_APP_COMMENT,AP_APP_RELEASE WHERE " - + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND " - + "AP_APP_COMMENT.AP_APP_ID=AP_APP_RELEASE.AP_APP_ID and AP_APP_RELEASE.UUID=? and PARENT_ID=?;"; - - statement = conn.prepareStatement(sql); - statement.setString(1, uuid); - statement.setInt(2, parentId); - ResultSet rs = statement.executeQuery(); - if (rs.next()) { - commentCount = rs.getInt("COMMENT_COUNT"); - } - } finally { - Util.cleanupResources(statement, null); - } - return commentCount; - } - - @Override - public void deleteComment(int commentId) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - try { - conn = this.getDBConnection(); - sql = "DELETE FROM AP_APP_COMMENT WHERE ID=?;"; - statement = conn.prepareStatement(sql); - statement.setInt(1, commentId); - statement.executeUpdate(); - } finally { - Util.cleanupResources(statement, null); - } - } - - public void deleteComment(String uuid) throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - try { - conn = this.getDBConnection(); - sql = "DELETE FROM AP_APP_COMMENT WHERE " - + "(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?)AND (SELECT AP_APP_ID FROM AP_APP_RELEASE " - + "WHERE UUID=?);"; - statement = conn.prepareStatement(sql); - statement.setString(1, uuid); - statement.setString(2, uuid); - statement.executeUpdate(); - } finally { - Util.cleanupResources(statement, null); - } - } - - @Override - public void deleteComments(int appId, int appReleaseID) - throws CommentManagementException, DBConnectionException, SQLException { - - Connection conn; - PreparedStatement statement = null; - try { - conn = this.getDBConnection(); - sql = "DELETE FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? and AP_APP_ID=?;"; - statement = conn.prepareStatement(sql); - statement.setInt(1, appReleaseID); - statement.setInt(2, appId); - statement.executeUpdate(); - } finally { - Util.cleanupResources(statement, null); - } - } - - @Override - public void deleteComments(String appType, String appName, String version) - throws CommentManagementException { - - Connection conn; - PreparedStatement statement = null; - try { - conn = this.getDBConnection(); - sql = "DELETE FROM AP_APP_COMMENT WHERE " - + "(SELECT AP_APP_RELEASE_ID FROM AP_APP_RELEASE WHERE VERSION=? AND " - + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? AND TYPE=?)) AND " - + "(SELECT AP_APP_ID FROM AP_APP AND NAME=? AND TYPE=?);"; - statement = conn.prepareStatement(sql); - statement.setString(1, version); - statement.setString(2, appName); - statement.setString(3, appType); - statement.setString(4, appName); - statement.setString(5, appType); - statement.executeUpdate(); - } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while deleting comments", e); - } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurred while deleting comments", e); - } finally { - Util.cleanupResources(statement, null); - } - } - - @Override - public void deleteComments(String appType, String appName, String version, String createdBy) - throws CommentManagementException { - - Connection conn; - PreparedStatement statement = null; - try { - conn = this.getDBConnection(); - sql = "DELETE FROM AP_APP_COMMENT WHERE " - + "(SELECT AP_APP_RELEASE_ID FROM AP_APP_RELEASE WHERE VERSION=? AND " - + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? AND TYPE=?)) AND " - + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? and TYPE=?) AND CREATED_BY=?;"; - statement = conn.prepareStatement(sql); - statement.setString(1, version); - statement.setString(2, appName); - statement.setString(3, appType); - statement.setString(4, appName); - statement.setString(5, appType); - statement.setString(6, createdBy); - statement.executeUpdate(); - } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while deleting comments ", e); - } catch (SQLException e) { - throw new CommentManagementException("Error occurred while deleting comments", e); - } finally { - Util.cleanupResources(statement, null); - } - } - - @Override - public void deleteComments(String uuid, int parentId) throws CommentManagementException { - - Connection conn; - PreparedStatement statement = null; - try { - conn = this.getDBConnection(); - sql = "DELETE FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?) " - + "AND AP_APP_ID=(SELECT AP_APP_ID FROM AP_APP_RELEASE where UUID=?)AND PARENT_ID=?;"; - statement = conn.prepareStatement(sql); - statement.setString(1, uuid); - statement.setString(2, uuid); - statement.setInt(3, parentId); - statement.executeUpdate(); - } catch (DBConnectionException e) { - log.error("DB Connection Exception occurred while deleting comments.", e); - } catch (SQLException e) { - throw new CommentManagementException("Error occurred while deleting comments", e); - } finally { - Util.cleanupResources(statement, null); - } - } - - @Override - public int updateStars(int stars, String uuid) throws ApplicationManagementDAOException { - - Connection connection; - PreparedStatement statement = null; - ResultSet resultSet = null; - try { - connection = this.getDBConnection(); - sql = "UPDATE AP_APP_RELEASE SET STARS=?, NO_OF_RATED_USERS=(NO_OF_RATED_USERS+1) WHERE UUID=?;"; - statement = connection.prepareStatement(sql); - statement.setInt(1, stars); - statement.setString(2, uuid); - resultSet = statement.executeQuery(sql); - if (resultSet != null) { - resultSet.getInt("STARS"); - } - int numORows = resultSet.getRow(); - if (resultSet.next()) { - ApplicationRelease applicationRelease = new ApplicationRelease(); - applicationRelease.setRating(resultSet.getDouble("RATING")); - Util.cleanupResources(statement, resultSet); - } - } catch (SQLException e) { - throw new ApplicationManagementDAOException( - "SQL Exception while trying to add stars to an application (UUID : " + uuid + "), by executing " - + "the query " + e); - } catch (DBConnectionException e) { - log.error("DB Connection Exception while trying to add stars to an application (UUID : " + uuid + "), ", - e); - } finally { - Util.cleanupResources(statement, null); - return getStars(uuid); - } - } - - @Override - public int getStars(String uuid) throws ApplicationManagementDAOException { - - Connection connection; - PreparedStatement statement = null; - ResultSet resultSet = null; - int Stars = 0; - try { - connection = this.getDBConnection(); - sql = "SELECT STARS FROM AP_APP_RELEASE WHERE UUID=?;"; - statement = connection.prepareStatement(sql); - statement.setString(1, uuid); - resultSet = statement.executeQuery(); - if (resultSet.next()) { - ApplicationRelease applicationRelease = new ApplicationRelease(); - Stars = resultSet.getInt("STARS"); - return Stars; - } - } catch (SQLException e) { - throw new ApplicationManagementDAOException( - "SQL Exception while trying to get stars from an application (UUID : " + uuid + "), by executing " - + "the query " + e); - } catch (DBConnectionException e) { - log.error( - "DB Connection Exception while trying to get stars from an application (UUID : " + uuid + ")," + e); - } finally { - Util.cleanupResources(statement, resultSet); - } - return Stars; - } - - @Override - public int getRatedUser(String uuid) throws ApplicationManagementDAOException { - - Connection connection; - PreparedStatement statement = null; - ResultSet resultSet = null; - int ratedUsers = 0; - try { - connection = this.getDBConnection(); - sql = "SELECT NO_OF_RATED_USERS FROM AP_APP_RELEASE WHERE UUID=?;"; - statement = connection.prepareStatement(sql); - statement.setString(1, uuid); - resultSet = statement.executeQuery(); - if (resultSet.next()) { - ApplicationRelease applicationRelease = new ApplicationRelease(); - ratedUsers = resultSet.getInt("NO_OF_RATED_USERS"); - applicationRelease.setRatedUsers(ratedUsers); - Util.cleanupResources(statement, resultSet); - return ratedUsers; - } - } catch (SQLException e) { - log.error("SQL Exception occurs.", e); - } catch (DBConnectionException e) { - log.error("DB Connection Exception occurs.", e); - } finally { - Util.cleanupResources(statement, resultSet); - } - return ratedUsers; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/ReviewManagementDAOException.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/ReviewManagementDAOException.java new file mode 100644 index 00000000000..f32f08b3244 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/ReviewManagementDAOException.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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. + * + */ +package org.wso2.carbon.device.application.mgt.core.exception; + +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; + +/** + * Exception thrown during the Review Management DAO operations. + */ +public class ReviewManagementDAOException extends ReviewManagementException { + + public ReviewManagementDAOException(String message, Throwable throwable) { + super(message, throwable); + } + + public ReviewManagementDAOException(String message) { + super(message, new Exception()); + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java index f742fd5c57b..85e4ec184b8 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ReviewManagerImpl.java @@ -1,20 +1,20 @@ /* -* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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. -* -*/ + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * WSO2 Inc. licenses this file to you 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. + * + */ package org.wso2.carbon.device.application.mgt.core.impl; import org.apache.commons.logging.Log; @@ -25,7 +25,7 @@ import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.PaginationResult; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException; import org.wso2.carbon.device.application.mgt.common.services.*; @@ -34,6 +34,7 @@ import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.dao.common.Util; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException; import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.user.api.UserRealm; @@ -41,6 +42,7 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; import java.util.TreeMap; @@ -62,8 +64,7 @@ public class ReviewManagerImpl implements ReviewManager { this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO(); } - @Override - public boolean addReview(Review review, int appId, int appReleaseId) throws CommentManagementException { + @Override public boolean addReview(Review review, int appId, int appReleaseId) throws ReviewManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); boolean isSuccess; @@ -71,16 +72,7 @@ public class ReviewManagerImpl implements ReviewManager { ConnectionManagerUtil.beginDBTransaction(); Review existingReview = reviewDAO.isExistReview(appId, appReleaseId, username, tenantId); if (existingReview != null && review.getRating() > 0 && review.getRating() != existingReview.getRating()) { - Runnable task = () -> { - try { - if (calculateRating(review.getRating(), existingReview.getRating()) <= 0.0) { - log.error("Application release rating updating task is failed"); - } - } catch (CommentManagementException e) { - // todo - log.error("comment management error occured"); - } - }; + Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating()); new Thread(task).start(); isSuccess = updateReview(review, existingReview.getId(), false); if (isSuccess) { @@ -89,17 +81,8 @@ public class ReviewManagerImpl implements ReviewManager { ConnectionManagerUtil.rollbackDBTransaction(); } } else { - if (review.getRating()>0){ - Runnable task = () -> { - try { - if (calculateRating(review.getRating(), -12345) <= 0.0) { - log.error("Application release rating inserting task is failed"); - } - } catch (CommentManagementException e) { - // todo - log.error("comment management error occured"); - } - }; + if (review.getRating() > 0) { + Runnable task = () -> calculateRating(review.getRating(), -12345); new Thread(task).start(); } review.setUsername(username); @@ -113,17 +96,17 @@ public class ReviewManagerImpl implements ReviewManager { return isSuccess; } catch (DBConnectionException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( + throw new ReviewManagementException( "DB Connection error occurs ,Review for application with app id: " + appId + " and app release id: " + appReleaseId + " is failed", e); } catch (SQLException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( + throw new ReviewManagementException( "SQL Exception occurs,Review for application with app id:" + appId + " and app release id:" + appReleaseId + " is failed", e); } catch (TransactionManagementException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( + throw new ReviewManagementException( "Transaction Management Exception occurs,Review for application with app id:" + appId + " and app release id:" + appReleaseId + " is failed ", e); } finally { @@ -131,9 +114,8 @@ public class ReviewManagerImpl implements ReviewManager { } } - @Override - public boolean updateReview(Review review, int reviewId, boolean checkExistence) - throws CommentManagementException { + @Override public boolean updateReview(Review review, int reviewId, boolean checkExistence) + throws ReviewManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); Review existingReview; @@ -143,28 +125,20 @@ public class ReviewManagerImpl implements ReviewManager { } try { ConnectionManagerUtil.openDBConnection(); + // todo if (!username.equals(review.getUsername())) { - throw new CommentManagementException( + throw new ReviewManagementException( "User " + review.getUsername() + "doesn't match with the logged in user: " + username); } if (checkExistence) { existingReview = this.reviewDAO.getComment(reviewId); if (existingReview != null) { if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) { - Runnable task = () -> { - try { - if (calculateRating(review.getRating(), existingReview.getRating()) <= 0.0) { - log.error("Application release review updating task is failed"); - } - } catch (CommentManagementException e) { - // todo - log.error("error"); - } - }; + Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating()); new Thread(task).start(); } } else { - throw new CommentManagementException("Couldn't find a review for review id: " + reviewId); + throw new ReviewManagementException("Couldn't find a review for review id: " + reviewId); } } ConnectionManagerUtil.beginDBTransaction(); @@ -176,13 +150,13 @@ public class ReviewManagerImpl implements ReviewManager { } return isSuccess; } catch (SQLException e) { - throw new CommentManagementException("SQL Error occurs updating review with review id " + reviewId + ".", + throw new ReviewManagementException("SQL Error occurs updating review with review id " + reviewId + ".", e); } catch (DBConnectionException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "DB Connection error occurs updating review with review id " + reviewId + ".", e); } catch (TransactionManagementException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "Transaction management error occurs when updating review with review id " + reviewId + ".", e); } finally { ConnectionManagerUtil.closeDBConnection(); @@ -190,39 +164,51 @@ public class ReviewManagerImpl implements ReviewManager { } @Override - public PaginationResult getAllReviews(PaginationRequest request, String uuid) throws CommentManagementException { + public PaginationResult getAllReviews(PaginationRequest request, String uuid) + throws ReviewManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); PaginationResult paginationResult = new PaginationResult(); int numOfComments; List reviews; + TreeMap hierarchicalReviewSet = new TreeMap<>(); if (log.isDebugEnabled()) { - log.debug("get all reviews of the application release" + uuid); + log.debug("Get all reviews of the application release uuid: " + uuid); } try { ConnectionManagerUtil.openDBConnection(); - reviews = this.reviewDAO.getAllComments(uuid, Util.validateCommentListPageSize(request)); - numOfComments = reviews.size(); - paginationResult.setData(reviews); + reviews = this.reviewDAO.getAllReviews(uuid, Util.validateCommentListPageSize(request), tenantId); + + for (Review review : reviews) { + if (hierarchicalReviewSet.containsKey(review.getParentId())) { + Review parentReview = hierarchicalReviewSet.get(review.getParentId()); + parentReview.setReplyReview(review); + hierarchicalReviewSet.replace(review.getParentId(), parentReview); + } else { + hierarchicalReviewSet.put(review.getId(), review); + } + } + numOfComments = hierarchicalReviewSet.size(); if (numOfComments > 0) { + paginationResult.setData(new ArrayList<>(hierarchicalReviewSet.values())); paginationResult.setRecordsFiltered(numOfComments); paginationResult.setRecordsTotal(numOfComments); } else { + paginationResult.setData(new ArrayList()); paginationResult.setRecordsFiltered(0); paginationResult.setRecordsTotal(0); } return paginationResult; + } catch (ReviewManagementDAOException e) { + throw new ReviewManagementException("Error occured while getting all reviews for application uuid: " + uuid, + e); } catch (DBConnectionException e) { - throw new CommentManagementException( - "DB Connection error occurs , while getting reviews of application release UUID: " + uuid, e); - } catch (SQLException e) { - throw new CommentManagementException( - "Error occured in the data layer, while getting reviews of application release UUID: " + uuid, e); + throw new ReviewManagementException("Error occured while getting the DB connection.", e); } finally { ConnectionManagerUtil.closeDBConnection(); } } - @Override - public Review getReview(int commentId) throws CommentManagementException { + @Override public Review getReview(int commentId) throws ReviewManagementException { PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); Review review; if (log.isDebugEnabled()) { @@ -232,10 +218,10 @@ public class ReviewManagerImpl implements ReviewManager { ConnectionManagerUtil.openDBConnection(); review = this.reviewDAO.getComment(commentId); } catch (DBConnectionException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "DB Connection error occurs ,Review with review id " + commentId + "cannot get.", e); } catch (SQLException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "SQL Exception occurs,Review with review id " + commentId + "cannot get.", e); } finally { ConnectionManagerUtil.closeDBConnection(); @@ -243,47 +229,38 @@ public class ReviewManagerImpl implements ReviewManager { return review; } - @Override - public void deleteReview(String loggedInUser, int commentId) throws CommentManagementException { + @Override public void deleteReview(String loggedInUser, int commentId) throws ReviewManagementException { Review existingReview; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); try { - if (!loggedInUser.equals(username) && !isAdminUser(username, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)){ - throw new CommentManagementException( + if (!loggedInUser.equals(username) && !isAdminUser(username, tenantId, + CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { + throw new ReviewManagementException( "You don't have permission to delete the review. Please contact the administrator. Review Id: " + commentId); } existingReview = getReview(commentId); if (existingReview == null) { - throw new CommentManagementException( + throw new ReviewManagementException( "Cannot delete a non-existing review for the application with review id" + commentId); } - Runnable task = () -> { - try { - if (calculateRating(0, existingReview.getRating()) <= 0.0) { - log.error("Application release review updating task is failed"); - } - } catch (CommentManagementException e) { - // todo - log.error("error occured"); - } - }; + Runnable task = () -> calculateRating(0, existingReview.getRating()); new Thread(task).start(); ConnectionManagerUtil.beginDBTransaction(); this.reviewDAO.deleteComment(commentId); ConnectionManagerUtil.commitDBTransaction(); } catch (DBConnectionException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "DB Connection error occurs deleting review with review id " + commentId + ".", e); } catch (SQLException e) { - throw new CommentManagementException("SQL error occurs deleting review with review id " + commentId + ".", + throw new ReviewManagementException("SQL error occurs deleting review with review id " + commentId + ".", e); } catch (TransactionManagementException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "Transaction Management Exception occurs deleting review with review id " + commentId + ".", e); } catch (UserStoreException e) { - throw new CommentManagementException( + throw new ReviewManagementException( "User-store exception while checking whether the user " + username + " of tenant " + tenantId + " has the publisher permission"); } finally { @@ -291,15 +268,14 @@ public class ReviewManagerImpl implements ReviewManager { } } - @Override - public Rating getRating(String appReleaseUuuid) throws CommentManagementException{ + @Override public Rating getRating(String appReleaseUuuid) throws ReviewManagementException { //todo int appReleaseId = 0; try { ConnectionManagerUtil.openDBConnection(); Rating rating = this.applicationReleaseDAO.getRating(appReleaseId); if (rating == null) { - throw new CommentManagementException("Couldn't find rating for application release id: " + appReleaseId + throw new ReviewManagementException("Couldn't find rating for application release id: " + appReleaseId + ". Please check the existence of the application relese"); } @@ -316,65 +292,63 @@ public class ReviewManagerImpl implements ReviewManager { return rating; } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( + throw new ReviewManagementException( "Error occured while updated the rating value of the application release id: " + appReleaseId + " can not get.", e); } catch (DBConnectionException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( - "DB Connection error occured while updated the rating value of the application release id: " + appReleaseId - + " can not get.", e); + throw new ReviewManagementException( + "DB Connection error occured while updated the rating value of the application release id: " + + appReleaseId + " can not get.", e); } catch (SQLException e) { - throw new CommentManagementException( - "DB Connection error occured while updated the rating value of the application release id: " + appReleaseId - + " can not get.", e); + throw new ReviewManagementException( + "DB Connection error occured while updated the rating value of the application release id: " + + appReleaseId + " can not get.", e); } finally { ConnectionManagerUtil.closeDBConnection(); } } - private double calculateRating(int newRatingVal, int oldRatingVal) throws CommentManagementException { + private void calculateRating(int newRatingVal, int oldRatingVal) { // todo need to pass app release id int appReleaseId = 0; try { ConnectionManagerUtil.beginDBTransaction(); Rating rating = this.applicationReleaseDAO.getRating(appReleaseId); if (rating == null) { - throw new CommentManagementException( - "Couldn't find rating for application release id: " + appReleaseId); - } - double updatedRating; - int numOfUsers = rating.getNoOfUsers(); - double currentRating = rating.getRatingValue() * numOfUsers; - if (oldRatingVal == -12345) { - updatedRating = (currentRating + newRatingVal) / (numOfUsers + 1); - this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers + 1); - } else if ( newRatingVal == 0){ - updatedRating = (currentRating - newRatingVal) / (numOfUsers - 1); - this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers - 1); - } else{ - double tmpVal; - tmpVal = currentRating - oldRatingVal; - updatedRating = (tmpVal + newRatingVal) / numOfUsers; - this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers ); + log.error("Couldn't find rating for application release id: " + appReleaseId); + } else { + double updatedRating; + int numOfUsers = rating.getNoOfUsers(); + double currentRating = rating.getRatingValue() * numOfUsers; + if (oldRatingVal == -12345) { + updatedRating = (currentRating + newRatingVal) / (numOfUsers + 1); + this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers + 1); + } else if (newRatingVal == 0) { + updatedRating = (currentRating - newRatingVal) / (numOfUsers - 1); + this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers - 1); + } else { + double tmpVal; + tmpVal = currentRating - oldRatingVal; + updatedRating = (tmpVal + newRatingVal) / numOfUsers; + this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers); + } } ConnectionManagerUtil.commitDBTransaction(); - return updatedRating; } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( - "Error occured while updated the rating value of the application release id: " + appReleaseId - + " can not get.", e); + log.error("Error occured while updated the rating value of the application release id: " + appReleaseId + + " can not get."); } catch (TransactionManagementException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( - "Transaction Management Exception occured while updated the rating value of the application release id: " + appReleaseId - + " can not get.", e); + log.error( + "Transaction Management Exception occured while updated the rating value of the application release id: " + + appReleaseId + " can not get."); + } catch (DBConnectionException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new CommentManagementException( - "DB Connection error occured while updated the rating value of the application release id: " + appReleaseId - + " can not get.", e); + log.error("DB Connection error occured while updated the rating value of the application release id: " + + appReleaseId + " can not get."); } finally { ConnectionManagerUtil.closeDBConnection(); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java index 6ee1fc018d8..6252ddada73 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java @@ -32,7 +32,7 @@ import org.wso2.carbon.device.application.mgt.store.api.APIUtil; import org.wso2.carbon.device.application.mgt.store.api.services.ReviewManagementAPI; import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import javax.ws.rs.Path; import javax.ws.rs.Consumes; @@ -59,17 +59,15 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @PathParam("uuid") String uuid, @QueryParam("offset") int offSet, @QueryParam("limit") int limit) { - ReviewManager reviewManager = APIUtil.getCommentsManager(); PaginationRequest request = new PaginationRequest(offSet, limit); try { PaginationResult paginationResult = reviewManager.getAllReviews(request, uuid); return Response.status(Response.Status.OK).entity(paginationResult).build(); - } catch (CommentManagementException e) { - String msg = "Error occurred while retrieving comments."; + } catch (ReviewManagementException e) { + String msg = "Error occurred while retrieving reviews for application UUID: " + uuid; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg) - .build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -80,7 +78,6 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { public Response addReview( @ApiParam Review review, @PathParam("uuid") String uuid) { - ReviewManager reviewManager = APIUtil.getCommentsManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager(); Application application; @@ -96,7 +93,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { log.error(msg); return Response.status(Response.Status.BAD_REQUEST).build(); } - } catch (CommentManagementException e) { + } catch (ReviewManagementException e) { String msg = "Error occurred while creating the review"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) @@ -131,7 +128,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("").build(); } - } catch (CommentManagementException e) { + } catch (ReviewManagementException e) { String msg = "Error occurred while retrieving comments."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) @@ -153,7 +150,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { } else { reviewManager.deleteReview(username, commentId); } - } catch (CommentManagementException e) { + } catch (ReviewManagementException e) { String msg = "Error occurred while deleting the comment."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg) @@ -172,7 +169,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { Rating rating; try { rating = reviewManager.getRating(uuid); - } catch (CommentManagementException e) { + } catch (ReviewManagementException e) { log.error("Review Management Exception occurs", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java index c59db2a67db..f3412cab3c2 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java @@ -34,7 +34,7 @@ import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.store.api.APIUtil; import org.wso2.carbon.device.application.mgt.store.api.services.impl.ReviewManagementAPIImpl; @@ -63,7 +63,7 @@ import static org.mockito.MockitoAnnotations.initMocks; } @BeforeClass - void init() throws CommentManagementException { + void init() throws ReviewManagementException { log.info("Initializing ReviewManagementAPI tests"); initMocks(this); @@ -84,7 +84,7 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testGetAllCommentsInternalError() throws Exception { PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); - Mockito.doThrow(new CommentManagementException()).when(this.reviewManager) + Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager) .getAllReviews(Mockito.any(), Mockito.anyString()); Response response = this.commentManagementAPI.getAllReviews("a", 1, 4); Assert.assertNotNull(response, "The response object is null."); @@ -129,7 +129,7 @@ import static org.mockito.MockitoAnnotations.initMocks; Review review = CommentMgtTestHelper.getDummyComment("a", "a"); PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Mockito.when(this.commentManagementAPI.addReview(Mockito.any(), Mockito.anyString())) - .thenThrow(new CommentManagementException()); + .thenThrow(new ReviewManagementException()); Response response = this.commentManagementAPI.addReview(review, null); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), @@ -170,7 +170,7 @@ import static org.mockito.MockitoAnnotations.initMocks; public void testUpdateCommentInternalServerError() throws Exception { Review review = CommentMgtTestHelper.getDummyComment("a", "a"); PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); - Mockito.doThrow(new CommentManagementException()).when(this.reviewManager).updateReview(review, 9, true); + Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager).updateReview(review, 9, true); Response response = this.commentManagementAPI.updateComment(review, 9); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), @@ -189,7 +189,7 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testDeleteCommentInternalError() throws Exception { PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); - Mockito.when(this.commentManagementAPI.deleteComment(1,"")).thenThrow(new CommentManagementException()); + Mockito.when(this.commentManagementAPI.deleteComment(1,"")).thenThrow(new ReviewManagementException()); Response response = this.commentManagementAPI.deleteComment(1,""); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), @@ -219,7 +219,7 @@ import static org.mockito.MockitoAnnotations.initMocks; public void testGetStarsCommentError() throws Exception { PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString())) - .thenThrow(new CommentManagementException()); + .thenThrow(new ReviewManagementException()); Response response = this.commentManagementAPI.getRating("a"); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), From 7630cb0fb1702929d33c7e55dec10818f0a7c071 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Thu, 20 Sep 2018 11:52:25 +0530 Subject: [PATCH 08/10] Fix the osgi issues --- components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml | 2 -- .../device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml | 1 - .../email-sender/org.wso2.carbon.email.sender.core/pom.xml | 1 - 3 files changed, 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 5b7ce8b77c1..dcf9411e2b3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -78,12 +78,10 @@ org.wso2.carbon.device.mgt.core.internal org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.apache.axiom.*; version="${axiom.osgi.version.range}", org.osgi.framework, org.osgi.service.component, org.apache.commons.logging, javax.naming, - javax.xml.*, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, javax.servlet.*, org.xml.sax, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 2d2c40b3b48..5c4ffa80abd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -154,7 +154,6 @@ javax.xml.namespace;resolution:=optional, org.wso2.carbon.context, org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.common.license.mgt, org.wso2.carbon.registry.api, org.wso2.carbon.registry.core, org.wso2.carbon.registry.core.exceptions, diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml b/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml index 6b0cf581e56..7532c783ac3 100644 --- a/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml +++ b/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml @@ -56,7 +56,6 @@ org.osgi.framework, org.osgi.service.component, org.apache.commons.logging, - javax.xml.*, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.wso2.carbon.context, org.wso2.carbon.utils.*, From 1ea47c83612ce22bf9f3d4270b0dff52f63ebf6e Mon Sep 17 00:00:00 2001 From: lasanthaDLPDS Date: Thu, 20 Sep 2018 11:58:05 +0530 Subject: [PATCH 09/10] Improve review mnagement WIP --- .../mgt/core/dao/ApplicationReleaseDAO.java | 1 + .../GenericApplicationDAOImpl.java | 9 +-- .../GenericApplicationReleaseDAOImpl.java | 8 +++ .../application/mgt/store/api/APIUtil.java | 2 +- .../api/services/ReviewManagementAPI.java | 17 ++--- .../impl/ReviewManagementAPIImpl.java | 63 +++++++++---------- .../api/services/ReviewManagementAPITest.java | 8 +-- 7 files changed, 55 insertions(+), 53 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java index e3bcfecad2e..ec573b8d239 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.application.mgt.core.dao; +import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 12c80c4c525..586d6d92f02 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -380,7 +380,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - boolean isAppExist = false; try { conn = this.getDBConnection(); String sql = @@ -396,13 +395,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic if (log.isDebugEnabled()) { log.debug("Successfully retrieved basic details of the application with the application ID " + appId); } - - if (rs.next()) { - isAppExist = true; - } - - return isAppExist; - + return rs.next(); } catch (SQLException e) { throw new ApplicationManagementDAOException( "Error occurred while getting application details with app ID " + appId + " While executing query ", diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java index c86e7f86849..105d72fc252 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java @@ -19,12 +19,17 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application.release; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONException; +import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.Util; import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import java.sql.Connection; @@ -40,6 +45,9 @@ import java.util.List; */ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO { + private static final Log log = LogFactory.getLog(GenericApplicationReleaseDAOImpl.class); + + /** * To insert the Application Release Details. * diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java index b82802b85d1..1811c066d05 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/APIUtil.java @@ -92,7 +92,7 @@ public class APIUtil { * @return ReviewManager instance in the current osgi context. */ - public static ReviewManager getCommentsManager() { + public static ReviewManager getReviewManager() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); ReviewManager reviewManager = (ReviewManager) ctx.getOSGiService(ReviewManager.class, null); if (reviewManager == null) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java index a86d0d79011..c8cef67b321 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPI.java @@ -200,11 +200,10 @@ public interface ReviewManagementAPI { name="uuid", value="uuid of the release version of the application", required=true) - @PathParam("uuid") - String uuid); + @PathParam("uuid") String uuid); @PUT - @Path("/{CommentId}") + @Path("/{uuid}/{reviewId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( @@ -238,18 +237,22 @@ public interface ReviewManagementAPI { message = "Internal Server Error. \n Error occurred while updating the new review.", response = ErrorResponse.class) }) - Response updateComment( + Response updateReview( @ApiParam( name = "review", value = "The review that need to be updated.", required = true) @Valid Review review, @ApiParam( - name="commentId", + name="uuid", + value = "uuid of the application release", + required = true) + @PathParam("uuid") String uuid, + @ApiParam( + name="reviewId", value = "review id of the updating review.", required = true) - @QueryParam("commentId") - int commentId); + @PathParam("reviewId") int reviewId); @DELETE @Path("/{commentId}") diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java index 6252ddada73..e188d4861e7 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java @@ -22,7 +22,6 @@ import io.swagger.annotations.ApiParam; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.Application; -import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.PaginationResult; import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Review; @@ -59,7 +58,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @PathParam("uuid") String uuid, @QueryParam("offset") int offSet, @QueryParam("limit") int limit) { - ReviewManager reviewManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getReviewManager(); PaginationRequest request = new PaginationRequest(offSet, limit); try { PaginationResult paginationResult = reviewManager.getAllReviews(request, uuid); @@ -78,29 +77,34 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { public Response addReview( @ApiParam Review review, @PathParam("uuid") String uuid) { - ReviewManager reviewManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getReviewManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager(); Application application; - ApplicationRelease applicationRelease; try { application = applicationManager.getApplicationByRelease(uuid); - applicationRelease = applicationManager.getAppReleaseIfExists(application.getId(), uuid); - boolean abc = reviewManager.addReview(review, application.getId(), applicationRelease.getId()); - if (abc) { + if (application.getApplicationReleases().isEmpty()){ + String msg = "Couldn't Found an one application release for the UUID: " + uuid; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + if (application.getApplicationReleases().size()>1){ + String msg = "Found more than one application release for the UUID: " + uuid; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + boolean isReviewCreated = reviewManager + .addReview(review, application.getId(), application.getApplicationReleases().get(0).getId()); + if (isReviewCreated) { return Response.status(Response.Status.CREATED).entity(review).build(); } else { - String msg = "Given review is not valid "; + String msg = "Given review is not valid. Please check the review payload."; log.error(msg); - return Response.status(Response.Status.BAD_REQUEST).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } catch (ReviewManagementException e) { String msg = "Error occurred while creating the review"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(msg).build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (ApplicationManagementException e) { -// todo - log.error(""); + log.error("Error occured while getting the application for application UUID: " + uuid); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("").build(); } @@ -109,41 +113,35 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @Override @PUT @Consumes("application/json") - @Path("/review/{commentId}") - public Response updateComment( + @Path("/{uuid}/{reviewId}") + public Response updateReview( @ApiParam Review review, - @PathParam("commentId") int commentId) { - - ReviewManager reviewManager = APIUtil.getCommentsManager(); + @PathParam("uuid") String uuid, + @PathParam("reviewId") int reviewId) { + ReviewManager reviewManager = APIUtil.getReviewManager(); try { - if (commentId == 0) { - return Response.status(Response.Status.NOT_FOUND) - .entity("Review not found").build(); - } else if (review == null) { - String msg = "Given review is not valid "; - log.error(msg); - return Response.status(Response.Status.BAD_REQUEST).build(); - } else if (reviewManager.updateReview(review, commentId, true)) { + if (reviewManager.updateReview(review, reviewId, true)) { return Response.status(Response.Status.OK).entity(review).build(); } else { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("").build(); + String msg = "Review updating failed. Please contact the administrator"; + log.error(msg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } catch (ReviewManagementException e) { String msg = "Error occurred while retrieving comments."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(msg).build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @Override @DELETE - @Path("/comment/{commentId}") + @Path("/{commentId}") public Response deleteComment( @PathParam("commentId") int commentId, @QueryParam("username") String username) { - ReviewManager reviewManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getReviewManager(); try { if (commentId == 0) { return Response.status(Response.Status.NOT_FOUND).entity("Review not found").build(); @@ -164,8 +162,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI { @Path("/{uuid}/rating") public Response getRating( @PathParam("uuid") String uuid) { - - ReviewManager reviewManager = APIUtil.getCommentsManager(); + ReviewManager reviewManager = APIUtil.getReviewManager(); Rating rating; try { rating = reviewManager.getRating(uuid); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java index f3412cab3c2..654abf6bdfc 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/test/java/org/wso2/carbon/device/application/mgt/store/api/services/ReviewManagementAPITest.java @@ -141,7 +141,7 @@ import static org.mockito.MockitoAnnotations.initMocks; public void testUpdateComment() throws Exception { Review review = CommentMgtTestHelper.getDummyComment("a", "a"); PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); - Response response = this.commentManagementAPI.updateComment(review, 1); + Response response = this.commentManagementAPI.updateReview(review, 1); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The response status should be 200."); @@ -150,7 +150,7 @@ import static org.mockito.MockitoAnnotations.initMocks; @Test public void testUpdateNullComment() throws Exception { PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); - Response response = this.commentManagementAPI.updateComment(null, 1); + Response response = this.commentManagementAPI.updateReview(null, 1); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), "The response status should be 400."); @@ -160,7 +160,7 @@ import static org.mockito.MockitoAnnotations.initMocks; public void testUpdateCommentWhenNullCommentId() throws Exception { Review review = CommentMgtTestHelper.getDummyComment("a", "a"); PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); - Response response = this.commentManagementAPI.updateComment(review, 0); + Response response = this.commentManagementAPI.updateReview(review, 0); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), "The response status should be 404."); @@ -171,7 +171,7 @@ import static org.mockito.MockitoAnnotations.initMocks; Review review = CommentMgtTestHelper.getDummyComment("a", "a"); PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager).updateReview(review, 9, true); - Response response = this.commentManagementAPI.updateComment(review, 9); + Response response = this.commentManagementAPI.updateReview(review, 9); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "The response status should be 500."); From c23770db3387e80b767dce8861068ce11b385d65 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Thu, 20 Sep 2018 15:07:40 +0530 Subject: [PATCH 10/10] Fix the osgi and validate issues --- .../device/application/mgt/common/Filter.java | 29 +++++ .../publisher/api/ValidationInterceptor.java | 120 ++++++++++++++++++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 37 ++++-- .../src/main/webapp/WEB-INF/web.xml | 6 + 4 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/ValidationInterceptor.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Filter.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Filter.java index 16c4e12f7c4..144abba320f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Filter.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Filter.java @@ -18,21 +18,50 @@ */ package org.wso2.carbon.device.application.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + /** * Filter represents a criteria that can be used for searching applications. */ + +@ApiModel(value = "Filter", description = "This is related to the application filtering.") public class Filter { + @ApiModelProperty( + name = "appName", + value = "Name of the application", + required = false) private String appName; + @ApiModelProperty( + name = "appType", + value = "Type of the application", + required = false) private String appType; + @ApiModelProperty( + name = "isFullMatch", + value = "Checking the application name matches fully with given name", + required = false) private boolean isFullMatch; + @ApiModelProperty( + name = "limit", + value = "Limit of the applications", + required = false) private int limit; + @ApiModelProperty( + name = "offset", + value = "Started from", + required = false) private int offset; + @ApiModelProperty( + name = "sortBy", + value = "Ascending or descending order", + required = false) private String sortBy; public int getLimit() { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/ValidationInterceptor.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/ValidationInterceptor.java new file mode 100644 index 00000000000..a7c436bfe38 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/ValidationInterceptor.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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. + */ + + +package org.wso2.carbon.device.application.mgt.publisher.api; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.jaxrs.lifecycle.ResourceProvider; +import org.apache.cxf.jaxrs.model.ClassResourceInfo; +import org.apache.cxf.jaxrs.model.OperationResourceInfo; +import org.apache.cxf.message.Message; +import org.apache.cxf.message.MessageContentsList; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; + +import javax.validation.*; +import javax.validation.executable.ExecutableValidator; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Set; + +public class ValidationInterceptor extends AbstractPhaseInterceptor { + private Log log = LogFactory.getLog(getClass()); + private Validator validator = null; //validator interface is thread-safe + + public ValidationInterceptor() { + super(Phase.PRE_INVOKE); + ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory(); + validator = defaultFactory.getValidator(); + if (validator == null) { + log.warn("Bean Validation provider could not be found, no validation will be performed"); + } else { + log.debug("Validation In-Interceptor initialized successfully"); + } + } + + @Override + public void handleMessage(Message message) throws Fault { + final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class); + if (operationResource == null) { + log.info("OperationResourceInfo is not available, skipping validation"); + return; + } + + final ClassResourceInfo classResource = operationResource.getClassResourceInfo(); + if (classResource == null) { + log.info("ClassResourceInfo is not available, skipping validation"); + return; + } + + final ResourceProvider resourceProvider = classResource.getResourceProvider(); + if (resourceProvider == null) { + log.info("ResourceProvider is not available, skipping validation"); + return; + } + + final List arguments = MessageContentsList.getContentsList(message); + final Method method = operationResource.getAnnotatedMethod(); + final Object instance = resourceProvider.getInstance(message); + if (method != null && arguments != null) { + //validate the parameters(arguments) over the invoked method + validate(method, arguments.toArray(), instance); + + //validate the fields of each argument + for (Object arg : arguments) { + if (arg != null) + validate(arg); + } + } + + } + + public void validate(final Method method, final Object[] arguments, final T instance) { + if (validator == null) { + log.warn("Bean Validation provider could not be found, no validation will be performed"); + return; + } + + ExecutableValidator methodValidator = validator.forExecutables(); + Set> violations = methodValidator.validateParameters(instance, + method, arguments); + + if (!violations.isEmpty()) { + throw new ConstraintViolationException(violations); + } + } + + public void validate(final T object) { + if (validator == null) { + log.warn("Bean Validation provider could be found, no validation will be performed"); + return; + } + + Set> violations = validator.validate(object); + + if (!violations.isEmpty()) { + throw new ConstraintViolationException(violations); + } + } + + public void handleFault(org.apache.cxf.message.Message messageParam) { + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 8e0452c6b37..92d7f203303 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -18,29 +18,50 @@ --> + xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd + http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"> + - - + + + + + + + + + + + + + + + + + + + - - + + + + + + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/web.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/web.xml index 7574e19e4c0..be302ea7ad9 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/web.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/WEB-INF/web.xml @@ -27,6 +27,12 @@ org.apache.cxf.transport.servlet.CXFServlet + + + swagger.security.filter + ApiAuthorizationFilterImpl + + 1 CXFServlet