Improve review management

merge-requests/9/head
lasanthaDLPDS 6 years ago
parent 56048907e6
commit 3e16ec96b9

@ -0,0 +1,45 @@
/*
* 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.exception;
public class ReviewDoesNotExistException extends Exception {
private String message;
public ReviewDoesNotExistException(String message, Throwable throwable) {
super(message, throwable);
setMessage(message);
}
public ReviewDoesNotExistException(String message) {
super(message);
setMessage(message);
}
public ReviewDoesNotExistException() {
}
@Override public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

@ -22,25 +22,29 @@ 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.Review;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest; 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.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewDoesNotExistException;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
/** /**
* ReviewManager is responsible for handling all the add/update/delete/get operations related with * ReviewManager is responsible for handling all the add/update/delete/get operations related with
*/ */
public interface ReviewManager { public interface ReviewManager {
/** /**
* To add a review to a application * To add a review to an application release
* *
* @param review review of the application. * @param review review of the application.
* @param uuid uuid of the application release. * @param uuid uuid of the application release.
* @return {@link Review} Review added * @return {@link Review} Review added
* @throws ReviewManagementException Exceptions of the review management. * @throws ReviewManagementException Exceptions of the review management.
*/ */
boolean addReview(Review review, String uuid) throws ReviewManagementException; boolean addReview(Review review, String uuid) throws ReviewManagementException, RequestValidatingException;
/** /**
* Get all comments to pagination * Get all review with pagination
* *
* @param request Pagination request {@link PaginationRequest} * @param request Pagination request {@link PaginationRequest}
* @param uuid uuid of the application release * @param uuid uuid of the application release
@ -49,15 +53,6 @@ public interface ReviewManager {
*/ */
PaginationResult getAllReviews(PaginationRequest request, String uuid) throws ReviewManagementException; 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 ReviewManagementException Exceptions of the comment management.
*/
Review getReview(int commentId) throws ReviewManagementException;
/** /**
* To delete review using review id. * To delete review using review id.
* *
@ -66,7 +61,8 @@ public interface ReviewManager {
* @return If review is successfully deleted return true, otherwise returns false * @return If review is successfully deleted return true, otherwise returns false
* @throws ReviewManagementException Exceptions of the comment management * @throws ReviewManagementException Exceptions of the comment management
*/ */
boolean deleteReview(String uuid, int commentId) throws ReviewManagementException; boolean deleteReview(String uuid, int commentId)
throws ReviewManagementException, ReviewDoesNotExistException;
/** /**
* To update a review. * To update a review.
@ -74,12 +70,13 @@ public interface ReviewManager {
* @param review review of the application. * @param review review of the application.
* @param reviewId id of the review * @param reviewId id of the review
* @param uuid UUID of the application release * @param uuid UUID of the application release
* @param checkExistence Pass true if it is required to check the existence of the review, otherwise pass false * @param existingReview Pass existing review when same user adding a review for same application release,
* otherwise pass null
* @return {@link Review}updated review * @return {@link Review}updated review
* @throws ReviewManagementException Exceptions of the review management * @throws ReviewManagementException Exceptions of the review management
*/ */
boolean updateReview(Review review, int reviewId, String uuid, boolean checkExistence) boolean updateReview(Review review, int reviewId, String uuid, Review existingReview)
throws ReviewManagementException; throws ReviewManagementException, RequestValidatingException;
/** /**
* To get the overall rating for a application release * To get the overall rating for a application release

@ -81,19 +81,21 @@ public interface ApplicationReleaseDAO {
/** /**
* To update an Application release. * To update an Application release.
* @param id id of the ApplicationRelease that need to be updated. * @param uuid UUID of the ApplicationRelease that need to be updated.
* @param rating given stars for the application. * @param rating given stars for the application.
* @param ratedUsers number of users who has rated for the application release. * @param ratedUsers number of users who has rated for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception * @throws ApplicationManagementDAOException Application Management DAO Exception
*/ */
int updateRatingValue(int id, double rating, int ratedUsers) throws ApplicationManagementDAOException; void updateRatingValue(String uuid, double rating, int ratedUsers) throws ApplicationManagementDAOException;
/** /**
* To retrieve rating of an application release. * To retrieve rating of an application release.
*
* @param uuid UUID of the application Release. * @param uuid UUID of the application Release.
* @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
Rating getRating(String uuid) throws ApplicationManagementDAOException; Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException;
/** /**

@ -45,7 +45,7 @@ import java.util.List;
boolean addReview(Review review, String uuid, int tenantId) throws ReviewManagementDAOException; boolean addReview(Review review, String uuid, int tenantId) throws ReviewManagementDAOException;
/** /**
* To verify whether review is exists or not. * To verify whether user has already commented for the application release or not.
* *
* @param uuid UUID of the application release. * @param uuid UUID of the application release.
* @param username username of the logged in user. * @param username username of the logged in user.
@ -58,33 +58,33 @@ import java.util.List;
/** /**
* To update already added comment. * To update already added comment.
* *
* @return {@link Review}Updated comment * @param review Updating review
* @throws ReviewManagementException Exceptions of the comment management. * @param reviewId id of the updating review
* @throws DBConnectionException db connection exception * @param username review owner
* @throws SQLException sql exception * @param tenantId tenant id
* @return row count if updating is succeed otherwise 0
* @throws ReviewManagementDAOException Exceptions of the review management.
*/ */
boolean updateReview(Review review, int reviewId, int tenantId) int updateReview(Review review, int reviewId, String username, int tenantId)
throws ReviewManagementException, DBConnectionException, SQLException; throws ReviewManagementDAOException;
/** /**
* To get the comment with id. * To get the comment with id.
* *
* @param commentId id of the comment * @param reviewId id of the review
* @return {@link Review}Review * @return {@link Review}Review
* @throws ReviewManagementException Exceptions of the comment management. * @throws ReviewManagementDAOException Exceptions of the review management DAO.
* @throws DBConnectionException db connection exception
* @throws SQLException sql exception
*/ */
Review getReview(int commentId) throws ReviewManagementException, SQLException, DBConnectionException; Review getReview(int reviewId) throws ReviewManagementDAOException;
/** /**
* To get all the comments * To get all reviews
* *
* @param uuid uuid of the application * @param uuid uuid of the application
* @param request {@link PaginationRequest}pagination request with offSet and limit * @param request {@link PaginationRequest}pagination request with offSet and limit
* @param tenantId Tenant id * @param tenantId Tenant id
* @return {@link List}List of all the comments in an application * @return {@link List}List of all reviews for the application release
* @throws ReviewManagementDAOException Review management DAO exception * @throws ReviewManagementDAOException Review management DAO exception
**/ **/
List<Review> getAllReviews(String uuid, PaginationRequest request, int tenantId) List<Review> getAllReviews(String uuid, PaginationRequest request, int tenantId)
@ -92,11 +92,12 @@ import java.util.List;
/** /**
* To get list of comments using release id and application id. * To get list of comments using release id and application id.
* * @param uuid UUID of the application release
* @param tenantId tenant id
* @return {@link List}List of comments * @return {@link List}List of comments
* @throws ReviewManagementException Exceptions of the comment management. * @throws ReviewManagementDAOException Exceptions of the review management DAO.
*/ */
List<Integer> getAllRatingValues(String uuid)throws SQLException, DBConnectionException; List<Integer> getAllRatingValues(String uuid, int tenantId) throws ReviewManagementDAOException;
/** /**
* To get count of comments by application details. * To get count of comments by application details.
@ -122,15 +123,6 @@ import java.util.List;
*/ */
int deleteReview(String username, int reviewId) throws ReviewManagementDAOException; int deleteReview(String username, int reviewId) throws ReviewManagementDAOException;
/**
* To delete review using review id, in this case, it doesn't check whether user is review owner or not.
*
* @param reviewId id of the review
* @return If review is successfully deleted return 1, otherwise returns 0.
* @throws ReviewManagementDAOException Review management DAO exception.
*/
int deleteReviewByAdmin(int reviewId) throws ReviewManagementDAOException;
/** /**
* To delete comments using application details. * To delete comments using application details.
* *
@ -142,12 +134,11 @@ import java.util.List;
void deleteReviews(String appType, String appName, String version) throws ReviewManagementException; void deleteReviews(String appType, String appName, String version) throws ReviewManagementException;
/** /**
* To get comment count for pagination * To get review count for a specific application release
* *
* @param request pagination request
* @param uuid uuid of the application release * @param uuid uuid of the application release
* @return Review count * @return Review count
* @throws ReviewManagementException * @throws ReviewManagementDAOException Review management DAO exception
*/ */
int getReviewCount(PaginationRequest request, String uuid) throws ReviewManagementException; int getReviewCount(String uuid) throws ReviewManagementDAOException;
} }

@ -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.common.exception.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; 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.*;
import org.wso2.carbon.device.application.mgt.core.dao.impl.Comment.ReviewDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.Review.ReviewDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; 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.release.GenericApplicationReleaseDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.OracleApplicationDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.application.OracleApplicationDAOImpl;

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.application.mgt.core.dao.impl.Comment; package org.wso2.carbon.device.application.mgt.core.dao.impl.Review;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -28,7 +28,6 @@ import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionExcep
import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO; 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.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; 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 org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException;
import java.sql.SQLException; import java.sql.SQLException;
@ -48,14 +47,13 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
private String sql; private String sql;
@Override @Override
public boolean addReview(Review review, String uuid, int tenantId) public boolean addReview(Review review, String uuid, int tenantId) throws ReviewManagementDAOException {
throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add review for application release. Application UUID: " + uuid); log.debug("Request received in DAO Layer to add review for application release. Application UUID: " + uuid);
} }
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs = null; ResultSet rs = null;
sql = "INSERT INTO AP_APP_Review (TENANT_ID, COMMENT, PARENT_ID, USERNAME, AP_APP_RELEASE_ID, AP_APP_ID) " 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= ?)," + "VALUES (?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?),"
+ "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));"; + "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));";
try { try {
@ -102,7 +100,6 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
statement.setString(1, uuid); statement.setString(1, uuid);
statement.setString(2, username); statement.setString(2, username);
statement.setInt(3, tenantId); statement.setInt(3, tenantId);
rs = statement.executeQuery(); rs = statement.executeQuery();
if (rs.next()){ if (rs.next()){
review = new Review(); review = new Review();
@ -128,7 +125,8 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public boolean updateReview(Review review, int reviewId, int tenantId) throws ReviewManagementException, DBConnectionException, SQLException { public int updateReview(Review review, int reviewId, String username, int tenantId)
throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to update the comment with ID (" + reviewId + ")"); log.debug("Request received in DAO Layer to update the comment with ID (" + reviewId + ")");
@ -136,55 +134,59 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs = null; ResultSet rs = null;
sql = "UPDATE AP_APP_COMMENT SET COMMENT_TEXT=?, MODEFIED_BY=? WHERE ID=?;"; sql = "UPDATE AP_APP_REVIEW SET COMMENT=?, RATING=? WHERE ID=? AND USERNAME=? AND TENANT_ID=?;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
// statement.setString(1, updatedComment); statement.setString(1, review.getComment());
// statement.setString(2, modifiedBy); statement.setInt(2, review.getRating());
statement.setInt(3, reviewId); statement.setInt(3, reviewId);
statement.executeUpdate(); statement.setString(4, username);
rs = statement.executeQuery(); statement.setInt(5, tenantId);
return statement.executeUpdate();
} catch (SQLException e) {
throw new ReviewManagementDAOException("Error occurred while executing review updating query");
} catch (DBConnectionException e) {
throw new ReviewManagementDAOException("Error occured while getting the db connection to update review");
} finally { } finally {
Util.cleanupResources(statement, rs); Util.cleanupResources(statement, rs);
} }
// todo
return false;
} }
@Override @Override
public Review getReview(int commentId) throws ReviewManagementException { public Review getReview(int reviewId) throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting review with the review id(" + commentId + ") from the database"); log.debug("Getting review with the review id(" + reviewId + ") from the database");
} }
Connection conn; Connection conn;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs; ResultSet rs = null;
Review review = new Review(); Review review = new Review();
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE ID=?;"; sql = "SELECT ID, COMMENT, CREATED_AT, MODIFIED_AT, RATING, USERNAME FROM AP_APP_REVIEWE WHERE ID=?;";
statement = conn.prepareStatement(sql); statement = conn.prepareStatement(sql);
statement.setInt(1, commentId); statement.setInt(1, reviewId);
rs = statement.executeQuery(); rs = statement.executeQuery();
if (rs.next()) { if (rs.next()) {
review.setId(rs.getInt("ID")); review.setId(rs.getInt("ID"));
// review.setTenantId(rs.getInt("TENANT_ID")); review.setComment(rs.getString("COMMENT"));
review.setComment(rs.getString("COMMENT_TEXT"));
review.setCreatedAt(rs.getTimestamp("CREATED_AT")); review.setCreatedAt(rs.getTimestamp("CREATED_AT"));
review.setUsername(rs.getString("CREATED_BY")); review.setUsername(rs.getString("CREATED_BY"));
review.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); review.setModifiedAt(rs.getTimestamp("MODIFIED_AT"));
Util.cleanupResources(statement, rs); review.setRating(rs.getInt("RATING"));
review.setUsername(rs.getString("USERNAME"));
return review; return review;
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new ReviewManagementException( throw new ReviewManagementDAOException(
"SQL Error occurred while retrieving information of the review " + commentId, e); "SQL Error occurred while retrieving information of the review " + reviewId, e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
log.error("DB Connection Exception occurred while retrieving information of the review " + commentId, e); throw new ReviewManagementDAOException(
"DB Connection Exception occurred while retrieving information of the review " + reviewId, e);
} finally { } finally {
Util.cleanupResources(statement, null); Util.cleanupResources(statement, rs);
} }
return review; return review;
} }
@ -202,11 +204,11 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
List<Review> reviews = new ArrayList<>(); List<Review> reviews = new ArrayList<>();
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS COMMENT_TEXT, " sql = "SELECT AP_APP_REVIEW.ID AS ID, AP_APP_REVIEW.COMMENT AS COMMENT, "
+ "AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS MODIFIED_BY, " + "AP_APP_REVIEW.CREATED_BY AS CREATED_BY, AP_APP_REVIEW.MODIFIED_BY AS MODIFIED_BY, "
+ "AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE " + "AP_APP_REVIEW.PARENT_ID AS PARENT_ID FROM AP_APP_REVIEW, AP_APP_RELEASE WHERE "
+ "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND " + "AP_APP_REVIEW.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 " + "AP_APP_REVIEW.TENANT_ID = ? AND AP_APP_REVIEW.TENANT_ID = AP_APP_RELEASE.TENANT_ID "
+ "LIMIT ? OFFSET ?;"; + "LIMIT ? OFFSET ?;";
statement = conn.prepareStatement(sql); statement = conn.prepareStatement(sql);
statement.setString(1, uuid); statement.setString(1, uuid);
@ -233,7 +235,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public List<Integer> getAllRatingValues(String uuid)throws SQLException, DBConnectionException { public List<Integer> getAllRatingValues(String uuid, int tenantId) throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting comment of the application release (" + uuid + ") from the database"); log.debug("Getting comment of the application release (" + uuid + ") from the database");
@ -244,18 +246,24 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
List<Integer> reviews = new ArrayList<>(); List<Integer> reviews = new ArrayList<>();
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
// todo sql = "SELECT AP_APP_COMMENT.RATING AS RATING FROM AP_APP_REVIEW, AP_APP_RELEASE WHERE "
sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS " + "AP_APP_REVIEW.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND "
+ "COMMENT_TEXT, AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS " + "AP_APP_COMMENT.TENANT_ID = AP_APP_RELEASE.TENANT_ID AND AP_APP_COMMENT.TENANT_ID = ?;";
+ "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 = conn.prepareStatement(sql);
statement.setString(1, uuid); statement.setString(1, uuid);
statement.setInt(2, tenantId);
rs = statement.executeQuery(); rs = statement.executeQuery();
while (rs.next()) { while (rs.next()) {
reviews.add(rs.getInt("RATING")); reviews.add(rs.getInt("RATING"));
} }
} catch (SQLException e) {
throw new ReviewManagementDAOException(
"Error occured while getting all rating values for the application release. App release UUID: "
+ uuid, e);
} catch (DBConnectionException e) {
throw new ReviewManagementDAOException(
"Error occured while getting DB connection to retrieve all rating values for the application release. App release UUID: "
+ uuid, e);
} finally { } finally {
Util.cleanupResources(statement, rs); Util.cleanupResources(statement, rs);
} }
@ -263,7 +271,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public int getReviewCount(PaginationRequest request, String uuid) throws ReviewManagementException { public int getReviewCount(String uuid) throws ReviewManagementDAOException {
int commentCount = 0; int commentCount = 0;
Connection conn; Connection conn;
@ -276,20 +284,20 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
isUuidProvided = true; isUuidProvided = true;
} }
if (isUuidProvided) { if (isUuidProvided) {
sql = "SELECT COUNT(AP_APP_COMMENT.ID) FROM AP_APP_COMMENT,AP_APP_RELEASE " sql = "SELECT COUNT(AP_APP_REVIEW.ID) AS REVIEW_COUNT FROM AP_APP_REVIEW,AP_APP_RELEASE "
+ "WHERE AP_APP_COMMENT.AP_APP_RELEASE_ID= AP_APP_RELEASE.ID AND " + "WHERE AP_APP_REVIEW.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=?;"; + "AP_APP_REVIEW.AP_APP_ID= AP_APP_RELEASE.AP_APP_ID AND AP_APP_RELEASE.UUID=?;";
statement = conn.prepareStatement(sql); statement = conn.prepareStatement(sql);
statement.setString(1, uuid); statement.setString(1, uuid);
rs = statement.executeQuery(); rs = statement.executeQuery();
if (rs.next()) { if (rs.next()) {
commentCount = rs.getInt("COMMENTS_COUNT"); commentCount = rs.getInt("REVIEW_COUNT");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new ReviewManagementException("SQL Error occurred while retrieving count of comments", e); throw new ReviewManagementDAOException("SQL Error occurred while retrieving review counts", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
log.error("DB Connection Exception occurred while retrieving count of comments", e); throw new ReviewManagementDAOException("DB Connection Exception occurred while retrieving review counts", e);
} finally { } finally {
Util.cleanupResources(statement, rs); Util.cleanupResources(statement, rs);
} }
@ -302,8 +310,10 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
Connection conn; Connection conn;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs = null;
int commentCount = 0; int commentCount = 0;
try { try {
//todo need to reconstruct the query
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT COUNT(ID) AS COMMENT_COUNT FROM AP_APP_COMMENT C, " 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 RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=? )R,"
@ -313,12 +323,12 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
statement.setString(1, version); statement.setString(1, version);
statement.setString(2, appName); statement.setString(2, appName);
statement.setString(3, appType); statement.setString(3, appType);
ResultSet rs = statement.executeQuery(); rs = statement.executeQuery();
if (rs.next()) { if (rs.next()) {
commentCount = rs.getInt("COMMENT_COUNT"); commentCount = rs.getInt("COMMENT_COUNT");
} }
} finally { } finally {
Util.cleanupResources(statement, null); Util.cleanupResources(statement, rs);
} }
return commentCount; return commentCount;
} }
@ -345,33 +355,13 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public int deleteReviewByAdmin(int reviewId) throws ReviewManagementDAOException { public void deleteReviews(String appType, String appName, String version) throws ReviewManagementException {
Connection conn;
PreparedStatement statement = null;
try {
conn = this.getDBConnection();
sql = "DELETE FROM AP_APP_REVIEW WHERE ID=?;";
statement = conn.prepareStatement(sql);
statement.setInt(1, reviewId);
return statement.executeUpdate();
} catch (SQLException e) {
throw new ReviewManagementDAOException("Error occured while accessing the Database", e);
} catch (DBConnectionException e) {
throw new ReviewManagementDAOException("Error occured while getting the database connection", e);
} finally {
Util.cleanupResources(statement, null);
}
}
@Override
public void deleteReviews(String appType, String appName, String version)
throws ReviewManagementException {
Connection conn; Connection conn;
PreparedStatement statement = null; PreparedStatement statement = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
//todo need to reconstruct the query,
sql = "DELETE FROM AP_APP_COMMENT WHERE " sql = "DELETE FROM AP_APP_COMMENT WHERE "
+ "(SELECT AP_APP_RELEASE_ID FROM AP_APP_RELEASE WHERE VERSION=? AND " + "(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 "

@ -279,28 +279,28 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
/** /**
* To Update starts of an application release. * To Update starts of an application release.
* *
* @param id Id of the application Release. * @param uuid UUID of the application Release.
* @param rating given stars for the application release. * @param rating given stars for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override
public int updateRatingValue(int id, double rating, int ratedUsers) throws ApplicationManagementDAOException { public void updateRatingValue(String uuid, double rating, int ratedUsers) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "UPDATE AP_APP_RELEASE SET RATING = ? AND RATED_USERS = ? WHERE ID = ?;"; String sql = "UPDATE AP_APP_RELEASE SET RATING = ? AND RATED_USERS = ? WHERE UUID = ?;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setDouble(1, rating); statement.setDouble(1, rating);
statement.setInt(2, ratedUsers); statement.setInt(2, ratedUsers);
statement.setInt(2, id); statement.setString(3, uuid);
return statement.executeUpdate(); statement.executeUpdate();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Database connection exception while trying to update the application release", e); "Database connection exception while trying to update the application release rating value", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"SQL exception while updating the release ,while executing the query " + sql, e); "SQL exception while updating the release rating value ,while executing the query " + sql, e);
} finally { } finally {
Util.cleanupResources(statement, null); Util.cleanupResources(statement, null);
} }
@ -313,16 +313,17 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override
public Rating getRating(String uuid) throws ApplicationManagementDAOException { public Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
Rating rating = null; Rating rating = null;
String sql = "SELECT RATING, RATED_USERS FROM AP_APP_RELEASE WHERE UUID = ?;"; String sql = "SELECT RATING, RATED_USERS FROM AP_APP_RELEASE WHERE UUID = ? AND TENANT_D=?;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, uuid); statement.setString(1, uuid);
statement.setInt(2, tenantId);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (resultSet.next()){ if (resultSet.next()){

@ -25,6 +25,8 @@ 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.Review;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest; 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.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewDoesNotExistException;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; 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.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException; import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
@ -41,7 +43,6 @@ import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.TreeMap; import java.util.TreeMap;
@ -64,34 +65,29 @@ public class ReviewManagerImpl implements ReviewManager {
this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO(); this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO();
} }
@Override public boolean addReview(Review review, String uuid) throws ReviewManagementException { @Override public boolean addReview(Review review, String uuid)
throws ReviewManagementException, RequestValidatingException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
boolean isSuccess; boolean isSuccess = false;
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
Review existingReview = reviewDAO.haveUerCommented(uuid, username, tenantId); Review existingReview = reviewDAO.haveUerCommented(uuid, username, tenantId);
if (existingReview != null && review.getRating() > 0 && review.getRating() != existingReview.getRating()) { if (existingReview != null && isAuthorizedUser(username, existingReview.getUsername(), tenantId)
&& review.getRating() > 0 && review.getRating() != existingReview.getRating()) {
Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating(), uuid); Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating(), uuid);
new Thread(task).start(); new Thread(task).start();
isSuccess = updateReview(review, existingReview.getId(),uuid, false); isSuccess = updateReview(review, existingReview.getId(), uuid, existingReview);
if (isSuccess) { } else if (review.getRating() > 0) {
ConnectionManagerUtil.commitDBTransaction(); Runnable task = () -> calculateRating(review.getRating(), -12345, uuid);
} else { new Thread(task).start();
ConnectionManagerUtil.rollbackDBTransaction();
}
} else {
if (review.getRating() > 0) {
Runnable task = () -> calculateRating(review.getRating(), -12345, uuid);
new Thread(task).start();
}
review.setUsername(username); review.setUsername(username);
isSuccess = this.reviewDAO.addReview(review, uuid, tenantId); isSuccess = this.reviewDAO.addReview(review, uuid, tenantId);
if (isSuccess) { }
ConnectionManagerUtil.commitDBTransaction(); if (isSuccess) {
} else { ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.rollbackDBTransaction(); } else {
} ConnectionManagerUtil.rollbackDBTransaction();
} }
return isSuccess; return isSuccess;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
@ -103,49 +99,54 @@ public class ReviewManagerImpl implements ReviewManager {
throw new ReviewManagementException( throw new ReviewManagementException(
"Transaction Management Exception occurs,Review for application release with UUID:" + uuid + "Transaction Management Exception occurs,Review for application release with UUID:" + uuid +
" is failed ", e); " is failed ", e);
} catch (UserStoreException e) {
throw new ReviewManagementException("Error occured while verifying user's permission to update the review.",
e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
@Override @Override
public boolean updateReview(Review review, int reviewId, String uuid, boolean checkExistence) public boolean updateReview(Review review, int reviewId, String uuid, Review existingReview)
throws ReviewManagementException { throws ReviewManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Review existingReview;
boolean isSuccess;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Review updating request is received for the review id " + reviewId); log.debug("Review updating request is received for the review id " + reviewId);
} }
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
// todo if (existingReview == null) {
if (!username.equals(review.getUsername())) {
throw new ReviewManagementException(
"User " + review.getUsername() + "doesn't match with the logged in user: " + username);
}
if (checkExistence) {
existingReview = this.reviewDAO.getReview(reviewId); existingReview = this.reviewDAO.getReview(reviewId);
if (existingReview != null) { if (existingReview != null && isAuthorizedUser(username, existingReview.getUsername(), tenantId)) {
if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) { if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) {
Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating(), uuid); Review finalExistingReview = existingReview;
Runnable task = () -> calculateRating(review.getRating(), finalExistingReview.getRating(),
uuid);
new Thread(task).start(); new Thread(task).start();
} }
} else { } else {
throw new ReviewManagementException("Couldn't find a review for review id: " + reviewId); throw new ReviewManagementException(
"Please check the existence of the review, Review-Id: " + reviewId
+ " or permission of the " + username + " to update the review.");
} }
} }
if (review.getComment().isEmpty()) {
review.setComment(existingReview.getComment());
}
if (review.getRating() == 0) {
review.setRating(existingReview.getRating());
}
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
isSuccess = this.reviewDAO.updateReview(review, reviewId, tenantId); if (this.reviewDAO.updateReview(review, reviewId, username, tenantId) == 1) {
if (isSuccess) {
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} else { return true;
ConnectionManagerUtil.rollbackDBTransaction();
} }
return isSuccess; ConnectionManagerUtil.rollbackDBTransaction();
} catch (SQLException e) { return false;
throw new ReviewManagementException("SQL Error occurs updating review with review id " + reviewId + ".", } catch (ReviewManagementDAOException e) {
throw new ReviewManagementException("Error occured while updating review with review id " + reviewId + ".",
e); e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ReviewManagementException( throw new ReviewManagementException(
@ -153,6 +154,10 @@ public class ReviewManagerImpl implements ReviewManager {
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
throw new ReviewManagementException( throw new ReviewManagementException(
"Transaction management error occurs when updating review with review id " + reviewId + ".", e); "Transaction management error occurs when updating review with review id " + reviewId + ".", e);
} catch (UserStoreException e) {
throw new ReviewManagementException(
"Error occured while verifying user's permission to update the review. review id: " + reviewId
+ ".", e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -203,55 +208,28 @@ public class ReviewManagerImpl implements ReviewManager {
} }
} }
@Override public Review getReview(int commentId) throws ReviewManagementException {
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.getReview(commentId);
} catch (DBConnectionException e) {
throw new ReviewManagementException(
"DB Connection error occurs ,Review with review id " + commentId + "cannot get.", e);
} catch (SQLException e) {
throw new ReviewManagementException(
"SQL Exception occurs,Review with review id " + commentId + "cannot get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
return review;
}
@Override @Override
public boolean deleteReview(String uuid, int reviewId) throws ReviewManagementException { public boolean deleteReview(String uuid, int reviewId)
throws ReviewManagementException, ReviewDoesNotExistException {
Review existingReview; Review existingReview;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int isReviewDeleted;
try { try {
existingReview = getReview(reviewId); ConnectionManagerUtil.openDBConnection();
existingReview = this.reviewDAO.getReview(reviewId);
if (existingReview == null) { if (existingReview == null) {
throw new ReviewManagementException( throw new ReviewDoesNotExistException(
"Cannot delete a non-existing review for the application with review id" + reviewId); "Cannot delete a non-existing review for the application with review id" + reviewId);
} }
Runnable task = () -> calculateRating(0, existingReview.getRating(), uuid); Runnable task = () -> calculateRating(0, existingReview.getRating(), uuid);
new Thread(task).start(); new Thread(task).start();
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
if (isAdminUser(username, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (isAuthorizedUser(username, existingReview.getUsername(), tenantId)
isReviewDeleted = this.reviewDAO.deleteReviewByAdmin(reviewId); && this.reviewDAO.deleteReview(username, reviewId) == 1) {
if (isReviewDeleted == 1) { ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.commitDBTransaction(); return true;
return true;
}
} else {
isReviewDeleted = this.reviewDAO.deleteReview(username, reviewId);
if (isReviewDeleted == 1) {
ConnectionManagerUtil.commitDBTransaction();
return true;
}
} }
ConnectionManagerUtil.rollbackDBTransaction();
return false; return false;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ReviewManagementException( throw new ReviewManagementException(
@ -272,17 +250,17 @@ public class ReviewManagerImpl implements ReviewManager {
} }
@Override public Rating getRating(String appReleaseUuuid) throws ReviewManagementException { @Override public Rating getRating(String appReleaseUuuid) throws ReviewManagementException {
//todo int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
int appReleaseId = 0;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
Rating rating = this.applicationReleaseDAO.getRating(appReleaseUuuid); Rating rating = this.applicationReleaseDAO.getRating(appReleaseUuuid, tenantId);
if (rating == null) { if (rating == null) {
throw new ReviewManagementException("Couldn't find rating for application release id: " + appReleaseId throw new ReviewManagementException(
+ ". Please check the existence of the application relese"); "Couldn't find rating for application release UUID: " + appReleaseUuuid
+ ". Please check the existence of the application release");
} }
List<Integer> ratingValues = this.reviewDAO.getAllRatingValues(appReleaseUuuid); List<Integer> ratingValues = this.reviewDAO.getAllRatingValues(appReleaseUuuid, tenantId);
TreeMap<Integer, Integer> ratingVariety = rating.getRatingVariety(); TreeMap<Integer, Integer> ratingVariety = rating.getRatingVariety();
for (Integer ratingVal : ratingValues) { for (Integer ratingVal : ratingValues) {
if (ratingVariety.containsKey(ratingVal)) { if (ratingVariety.containsKey(ratingVal)) {
@ -296,62 +274,59 @@ public class ReviewManagerImpl implements ReviewManager {
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException( throw new ReviewManagementException(
"Error occured while updated the rating value of the application release id: " + appReleaseId "Error occured while getting the rating value of the application release uuid: " + appReleaseUuuid,
+ " can not get.", e); e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException( throw new ReviewManagementException(
"DB Connection error occured while updated the rating value of the application release id: " "DB Connection error occured while getting the rating value of the application release uuid: "
+ appReleaseId + " can not get.", e); + appReleaseUuuid, e);
} catch (SQLException e) { } catch (ReviewManagementDAOException e) {
throw new ReviewManagementException( throw new ReviewManagementException(
"DB Connection error occured while updated the rating value of the application release id: " "Error occured while getting all rating values for the application release UUID: "
+ appReleaseId + " can not get.", e); + appReleaseUuuid, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
private void calculateRating(int newRatingVal, int oldRatingVal, String uuid) { private void calculateRating(int newRatingVal, int oldRatingVal, String uuid) {
// todo need to pass app release id int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
int appReleaseId = 0;
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
Rating rating = this.applicationReleaseDAO.getRating(uuid); Rating rating = this.applicationReleaseDAO.getRating(uuid, tenantId);
if (rating == null) { if (rating == null) {
log.error("Couldn't find rating for application release id: " + appReleaseId); log.error("Couldn't find rating for application release uuid: " + uuid);
} else { } else {
double updatedRating; double updatedRating;
int numOfUsers = rating.getNoOfUsers(); int numOfUsers = rating.getNoOfUsers();
double currentRating = rating.getRatingValue() * numOfUsers; double currentRating = rating.getRatingValue() * numOfUsers;
if (oldRatingVal == -12345) { if (oldRatingVal == -12345) {
updatedRating = (currentRating + newRatingVal) / (numOfUsers + 1); updatedRating = (currentRating + newRatingVal) / (numOfUsers + 1);
this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers + 1); this.applicationReleaseDAO.updateRatingValue(uuid, updatedRating, numOfUsers + 1);
} else if (newRatingVal == 0) { } else if (newRatingVal == 0) {
updatedRating = (currentRating - newRatingVal) / (numOfUsers - 1); updatedRating = (currentRating - newRatingVal) / (numOfUsers - 1);
this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers - 1); this.applicationReleaseDAO.updateRatingValue(uuid, updatedRating, numOfUsers - 1);
} else { } else {
double tmpVal; double tmpVal;
tmpVal = currentRating - oldRatingVal; tmpVal = currentRating - oldRatingVal;
updatedRating = (tmpVal + newRatingVal) / numOfUsers; updatedRating = (tmpVal + newRatingVal) / numOfUsers;
this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers); this.applicationReleaseDAO.updateRatingValue(uuid, updatedRating, numOfUsers);
} }
} }
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
log.error("Error occured while updated the rating value of the application release id: " + appReleaseId log.error("Error occured while updated the rating value of the application release UUID: " + uuid);
+ " can not get.");
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
log.error( log.error(
"Transaction Management Exception occured while updated the rating value of the application release id: " "Transaction Management Exception occured while updated the rating value of the application release UUID: "
+ appReleaseId + " can not get."); + uuid);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
log.error("DB Connection error occured while updated the rating value of the application release id: " log.error("DB Connection error occured while updated the rating value of the application release UUID: "
+ appReleaseId + " can not get."); + uuid + " can not get.");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -372,4 +347,20 @@ public class ReviewManagerImpl implements ReviewManager {
.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission, .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission,
CarbonConstants.UI_PERMISSION_ACTION); CarbonConstants.UI_PERMISSION_ACTION);
} }
/**
* To check whether logged in user is authorized user to do an specific action.
*
* @param loggedInUser username of the loggedin user.
* @param reviewOwner username of the review owner.
* @param tenantId ID of the tenant.
* @return true if the current user has the permission, otherwise false.
* @throws UserStoreException UserStoreException
*/
private boolean isAuthorizedUser(String loggedInUser, String reviewOwner, int tenantId) throws UserStoreException {
return loggedInUser.equals(reviewOwner) || isAdminUser(loggedInUser, tenantId,
CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION);
}
} }

@ -30,6 +30,7 @@ import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.publisher.api.beans.ErrorResponse; import org.wso2.carbon.device.application.mgt.publisher.api.beans.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.Review;
import javax.validation.Valid; import javax.validation.Valid;
@ -47,7 +48,7 @@ import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
/** /**
* APIs to handle comment management related tasks. * APIs to handle review management related tasks.
*/ */
@SwaggerDefinition( @SwaggerDefinition(
@ -56,51 +57,36 @@ import java.util.List;
title = "Store Management Service", title = "Store Management Service",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = "name", value = "CommentManagementService"), @ExtensionProperty(name = "name", value = "ReviewManagementService"),
@ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/comments"), @ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/review"),
}) })
} }
), ),
tags = { tags = {
@Tag(name = "store_management", description = "Review Management related " @Tag(name = "store_management", description = "Review Management related APIs")
+ "APIs")
} }
) )
@Scopes( @Scopes(
scopes = { scopes = {
@Scope( @Scope(
name = "Get Comments Details", name = "Get Review Details",
description = "Get comments details", description = "Get review details",
key = "perm:comment:get", key = "perm:app:review:view",
permissions = {"/device-mgt/comment/get"} permissions = {"/device-mgt/review/view"}
),
@Scope(
name = "Add a Review",
description = "Add a comment",
key = "perm:comment:add",
permissions = {"/device-mgt/comment/add"}
), ),
@Scope( @Scope(
name = "Update a Review", name = "Update a Review",
description = "Update a Review", description = "Update a comment",
key = "perm:comment:update", key = "perm:app:review:update",
permissions = {"/device-mgt/comment/update"} permissions = {"/device-mgt/review/update"}
),
@Scope(
name = "Delete a Review",
description = "Delete a comment",
key = "perm:comment:delete",
permissions = {"/device-mgt/comment/delete"}
), ),
} }
) )
@Path("/review") @Path("/review")
@Api(value = "Comments Management", description = "This API carries all comments management related operations " + @Api(value = "Review Management", description = "This API carries all review management related operations such as get "
"such as get all the comments, add comment, etc.") + "all the reviews, add review, etc.")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public interface ReviewManagementAPI { public interface ReviewManagementAPI {
String SCOPE = "scope"; String SCOPE = "scope";
@ -110,12 +96,12 @@ public interface ReviewManagementAPI {
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "get comments", value = "get reviews",
notes = "Get all comments", notes = "Get all reviews",
tags = "Store Management", tags = "Store Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:store:get") @ExtensionProperty(name = SCOPE, value = "perm:app:review:view")
}) })
} }
) )
@ -125,12 +111,8 @@ public interface ReviewManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully retrieved comments.", message = "OK. \n Successfully retrieved comments.",
response = List.class, response = PaginationResult.class,
responseContainer = "List"), responseContainer = "PaginationResult"),
@ApiResponse(
code = 404,
message = "Not Found. \n No activity found with the given ID.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while getting the comment list.", message = "Internal Server Error. \n Error occurred while getting the comment list.",
@ -146,14 +128,12 @@ public interface ReviewManagementAPI {
String uuid, String uuid,
@ApiParam( @ApiParam(
name="offSet", name="offSet",
value="Starting comment number.",defaultValue = "1", value="Starting comment number.",defaultValue = "0")
required = false)
@QueryParam("offSet") @QueryParam("offSet")
int offSet, int offSet,
@ApiParam( @ApiParam(
name="limit", name="limit",
value = "Limit of paginated comments",defaultValue = "20", value = "Limit of paginated comments",defaultValue = "20")
required = false)
@QueryParam("limit") @QueryParam("limit")
int limit); int limit);
@ -170,7 +150,7 @@ public interface ReviewManagementAPI {
tags = "Store Management", tags = "Store Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:store:add") @ExtensionProperty(name = SCOPE, value = "perm:app:review:update")
}) })
} }
) )
@ -215,7 +195,7 @@ public interface ReviewManagementAPI {
tags = "Store Management", tags = "Store Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:store:edit") @ExtensionProperty(name = SCOPE, value = "perm:app:review:update")
}) })
} }
) )

@ -25,6 +25,8 @@ import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.PaginationResult; 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.Rating;
import org.wso2.carbon.device.application.mgt.common.Review; import org.wso2.carbon.device.application.mgt.common.Review;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewDoesNotExistException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; 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.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.store.api.APIUtil; import org.wso2.carbon.device.application.mgt.store.api.APIUtil;
@ -106,6 +108,10 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error("Error occured while getting the application for application UUID: " + uuid); log.error("Error occured while getting the application for application UUID: " + uuid);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR) return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("").build(); .entity("").build();
} catch (RequestValidatingException e) {
String msg = "Error occurred while adding for application release. UUID of the application release: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
} }
@ -119,7 +125,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@PathParam("reviewId") int reviewId) { @PathParam("reviewId") int reviewId) {
ReviewManager reviewManager = APIUtil.getReviewManager(); ReviewManager reviewManager = APIUtil.getReviewManager();
try { try {
if (reviewManager.updateReview(review, reviewId, uuid, true)) { if (reviewManager.updateReview(review, reviewId, uuid, null)) {
return Response.status(Response.Status.OK).entity(review).build(); return Response.status(Response.Status.OK).entity(review).build();
} else { } else {
String msg = "Review updating failed. Please contact the administrator"; String msg = "Review updating failed. Please contact the administrator";
@ -130,6 +136,10 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
String msg = "Error occurred while retrieving comments."; String msg = "Error occurred while retrieving comments.";
log.error(msg, e); 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 (RequestValidatingException e) {
String msg = "Error occurred while updating review. Review id: " + reviewId;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
} }
@ -142,9 +152,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
ReviewManager reviewManager = APIUtil.getReviewManager(); ReviewManager reviewManager = APIUtil.getReviewManager();
try { try {
if (reviewId == 0) { if (reviewManager.deleteReview(uuid, reviewId)) {
return Response.status(Response.Status.NOT_FOUND).entity("Review not found").build();
} else if (reviewManager.deleteReview(uuid, reviewId)) {
return Response.status(Response.Status.OK).entity("Review is deleted successfully.").build(); return Response.status(Response.Status.OK).entity("Review is deleted successfully.").build();
} else { } else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Review deleting is failed.") return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Review deleting is failed.")
@ -154,6 +162,10 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
String msg = "Error occurred while deleting the comment."; String msg = "Error occurred while deleting the comment.";
log.error(msg, e); 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 (ReviewDoesNotExistException e) {
String msg = "Couldn't find a review for review-id: " + reviewId + " to delete.";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} }
} }

Loading…
Cancel
Save