Improve APPM review management

feature/appm-store/pbac
lasanthaDLPDS 5 years ago
parent 4aa42aed6f
commit a0f28ce969

@ -28,6 +28,8 @@ public class ReviewDTO {
private int rating; private int rating;
private int rootParentId; private int rootParentId;
private int immediateParentId; private int immediateParentId;
private String releaseUuid;
private String releaseVersion;
public int getId() { public int getId() {
return id; return id;
@ -84,4 +86,12 @@ public class ReviewDTO {
public int getImmediateParentId() { return immediateParentId; } public int getImmediateParentId() { return immediateParentId; }
public void setImmediateParentId(int immediateParentId) { this.immediateParentId = immediateParentId; } public void setImmediateParentId(int immediateParentId) { this.immediateParentId = immediateParentId; }
public String getReleaseUuid() { return releaseUuid; }
public void setReleaseUuid(String releaseUuid) { this.releaseUuid = releaseUuid; }
public String getReleaseVersion() { return releaseVersion; }
public void setReleaseVersion(String releaseVersion) { this.releaseVersion = releaseVersion; }
} }

@ -39,7 +39,7 @@ public interface ReviewManager {
* @return {@link Review} Added review * @return {@link Review} Added review
* @throws ReviewManagementException Exceptions of the reviewTmp management. * @throws ReviewManagementException Exceptions of the reviewTmp management.
*/ */
boolean addReview(ReviewWrapper reviewWrapper, String uuid) boolean addReview(ReviewWrapper reviewWrapper, String uuid, boolean allowMultipleReviews)
throws ReviewManagementException, ApplicationManagementException; throws ReviewManagementException, ApplicationManagementException;
boolean addReplyComment(ReviewWrapper reviewWrapper, String uuid, int parentReviewId) boolean addReplyComment(ReviewWrapper reviewWrapper, String uuid, int parentReviewId)
@ -53,14 +53,19 @@ public interface ReviewManager {
* @return {@link PaginationResult} pagination result with starting offSet and limit * @return {@link PaginationResult} pagination result with starting offSet and limit
* @throws ReviewManagementException Exceptions of the comment management. * @throws ReviewManagementException Exceptions of the comment management.
*/ */
PaginationResult getAllReviews(PaginationRequest request, String uuid) PaginationResult getAllReleaseReviews(PaginationRequest request, String uuid)
throws ReviewManagementException, ApplicationManagementException; throws ReviewManagementException, ApplicationManagementException;
PaginationResult getAllAppReviews(PaginationRequest request, String uuid) throws ReviewManagementException,
ApplicationManagementException;
PaginationResult getAllAppReviewsOfUser(PaginationRequest request, String uuid) throws ReviewManagementException,
ApplicationManagementException;
/** /**
* To delete review using review id. * To delete review using review id.
* *
* @param uuid UUID of the application release * @param uuid UUID of the application release
* @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
*/ */
void deleteReview(String uuid, int reviewId, boolean isPriviledgedUser) void deleteReview(String uuid, int reviewId, boolean isPriviledgedUser)
@ -70,19 +75,21 @@ public interface ReviewManager {
* To update a reviewTmp. * To update a reviewTmp.
* *
* @param reviewId id of the reviewTmp * @param reviewId id of the reviewTmp
* @param uuid UUID of the application release
* @return {@link Review}updated review * @return {@link Review}updated review
* @throws ReviewManagementException Exceptions of the reviewTmp management * @throws ReviewManagementException Exceptions of the reviewTmp management
*/ */
boolean updateReview(ReviewWrapper updatingReview, int reviewId, String uuid, boolean isPriviledgedUser) boolean updateReview(ReviewWrapper updatingReview, int reviewId, String uuid, boolean isPrivilegedUser)
throws ReviewManagementException, ApplicationManagementException; throws ReviewManagementException, ApplicationManagementException;
/** /**
* To get the overall rating for a application release * To get the overall rating for a application release
* *
* @param appReleaseUuuid UUID of the application release. * @param appReleaseUuid UUID of the application release.
* @return {@link Review}updated review * @return {@link Review}updated review
* @throws ReviewManagementException Exceptions of the review management * @throws ReviewManagementException Exceptions of the review management
*/ */
Rating getRating(String appReleaseUuuid) throws ReviewManagementException, ApplicationManagementException; Rating getAppReleaseRating(String appReleaseUuid) throws ReviewManagementException, ApplicationManagementException;
Rating getAppRating(String appReleaseUuid) throws ReviewManagementException, ApplicationManagementException;
} }

@ -48,13 +48,13 @@ import java.util.List;
/** /**
* To verify whether user has already commented for the application release or not. * To verify whether user has already commented for the application release or not.
* *
* @param appReleaseId ID of the application release. * @param appReleaseIds List of the application release IDs.
* @param username username of the logged in user. * @param username username of the logged in user.
* @param tenantId tenantId of the commented application. * @param tenantId tenantId of the commented application.
* @return If review exists, review returns * @return If review exists, review returns
* @throws ReviewManagementDAOException Exceptions of the review management DAO. * @throws ReviewManagementDAOException Exceptions of the review management DAO.
*/ */
boolean haveUerReviewed(int appReleaseId, String username, int tenantId) throws ReviewManagementDAOException; boolean hasUerReviewedApp(List<Integer> appReleaseIds, String username, int tenantId) throws ReviewManagementDAOException;
/** /**
* To update already added comment. * To update already added comment.
@ -65,7 +65,8 @@ import java.util.List;
* @return row count if updating is succeed otherwise 0 * @return row count if updating is succeed otherwise 0
* @throws ReviewManagementDAOException Exceptions of the reviewTmp management. * @throws ReviewManagementDAOException Exceptions of the reviewTmp management.
*/ */
int updateReview(ReviewDTO reviewDTO, int reviewId, int tenantId) throws ReviewManagementDAOException; int updateReview(ReviewDTO reviewDTO, int reviewId, boolean isActiveReview, int tenantId)
throws ReviewManagementDAOException;
/** /**
@ -89,9 +90,15 @@ import java.util.List;
* @return {@link List}List of all reviews for the application release * @return {@link List}List of all reviews for the application release
* @throws ReviewManagementDAOException Review management DAO exception * @throws ReviewManagementDAOException Review management DAO exception
**/ **/
List<ReviewDTO> getAllReviews(int releaseId, PaginationRequest request, int tenantId) List<ReviewDTO> getAllActiveReleaseReviews(int releaseId, PaginationRequest request, int tenantId)
throws ReviewManagementDAOException;
List<ReviewDTO> getAllActiveAppReviews(List<Integer> releaseIds, PaginationRequest request, int tenantId)
throws ReviewManagementDAOException; throws ReviewManagementDAOException;
List<ReviewDTO> getAllActiveAppReviewsOfUser(List<Integer> releaseIds, PaginationRequest request, String username,
int tenantId) throws ReviewManagementDAOException;
List<ReviewDTO> getReplyComments(int parentId, int tenantId) List<ReviewDTO> getReplyComments(int parentId, int tenantId)
throws ReviewManagementDAOException; throws ReviewManagementDAOException;
@ -102,7 +109,10 @@ import java.util.List;
* @return {@link List}List of comments * @return {@link List}List of comments
* @throws ReviewManagementDAOException Exceptions of the review management DAO. * @throws ReviewManagementDAOException Exceptions of the review management DAO.
*/ */
List<Integer> getAllRatingValues(String uuid, int tenantId) throws ReviewManagementDAOException; List<Integer> getAllAppReleaseRatingValues(String uuid, int tenantId) throws ReviewManagementDAOException;
List<Integer> getAllAppRatingValues(List<String> uuids, int tenantId) throws ReviewManagementDAOException;
/** /**
* To get count of comments by application details. * To get count of comments by application details.
@ -121,7 +131,6 @@ import java.util.List;
/** /**
* To delete review using review id and uuid of the application release. * To delete review using review id and uuid of the application release.
* *
* @param username username of the review owner
* @param reviewId id of the review * @param reviewId id of the review
* @return If review is successfully deleted return 1, otherwise returns 0. * @return If review is successfully deleted return 1, otherwise returns 0.
* @throws ReviewManagementDAOException Review management DAO exception. * @throws ReviewManagementDAOException Review management DAO exception.

@ -40,6 +40,7 @@ import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.StringJoiner;
/** /**
* This handles ReviewDAO related operations. * This handles ReviewDAO related operations.
@ -98,28 +99,29 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public boolean haveUerReviewed(int appReleaseId, String username, int tenantId) throws ReviewManagementDAOException { public boolean hasUerReviewedApp(List<Integer> appReleaseIds, String username, int tenantId)
throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to check whether user have already reviewed or not for the " log.debug("Request received in DAO Layer to check whether user have already reviewed or not for the "
+ "application release. Commenting user: " + username + " and tenant-id: " + tenantId); + "application. Commenting user: " + username + " and tenant-id: " + tenantId);
} }
Connection conn; Connection conn;
sql = "SELECT " int index = 1;
+ "rv.ID "
+ "FROM AP_APP_REVIEW rv "
+ "WHERE "
+ "rv.AP_APP_RELEASE_ID = ? AND "
+ "rv.USERNAME = ? AND "
+ "rv.TENANT_ID = ?";
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
try (PreparedStatement statement = conn.prepareStatement(sql)) { StringJoiner joiner = new StringJoiner(",",
statement.setInt(1, appReleaseId); "SELECT rv.ID FROM AP_APP_REVIEW " + "WHERE rv.AP_APP_RELEASE_ID IN (",
statement.setString(2, username); ") AND rv.USERNAME = ? AND rv.TENANT_ID = ?");
statement.setInt(3, tenantId); appReleaseIds.stream().map(ignored -> "?").forEach(joiner::add);
try (ResultSet rs = statement.executeQuery()) { String query = joiner.toString();
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : appReleaseIds) {
ps.setObject(index++, deviceId);
}
ps.setInt(index++, tenantId);
ps.setInt(index, tenantId);
try (ResultSet rs = ps.executeQuery()) {
return rs.next(); return rs.next();
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -132,7 +134,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public int updateReview(ReviewDTO reviewDTO, int reviewId, int tenantId) public int updateReview(ReviewDTO reviewDTO, int reviewId, boolean isActiveReview, int tenantId)
throws ReviewManagementDAOException { throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -146,7 +148,8 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
+ "SET " + "SET "
+ "COMMENT = ?, " + "COMMENT = ?, "
+ "RATING = ?, " + "RATING = ?, "
+ "MODIFIED_AT = ? " + "MODIFIED_AT = ?, "
+ "ACTIVE_REVIEW = ? "
+ "WHERE ID = ? AND " + "WHERE ID = ? AND "
+ "TENANT_ID = ?"; + "TENANT_ID = ?";
try { try {
@ -158,8 +161,9 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
statement.setString(1, reviewDTO.getContent()); statement.setString(1, reviewDTO.getContent());
statement.setInt(2, reviewDTO.getRating()); statement.setInt(2, reviewDTO.getRating());
statement.setTimestamp(3, timestamp); statement.setTimestamp(3, timestamp);
statement.setInt(4, reviewId); statement.setBoolean(4, isActiveReview);
statement.setInt(5, tenantId); statement.setInt(5, reviewId);
statement.setInt(6, tenantId);
return statement.executeUpdate(); return statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new ReviewManagementDAOException("Error occurred while executing reviewTmp updating query"); throw new ReviewManagementDAOException("Error occurred while executing reviewTmp updating query");
@ -182,16 +186,19 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT " sql = "SELECT "
+ "ID, " + "AP_APP_REVIEW.ID AS ID, "
+ "COMMENT," + "AP_APP_REVIEW.COMMENT AS COMMENT, "
+ "ROOT_PARENT_ID," + "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, "
+ "IMMEDIATE_PARENT_ID, " + "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, "
+ "CREATED_AT, " + "AP_APP_REVIEW.CREATED_AT AS CREATED_AT, "
+ "MODIFIED_AT, " + "AP_APP_REVIEW.MODIFIED_AT AS MODIFIED_AT, "
+ "RATING, " + "AP_APP_REVIEW.RATING AS RATING, "
+ "USERNAME " + "AP_APP_REVIEW.USERNAME AS USERNAME, "
+ "FROM AP_APP_REVIEW " + "AP_APP_RELEASE.UUID AS UUID, "
+ "WHERE ID = ?"; + "AP_APP_RELEASE.VERSION AS VERSION "
+ "FROM AP_APP_REVIEW INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = AP_APP_RELEASE.ID "
+ "WHERE AP_APP_REVIEW.ID = ?";
statement = conn.prepareStatement(sql); statement = conn.prepareStatement(sql);
statement.setInt(1, reviewId); statement.setInt(1, reviewId);
rs = statement.executeQuery(); rs = statement.executeQuery();
@ -251,14 +258,14 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
@Override @Override
public List<ReviewDTO> getAllReviews(int releaseId, PaginationRequest request, int tenantId) public List<ReviewDTO> getAllActiveReleaseReviews(int releaseId, PaginationRequest request, int tenantId)
throws ReviewManagementDAOException { throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting comment of the application release (" + releaseId + ") from the database"); log.debug("Getting comment of the application release (" + releaseId + ") from the database");
} }
Connection conn; Connection conn;
List<ReviewDTO> reviewDTOs = new ArrayList<>(); List<ReviewDTO> reviewDTOs;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT " sql = "SELECT "
@ -270,10 +277,13 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
+ "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, " + "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, "
+ "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, " + "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, "
+ "AP_APP_REVIEW.RATING AS RATING " + "AP_APP_REVIEW.RATING AS RATING "
+ "FROM AP_APP_REVIEW " + "AP_APP_RELEASE.UUID AS UUID, "
+ "WHERE " + "AP_APP_RELEASE.VERSION AS VERSION "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = ? AND " + "FROM AP_APP_REVIEW INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = AP_APP_RELEASE.ID "
+ "WHERE AP_APP_REVIEW.AP_APP_RELEASE_ID = ? AND "
+ "AP_APP_REVIEW.ROOT_PARENT_ID = ? AND " + "AP_APP_REVIEW.ROOT_PARENT_ID = ? AND "
+ "AP_APP_REVIEW.ACTIVE_REVIEW = true "
+ "AP_APP_REVIEW.TENANT_ID = ? " + "AP_APP_REVIEW.TENANT_ID = ? "
+ "LIMIT ? OFFSET ?"; + "LIMIT ? OFFSET ?";
try (PreparedStatement statement = conn.prepareStatement(sql)) { try (PreparedStatement statement = conn.prepareStatement(sql)) {
@ -294,6 +304,120 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} return reviewDTOs; } return reviewDTOs;
} }
@Override
public List<ReviewDTO> getAllActiveAppReviews(List<Integer> releaseIds, PaginationRequest request, int tenantId)
throws ReviewManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting reviews of the application from the database.");
}
Connection conn;
List<ReviewDTO> reviewDTOs;
int index = 1;
try {
conn = this.getDBConnection();
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "AP_APP_REVIEW.ID AS ID, "
+ "AP_APP_REVIEW.COMMENT AS COMMENT, "
+ "AP_APP_REVIEW.CREATED_AT AS CREATED_AT, "
+ "AP_APP_REVIEW.MODIFIED_AT AS MODIFIED_AT, "
+ "AP_APP_REVIEW.USERNAME AS USERNAME, "
+ "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, "
+ "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, "
+ "AP_APP_REVIEW.RATING AS RATING, "
+ "AP_APP_RELEASE.UUID AS UUID, "
+ "AP_APP_RELEASE.VERSION AS VERSION "
+ "FROM AP_APP_REVIEW INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = AP_APP_RELEASE.ID "
+ "WHERE AP_APP_REVIEW.AP_APP_RELEASE_ID (",
") AND AP_APP_REVIEW.ROOT_PARENT_ID = ? AND "
+ "AP_APP_REVIEW.ACTIVE_REVIEW = true AND "
+ "AP_APP_REVIEW.TENANT_ID = ? "
+ "LIMIT ? OFFSET ?");
releaseIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer releaseId : releaseIds) {
ps.setObject(index++, releaseId);
}
ps.setInt(index++, Constants.REVIEW_PARENT_ID);
ps.setInt(index++, tenantId);
ps.setInt(index++, request.getLimit());
ps.setInt(index, request.getOffSet());
try (ResultSet rs = ps.executeQuery()) {
reviewDTOs = DAOUtil.loadReviews(rs);
}
}
}
catch (DBConnectionException e) {
throw new ReviewManagementDAOException(
"Error occurred while obtaining the DB connection when verifying application existence.", e);
} catch (SQLException e) {
throw new ReviewManagementDAOException("DB connection error occurred while getting all reviews.", e);
} return reviewDTOs;
}
@Override
public List<ReviewDTO> getAllActiveAppReviewsOfUser(List<Integer> releaseIds, PaginationRequest request,
String username, int tenantId)
throws ReviewManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting reviews of the application for given user from the database.");
}
Connection conn;
List<ReviewDTO> reviewDTOs;
int index = 1;
try {
conn = this.getDBConnection();
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "AP_APP_REVIEW.ID AS ID, "
+ "AP_APP_REVIEW.COMMENT AS COMMENT, "
+ "AP_APP_REVIEW.CREATED_AT AS CREATED_AT, "
+ "AP_APP_REVIEW.MODIFIED_AT AS MODIFIED_AT, "
+ "AP_APP_REVIEW.USERNAME AS USERNAME, "
+ "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, "
+ "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, "
+ "AP_APP_REVIEW.RATING AS RATING, "
+ "AP_APP_RELEASE.UUID AS UUID, "
+ "AP_APP_RELEASE.VERSION AS VERSION "
+ "FROM AP_APP_REVIEW INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = AP_APP_RELEASE.ID "
+ "WHERE AP_APP_REVIEW.AP_APP_RELEASE_ID (",
") AND AP_APP_REVIEW.ROOT_PARENT_ID = ? AND "
+ "AP_APP_REVIEW.ACTIVE_REVIEW = true AND "
+ "AP_APP_REVIEW.USERNAME = ? AND "
+ "AP_APP_REVIEW.TENANT_ID = ? "
+ "LIMIT ? OFFSET ?");
releaseIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer releaseId : releaseIds) {
ps.setObject(index++, releaseId);
}
ps.setInt(index++, Constants.REVIEW_PARENT_ID);
ps.setString(index++, username);
ps.setInt(index++, tenantId);
ps.setInt(index++, request.getLimit());
ps.setInt(index, request.getOffSet());
try (ResultSet rs = ps.executeQuery()) {
reviewDTOs = DAOUtil.loadReviews(rs);
}
}
}
catch (DBConnectionException e) {
throw new ReviewManagementDAOException(
"Error occurred while obtaining the DB connection when application review of user: " + username , e);
} catch (SQLException e) {
throw new ReviewManagementDAOException("DB connection error occurred while getting application reviews of "
+ "user:" + username, e);
} return reviewDTOs;
}
@Override @Override
public List<ReviewDTO> getReplyComments(int parentId, int tenantId) throws ReviewManagementDAOException { public List<ReviewDTO> getReplyComments(int parentId, int tenantId) throws ReviewManagementDAOException {
@ -312,8 +436,11 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
+ "AP_APP_REVIEW.USERNAME AS USERNAME, " + "AP_APP_REVIEW.USERNAME AS USERNAME, "
+ "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, " + "AP_APP_REVIEW.ROOT_PARENT_ID AS ROOT_PARENT_ID, "
+ "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, " + "AP_APP_REVIEW.IMMEDIATE_PARENT_ID AS IMMEDIATE_PARENT_ID, "
+ "AP_APP_REVIEW.RATING AS RATING " + "AP_APP_REVIEW.RATING AS RATING, "
+ "FROM AP_APP_REVIEW " + "AP_APP_RELEASE.UUID AS UUID, "
+ "AP_APP_RELEASE.VERSION AS VERSION "
+ "FROM AP_APP_REVIEW INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = AP_APP_RELEASE.ID "
+ "WHERE " + "WHERE "
+ "AP_APP_REVIEW.ROOT_PARENT_ID = ? AND " + "AP_APP_REVIEW.ROOT_PARENT_ID = ? AND "
+ "AP_APP_REVIEW.TENANT_ID = ?"; + "AP_APP_REVIEW.TENANT_ID = ?";
@ -334,7 +461,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
@Override @Override
public List<Integer> getAllRatingValues(String uuid, int tenantId) throws ReviewManagementDAOException { public List<Integer> getAllAppReleaseRatingValues(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");
@ -347,7 +474,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT AP_APP_REVIEW.RATING AS RATING FROM AP_APP_REVIEW, AP_APP_RELEASE WHERE " sql = "SELECT AP_APP_REVIEW.RATING AS RATING FROM AP_APP_REVIEW, AP_APP_RELEASE WHERE "
+ "AP_APP_REVIEW.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_REVIEW.TENANT_ID = AP_APP_RELEASE.TENANT_ID AND AP_APP_REVIEW.TENANT_ID = ?;"; + "AP_APP_REVIEW.TENANT_ID = AP_APP_RELEASE.TENANT_ID AND AP_APP_REVIEW.TENANT_ID = ?";
statement = conn.prepareStatement(sql); statement = conn.prepareStatement(sql);
statement.setString(1, uuid); statement.setString(1, uuid);
statement.setInt(2, tenantId); statement.setInt(2, tenantId);
@ -369,6 +496,44 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
return reviews; return reviews;
} }
@Override
public List<Integer> getAllAppRatingValues(List<String> uuids, int tenantId) throws ReviewManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting rating values of the application from the database");
}
Connection conn;
List<Integer> reviews = new ArrayList<>();
try {
int index = 1;
conn = this.getDBConnection();
StringJoiner joiner = new StringJoiner(",",
"SELECT AP_APP_REVIEW.RATING AS RATING FROM AP_APP_REVIEW INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID = AP_APP_RELEASE.ID WHERE AP_APP_RELEASE.UUID IN (",
") AND AP_APP_REVIEW.ACTIVE_REVIEW = true AND AP_APP_REVIEW.TENANT_ID = ?");
uuids.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (String uuid : uuids) {
ps.setObject(index++, uuid);
}
ps.setInt(index++, tenantId);
ps.setInt(index, tenantId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
reviews.add(rs.getInt("RATING"));
} }
}
} catch (SQLException e) {
throw new ReviewManagementDAOException(
"Error occured while getting all rating values for the application.", e);
} catch (DBConnectionException e) {
throw new ReviewManagementDAOException(
"Error occured while getting DB connection to retrieve all rating values for the application.", e);
}
return reviews;
}
@Override @Override
public int getReviewCount(String uuid) throws ReviewManagementDAOException { public int getReviewCount(String uuid) throws ReviewManagementDAOException {

@ -144,7 +144,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "OPERATION_ID, " + "OPERATION_ID, "
+ "AP_DEVICE_SUBSCRIPTION_ID, " + "AP_DEVICE_SUBSCRIPTION_ID, "
+ "TENANT_ID) " + "TENANT_ID) "
+ "VALUES (?, ?, ?, ?, ?)"; + "VALUES (?, ?, ?)";
conn = this.getDBConnection(); conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (Integer subId : deviceSubscriptionIds) { for (Integer subId : deviceSubscriptionIds) {

@ -1924,6 +1924,14 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
if (applicationDAO.getTagForTagName(newTagName, tenantId) != null){
String msg =
"You are trying to modify tag name into existing tag. Therefore you can't modify tag name from "
+ oldTagName + " to new tag name " + newTagName;
log.error(msg);
throw new BadRequestException(msg);
}
TagDTO tag = applicationDAO.getTagForTagName(oldTagName, tenantId); TagDTO tag = applicationDAO.getTagForTagName(oldTagName, tenantId);
if (tag == null){ if (tag == null){
String msg = "Couldn't found a tag for tag name " + oldTagName + "."; String msg = "Couldn't found a tag for tag name " + oldTagName + ".";
@ -2129,7 +2137,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (!StringUtils.isEmpty(appType)) { if (!StringUtils.isEmpty(appType)) {
boolean isValidAppType = false; boolean isValidAppType = false;
for (ApplicationType applicationType : ApplicationType.values()) { for (ApplicationType applicationType : ApplicationType.values()) {
if (applicationType.toString().equals(appType)) { if (applicationType.toString().equalsIgnoreCase(appType)) {
isValidAppType = true; isValidAppType = true;
break; break;
} }

@ -24,6 +24,7 @@ import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.ReviewNode; import org.wso2.carbon.device.application.mgt.common.ReviewNode;
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.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ReviewDTO; import org.wso2.carbon.device.application.mgt.common.dto.ReviewDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
@ -49,6 +50,7 @@ import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/** /**
@ -72,7 +74,7 @@ public class ReviewManagerImpl implements ReviewManager {
} }
@Override @Override
public boolean addReview(ReviewWrapper reviewWrapper, String uuid) public boolean addReview(ReviewWrapper reviewWrapper, String uuid,boolean allowMultipleReviews)
throws ReviewManagementException, ApplicationManagementException { throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
@ -82,37 +84,47 @@ public class ReviewManagerImpl implements ReviewManager {
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
if (reviewWrapper.getRating() < 0) { if (reviewWrapper.getRating() <= 0) {
String msg = "You are trying to add invalid rating value as rating. Therefore please verify the request " String msg = "You are trying to add invalid rating value as rating. Therefore please verify the request "
+ "payload."; + "payload.";
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new BadRequestException(msg);
} }
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId); ApplicationDTO applicationDTO = this.applicationDAO.getApplicationByUUID(uuid, tenantId);
if (applicationReleaseDTO == null) { if (applicationDTO == null) {
String msg = "Couldn't find application release for the application UUID: " + uuid; String msg = "Couldn't find an application which has the application release of UUID: " + uuid;
log.error(msg); log.error(msg);
throw new NotFoundException(msg); throw new NotFoundException(msg);
} }
if (this.reviewDAO.haveUerReviewed(applicationReleaseDTO.getId(), username, tenantId)) { List<Integer> applicationReleaseIds = new ArrayList<>();
int associatedAppReleaseId = -1;
for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) {
if (applicationReleaseDTO.getUuid().equals(uuid)){
associatedAppReleaseId = applicationReleaseDTO.getId();
}
Integer id = applicationReleaseDTO.getId();
applicationReleaseIds.add(id);
}
if (!allowMultipleReviews && this.reviewDAO.hasUerReviewedApp(applicationReleaseIds, username, tenantId)) {
String msg = String msg =
"User " + username + " has already reviewed the application release which has UUID: " + uuid "User " + username + " has already reviewed the application of app release which has UUID: "
+ ". Hence you can't add another review for same application release. But you can update " + uuid + ". Hence you can't add another review for same application. But if you have "
+ "the review that you have already added for ths application release."; + "added review for same app release you can update the review that you have already "
+ "added for ths application.";
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new ForbiddenException(msg);
} }
Runnable task = () -> calculateRating(reviewWrapper.getRating(), -12345, uuid, tenantId);
new Thread(task).start();
ReviewDTO reviewDTO = reviewWrapperToDO(reviewWrapper); ReviewDTO reviewDTO = reviewWrapperToDTO(reviewWrapper);
reviewDTO.setUsername(username); reviewDTO.setUsername(username);
reviewDTO.setRootParentId(-1); reviewDTO.setRootParentId(-1);
reviewDTO.setImmediateParentId(-1); reviewDTO.setImmediateParentId(-1);
if (this.reviewDAO.addReview(reviewDTO, applicationReleaseDTO.getId(), tenantId)) { if (this.reviewDAO.addReview(reviewDTO, associatedAppReleaseId, tenantId)) {
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
Runnable task = () -> calculateRating(reviewWrapper.getRating(), -12345, uuid, tenantId);
new Thread(task).start();
return true; return true;
} }
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
@ -153,45 +165,52 @@ public class ReviewManagerImpl implements ReviewManager {
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
ReviewDTO parentReview = getReview(parentReviewId);
if (parentReview == null) {
String msg = "Couldn't find an review which has review ID: " + parentReviewId
+ " for application release which has UUID: " + uuid;
log.error(msg);
throw new NotFoundException(msg);
}
if (!parentReview.getReleaseUuid().equals(uuid)) {
String msg =
"Bad Request. You are trying to add reply comment for application release which has UUID: " + uuid
+ "," + " but parent review is associated with application release which has UUID: "
+ parentReview.getReleaseUuid() + ". Hence can't proceed this request further.";
log.error(msg);
throw new BadRequestException(msg);
}
ReviewDTO replyComment = reviewWrapperToDTO(reviewWrapper);
replyComment.setUsername(username);
replyComment.setRating(0);
replyComment.setImmediateParentId(parentReview.getId());
if (parentReview.getRootParentId() == -1) {
replyComment.setRootParentId(parentReview.getId());
} else {
replyComment.setRootParentId(parentReview.getRootParentId());
}
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId); ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find application release for the application UUID: " + uuid;
log.error(msg);
throw new NotFoundException(msg);
}
ReviewDTO parentReview = this.reviewDAO.getReview(applicationReleaseDTO.getId(), parentReviewId);
if (parentReview == null) {
String msg = "Couldn't find an review which has review ID: " + parentReviewId
+ " for application release which has UUID: " + uuid;
log.error(msg);
throw new NotFoundException(msg);
}
ReviewDTO replyComment = reviewWrapperToDO(reviewWrapper);
replyComment.setUsername(username);
replyComment.setRating(0);
replyComment.setImmediateParentId(parentReview.getId());
if (parentReview.getRootParentId() == -1) {
replyComment.setRootParentId(parentReview.getId());
} else {
replyComment.setRootParentId(parentReview.getRootParentId());
}
if (this.reviewDAO.addReview(replyComment, applicationReleaseDTO.getId(), tenantId)) { if (this.reviewDAO.addReview(replyComment, applicationReleaseDTO.getId(), tenantId)) {
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
return true; return true;
} }
ConnectionManagerUtil.rollbackDBTransaction();
return false; return false;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ReviewManagementException( throw new ReviewManagementException(
"DB Connection error occurs ,Review for application release with UUID: " + uuid + " is failed", "DB Connection error occurs ,Review for application release with UUID: " + uuid + " is failed", e);
e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
String msg = "DB transaction error occurred when adding reply comment for comment which has comment id: " String msg = "DB transaction error occurred when adding reply comment for comment which has comment id: "
+ parentReviewId; + parentReviewId;
log.error(msg); log.error(msg);
throw new ReviewManagementException(msg, e); throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException( throw new ReviewManagementException(
"Error occured while verifying whether application release is exists or not.", e); "Error occured while verifying whether application release is exists or not.", e);
} finally { } finally {
@ -199,7 +218,7 @@ public class ReviewManagerImpl implements ReviewManager {
} }
} }
private ReviewDTO reviewWrapperToDO(ReviewWrapper reviewWrapper){ private ReviewDTO reviewWrapperToDTO(ReviewWrapper reviewWrapper){
ReviewDTO reviewDTO = new ReviewDTO(); ReviewDTO reviewDTO = new ReviewDTO();
reviewDTO.setContent(reviewWrapper.getContent()); reviewDTO.setContent(reviewWrapper.getContent());
reviewDTO.setRating(reviewWrapper.getRating()); reviewDTO.setRating(reviewWrapper.getRating());
@ -229,50 +248,77 @@ public class ReviewManagerImpl implements ReviewManager {
return review; return review;
} }
private ReviewDTO getReview(int reviewId) throws ReviewManagementException {
try {
ConnectionManagerUtil.openDBConnection();
return this.reviewDAO.getReview(reviewId);
} catch (DBConnectionException e) {
String msg = "DB Connection error occurs updating reviewTmp with reviewTmp id " + reviewId + ".";
log.error(msg);
throw new ReviewManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override @Override
public boolean updateReview(ReviewWrapper updatingReview, int reviewId, String uuid, boolean isPriviledgedUser) public boolean updateReview(ReviewWrapper updatingReview, int reviewId, String uuid,
throws ReviewManagementException, ApplicationManagementException { boolean isPrivilegedUser) throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (log.isDebugEnabled()) { ReviewDTO reviewDTO = getReview(reviewId);
log.debug("Review updating request is received for the reviewTmp id " + reviewId); if (reviewDTO == null) {
String msg = "Couldn't found a review for review ID: " + reviewId;
log.error(msg);
throw new NotFoundException(msg);
}
if (!isPrivilegedUser && !username.equals(reviewDTO.getUsername())) {
String msg = "You are trying to update a review which is created by " + reviewDTO.getUsername()
+ ". Hence you are not permitted to update the review.";
log.error(msg);
throw new ForbiddenException(msg);
} }
try {
ConnectionManagerUtil.beginDBTransaction();
ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't found an application release for UUID: " + uuid;
log.error(msg);
throw new NotFoundException(msg);
}
ReviewDTO reviewDTO = this.reviewDAO.getReview(applicationReleaseDTO.getId(), reviewId);
if (reviewDTO == null) {
String msg =
"Couldn't found a review for application release which has UUID: " + uuid + " and review ID: "
+ reviewId;
log.error(msg);
throw new NotFoundException(msg);
}
if (!isPriviledgedUser && !username.equals(reviewDTO.getUsername())) {
String msg = "You are trying to update a review which is created by " + reviewDTO.getUsername()
+ ". Hence you are not permitted to update the review.";
log.error(msg);
throw new ForbiddenException(msg);
}
if (reviewDTO.getRootParentId() == -1 && reviewDTO.getImmediateParentId() == -1 boolean isActiveReview = true;
&& updatingReview.getRating() > 0 && updatingReview.getRating() != reviewDTO.getRating()) { //Handle Review
Runnable task = () -> calculateRating(updatingReview.getRating(), reviewDTO.getRating(), uuid, if (reviewDTO.getRootParentId() == -1 && reviewDTO.getImmediateParentId() == -1) {
tenantId); if (!reviewDTO.getReleaseUuid().equals(uuid)) {
isActiveReview = false;
if (!addReview(updatingReview, uuid, true)) {
String msg = "Review Updating Status: New review adding is failed.";
log.error(msg);
throw new ReviewManagementException(msg);
}
} else if (updatingReview.getRating() > 0 && updatingReview.getRating() != reviewDTO.getRating()) {
Runnable task = () -> ReviewManagerImpl.this
.calculateRating(updatingReview.getRating(), reviewDTO.getRating(), uuid, tenantId);
new Thread(task).start(); new Thread(task).start();
reviewDTO.setRating(updatingReview.getRating()); reviewDTO.setRating(updatingReview.getRating());
reviewDTO.setContent(updatingReview.getContent());
}
} else {
if (!reviewDTO.getReleaseUuid().equals(uuid)) {
String msg = "You are trying to update reply comment, but associated application release UUID and "
+ "requested app release UUID are mismatched.";
throw new BadRequestException(msg);
} }
reviewDTO.setContent(updatingReview.getContent()); reviewDTO.setContent(updatingReview.getContent());
if (this.reviewDAO.updateReview(reviewDTO, reviewId, tenantId) == 1){ }
return updateReviewInDB(reviewDTO, uuid, reviewId, isActiveReview, tenantId);
}
private boolean updateReviewInDB(ReviewDTO reviewDTO, String uuid, int reviewId, boolean isActiveReview,
int tenantId) throws ReviewManagementException, ApplicationManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
if (this.reviewDAO.updateReview(reviewDTO, reviewId, isActiveReview, tenantId) == 1) {
if (!isActiveReview) {
updateAppRating(uuid, tenantId);
}
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
return true; return true;
} }
ConnectionManagerUtil.rollbackDBTransaction();
return false; return false;
} catch (ReviewManagementDAOException e) { } catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
@ -283,10 +329,6 @@ public class ReviewManagerImpl implements ReviewManager {
String msg = "DB Connection error occurs updating reviewTmp with reviewTmp id " + reviewId + "."; String msg = "DB Connection error occurs updating reviewTmp with reviewTmp id " + reviewId + ".";
log.error(msg); log.error(msg);
throw new ReviewManagementException(msg, e); throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occured when getting application release data for application release UUID: " + uuid;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
String msg = "DB transaction error occurred when updating comment which has comment id: " + reviewId; String msg = "DB transaction error occurred when updating comment which has comment id: " + reviewId;
log.error(msg); log.error(msg);
@ -297,13 +339,11 @@ public class ReviewManagerImpl implements ReviewManager {
} }
@Override @Override
public PaginationResult getAllReviews(PaginationRequest request, String uuid) public PaginationResult getAllReleaseReviews(PaginationRequest request, String uuid)
throws ReviewManagementException, ApplicationManagementException { throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
PaginationResult paginationResult = new PaginationResult();
TreeMap<Integer, ReviewNode<ReviewDTO>> reviewTree = new TreeMap<>();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Get all reviewTmps of the application release uuid: " + uuid); log.debug("Get all release reviews of the application release uuid: " + uuid);
} }
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
@ -313,13 +353,115 @@ public class ReviewManagerImpl implements ReviewManager {
log.error(msg); log.error(msg);
throw new NotFoundException(msg); throw new NotFoundException(msg);
} }
List<ReviewDTO> reviewDTOs= this.reviewDAO.getAllReviews(releaseDTO.getId(), request, tenantId); return getReviewTree(this.reviewDAO.getAllActiveReleaseReviews(releaseDTO.getId(), request, tenantId));
for (ReviewDTO reviewDTO : reviewDTOs){ } catch (ReviewManagementDAOException e) {
throw new ReviewManagementException("Error occured while getting all reviews for application uuid: " + uuid,
e);
} catch (DBConnectionException e) {
throw new ReviewManagementException("Error occured while getting the DB connection.", e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred while getting application release details for application release UUId " + uuid;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public PaginationResult getAllAppReviews(PaginationRequest request, String uuid)
throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (log.isDebugEnabled()) {
log.debug("Get all reviews of the application release uuid: " + uuid);
}
List<Integer> applicationReleaseIds = getAppReleaseIdsByUUID(uuid, tenantId);
try {
ConnectionManagerUtil.openDBConnection();
return getReviewTree(this.reviewDAO.getAllActiveAppReviews(applicationReleaseIds, request, tenantId));
} catch (ReviewManagementDAOException e) {
String msg = "Error occured while getting all reviews for application which has an "
+ "application release of uuid: " + uuid;
log.error(msg);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occured while getting the DB connection to get app app reviews.";
log.error(msg);
throw new ReviewManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public PaginationResult getAllAppReviewsOfUser(PaginationRequest request, String uuid)
throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (log.isDebugEnabled()) {
log.debug("Get all reviews of the application release uuid: " + uuid);
}
List<Integer> applicationReleaseIds = getAppReleaseIdsByUUID(uuid, tenantId);
try {
ConnectionManagerUtil.openDBConnection();
List<ReviewDTO> reviewDtos = this.reviewDAO
.getAllActiveAppReviewsOfUser(applicationReleaseIds, request, username, tenantId);
if (!reviewDtos.isEmpty() && reviewDtos.size() > 1) {
String msg = "User " + username + " can't have more than active application review for application which"
+ " has application release of UUID: " + uuid;
log.error(msg);
throw new ApplicationManagementException(msg);
}
return getReviewTree(reviewDtos);
} catch (ReviewManagementDAOException e) {
throw new ReviewManagementException("Error occured while getting all reviews for application which has an "
+ "application release of uuid: " + uuid,
e);
} catch (DBConnectionException e) {
throw new ReviewManagementException("Error occured while getting the DB connection.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
private List<Integer> getAppReleaseIdsByUUID(String uuid, int tenantId)
throws ReviewManagementException, ApplicationManagementException {
try {
ConnectionManagerUtil.openDBConnection();
ApplicationDTO applicationDTO = this.applicationDAO.getApplicationByUUID(uuid, tenantId);
if (applicationDTO == null) {
String msg = "Couldn't find an application which has the application release of UUID: " + uuid;
log.error(msg);
throw new NotFoundException(msg);
}
return applicationDTO.getApplicationReleaseDTOs().stream().map(ApplicationReleaseDTO::getId)
.collect(Collectors.toList());
} catch (DBConnectionException e) {
String msg = "Error occured while getting the DB connection to get application which has application release"
+ " of UUID: " + uuid;
log.error(msg);
throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred while getting application release details for application which has an "
+ "application release of UUID " + uuid;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
private PaginationResult getReviewTree(List<ReviewDTO> reviewDTOs) throws ReviewManagementException {
TreeMap<Integer, ReviewNode<ReviewDTO>> reviewTree = new TreeMap<>();
PaginationResult paginationResult = new PaginationResult();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
for (ReviewDTO reviewDTO : reviewDTOs) {
ReviewNode<ReviewDTO> rootNode = new ReviewNode<>(reviewDTO); ReviewNode<ReviewDTO> rootNode = new ReviewNode<>(reviewDTO);
reviewTree.put(reviewDTO.getId(), rootNode); reviewTree.put(reviewDTO.getId(), rootNode);
List<ReviewDTO> replyComments = this.reviewDAO.getReplyComments(reviewDTO.getId(), tenantId); List<ReviewDTO> replyComments = this.reviewDAO.getReplyComments(reviewDTO.getId(), tenantId);
replyComments.sort(Comparator.comparing(ReviewDTO::getId)); replyComments.sort(Comparator.comparing(ReviewDTO::getId));
for (ReviewDTO reply : replyComments){ for (ReviewDTO reply : replyComments) {
reviewTree.put(reply.getRootParentId(), reviewTree.put(reply.getRootParentId(),
findAndSetChild(reviewTree.get(reply.getRootParentId()), reply)); findAndSetChild(reviewTree.get(reply.getRootParentId()), reply));
} }
@ -327,7 +469,7 @@ public class ReviewManagerImpl implements ReviewManager {
int numOfReviews = reviewTree.size(); int numOfReviews = reviewTree.size();
List<Review> results = new ArrayList<>(); List<Review> results = new ArrayList<>();
for (ReviewNode<ReviewDTO> reviewNode : reviewTree.values()){ for (ReviewNode<ReviewDTO> reviewNode : reviewTree.values()) {
results.add(constructReviewResponse(null, reviewNode)); results.add(constructReviewResponse(null, reviewNode));
} }
paginationResult.setData(new ArrayList<>(results)); paginationResult.setData(new ArrayList<>(results));
@ -335,16 +477,8 @@ public class ReviewManagerImpl implements ReviewManager {
paginationResult.setRecordsTotal(numOfReviews); paginationResult.setRecordsTotal(numOfReviews);
return paginationResult; return paginationResult;
} catch (ReviewManagementDAOException e) { } catch (ReviewManagementDAOException e) {
throw new ReviewManagementException("Error occured while getting all reviewTmps for application uuid: " + uuid, throw new ReviewManagementException("Error occured while getting all reply comments for given review list",
e); e);
} catch (DBConnectionException e) {
throw new ReviewManagementException("Error occured while getting the DB connection.", e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred while getting application release details for application release UUId " + uuid;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
} }
} }
@ -406,19 +540,18 @@ public class ReviewManagerImpl implements ReviewManager {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId); ReviewDTO existingReview = this.reviewDAO.getReview(reviewId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't found an application release for UUID: " + uuid
+ " to delete review which has review ID: " + reviewId;
log.error(msg);
throw new NotFoundException(msg);
}
ReviewDTO existingReview = this.reviewDAO.getReview(applicationReleaseDTO.getId(), reviewId);
if (existingReview == null) { if (existingReview == null) {
String msg = "Cannot delete a non-existing review for the application with review id" + reviewId; String msg = "Cannot delete a non-existing review for the application with review id" + reviewId;
log.error(msg); log.error(msg);
throw new NotFoundException(msg); throw new NotFoundException(msg);
} }
if (!existingReview.getReleaseUuid().equals(uuid)){
String msg = "You are trying to delete a review which is not associated with application release which "
+ "has UUID: " + uuid;
log.error(msg);
throw new ForbiddenException(msg);
}
if (!isPriviledgedUser && !username.equals(existingReview.getUsername())) { if (!isPriviledgedUser && !username.equals(existingReview.getUsername())) {
String msg = "You are trying to delete a comment that is owned by you. Hence you are not permitted to " String msg = "You are trying to delete a comment that is owned by you. Hence you are not permitted to "
+ "delete the review"; + "delete the review";
@ -433,7 +566,7 @@ public class ReviewManagerImpl implements ReviewManager {
Runnable task = () -> calculateRating(0, existingReview.getRating(), uuid, tenantId); Runnable task = () -> calculateRating(0, existingReview.getRating(), uuid, tenantId);
new Thread(task).start(); new Thread(task).start();
} else { } else {
ReviewDTO rootReview = this.reviewDAO.getReview(existingReview.getRootParentId()); ReviewDTO rootReview = this.reviewDAO.getReview(existingReview.getRootParentId(), tenantId);
List<ReviewDTO> replyComments = this.reviewDAO.getReplyComments(rootReview.getId(), tenantId); List<ReviewDTO> replyComments = this.reviewDAO.getReplyComments(rootReview.getId(), tenantId);
ReviewNode<ReviewDTO> reviewNode = new ReviewNode<>(rootReview); ReviewNode<ReviewDTO> reviewNode = new ReviewNode<>(rootReview);
@ -460,59 +593,97 @@ public class ReviewManagerImpl implements ReviewManager {
String msg = "Error occurred when handleing transaction to delete application reviews."; String msg = "Error occurred when handleing transaction to delete application reviews.";
log.error(msg); log.error(msg);
throw new ReviewManagementException(msg, e); throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error Occurred when getting application release data for application release UUID: " + uuid;
log.error(msg);
throw new ReviewManagementException(msg, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
@Override public Rating getRating(String appReleaseUuuid) throws ReviewManagementException, ApplicationManagementException { @Override
public Rating getAppReleaseRating(String appReleaseUuid) throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
Rating rating = this.applicationReleaseDAO.getRating(appReleaseUuuid, tenantId); Rating rating = this.applicationReleaseDAO.getRating(appReleaseUuid, tenantId);
if (rating == null) { if (rating == null) {
throw new NotFoundException( throw new NotFoundException(
"Couldn't find rating for application release UUID: " + appReleaseUuuid "Couldn't find rating for application release UUID: " + appReleaseUuid
+ ". Please check the existence of the application release"); + ". Please check the existence of the application release");
} }
List<Integer> ratingValues = this.reviewDAO.getAllRatingValues(appReleaseUuuid, tenantId); List<Integer> ratingValues = this.reviewDAO.getAllAppReleaseRatingValues(appReleaseUuid, tenantId);
TreeMap<Integer, Integer> ratingVariety = new TreeMap<>(); rating.setRatingVariety(constructRatingVariety(ratingValues));
ratingValues.forEach(ratingVal -> {
if (ratingVariety.containsKey(ratingVal)) {
ratingVariety.replace(ratingVal, ratingVariety.get(ratingVal) + 1);
} else {
ratingVariety.put(ratingVal, 1);
}
});
IntStream.rangeClosed(1, Constants.MAX_RATING).filter(i -> !ratingVariety.containsKey(i))
.forEach(i -> ratingVariety.put(i, 0));
rating.setRatingVariety(ratingVariety);
return rating; return rating;
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException( throw new ReviewManagementException(
"Error occured while getting the rating value of the application release uuid: " + appReleaseUuuid, "Error occured while getting the rating value of the application release uuid: " + appReleaseUuid,
e); e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException( throw new ReviewManagementException(
"DB Connection error occured while getting the rating value of the application release uuid: " "DB Connection error occured while getting the rating value of the application release uuid: "
+ appReleaseUuuid, e); + appReleaseUuid, e);
} catch (ReviewManagementDAOException e) { } catch (ReviewManagementDAOException e) {
throw new ReviewManagementException( throw new ReviewManagementException(
"Error occured while getting all rating values for the application release UUID: " "Error occured while getting all rating values for the application release UUID: "
+ appReleaseUuuid, e); + appReleaseUuid, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public Rating getAppRating(String appReleaseUuid) throws ReviewManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
ConnectionManagerUtil.openDBConnection();
ApplicationDTO applicationDTO = this.applicationDAO.getApplicationByUUID(appReleaseUuid, tenantId);
if (applicationDTO == null) {
String msg = "Couldn't found an application for application release UUID: " + appReleaseUuid;
log.error(msg);
throw new NotFoundException(msg);
}
List<String> uuids = applicationDTO.getApplicationReleaseDTOs().stream().map(ApplicationReleaseDTO::getUuid)
.collect(Collectors.toList());
List<Integer> ratingValues = this.reviewDAO.getAllAppRatingValues(uuids, tenantId);
Rating rating = new Rating();
rating.setRatingValue(applicationDTO.getAppRating());
rating.setNoOfUsers(ratingValues.size());
rating.setRatingVariety(constructRatingVariety(ratingValues));
return rating;
} catch (DBConnectionException e) {
String msg = "DB Connection error occured while getting app rating of the application which has application "
+ "release for uuid: " + appReleaseUuid;
log.error(msg);
throw new ReviewManagementException(msg, e);
}catch (ApplicationManagementDAOException e) {
String msg = "Error occured while getting the application DTO for the application release uuid: " + appReleaseUuid;
log.error(msg);
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
String msg ="Error occured while getting all rating values of application which has the application release "
+ "for UUID: " + appReleaseUuid;
log.error(msg);
throw new ReviewManagementException(msg, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
private TreeMap<Integer, Integer> constructRatingVariety(List<Integer> ratingValues) {
TreeMap<Integer, Integer> ratingVariety = new TreeMap<>();
ratingValues.forEach(ratingVal -> {
if (ratingVariety.containsKey(ratingVal)) {
ratingVariety.replace(ratingVal, ratingVariety.get(ratingVal) + 1);
} else {
ratingVariety.put(ratingVal, 1);
}
});
IntStream.rangeClosed(1, Constants.MAX_RATING).filter(i -> !ratingVariety.containsKey(i))
.forEach(i -> ratingVariety.put(i, 0));
return ratingVariety;
}
private void calculateRating(int newRatingVal, int oldRatingVal, String uuid, int tenantId) { private void calculateRating(int newRatingVal, int oldRatingVal, String uuid, int tenantId) {
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
@ -544,14 +715,7 @@ public class ReviewManagerImpl implements ReviewManager {
} }
this.applicationReleaseDAO.updateRatingValue(uuid, updatedRating, numOfUsers); this.applicationReleaseDAO.updateRatingValue(uuid, updatedRating, numOfUsers);
updateAppRating(uuid, tenantId);
List<Double> releaseRatings = this.applicationReleaseDAO.getReleaseRatings(uuid, tenantId);
double appAverageRatingValue = 0.0;
double sumOfRatings = releaseRatings.stream().mapToDouble(rt -> rt).sum();
if (sumOfRatings != 0.0) {
appAverageRatingValue = sumOfRatings / releaseRatings.size();
}
this.applicationDAO.updateApplicationRating(uuid, appAverageRatingValue, tenantId);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} }
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
@ -564,8 +728,31 @@ public class ReviewManagerImpl implements ReviewManager {
log.error( log.error(
"Transaction error occured while updated the rating value of the application release UUID: " + uuid "Transaction error occured while updated the rating value of the application release UUID: " + uuid
+ " can not get.", e); + " can not get.", e);
} catch (ApplicationManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
log.error("Error occured while updating app rating value which has application release for UUID: " + uuid,
e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
private void updateAppRating(String uuid, int tenantId) throws ApplicationManagementException {
try {
ApplicationDTO applicationDTO = this.applicationDAO.getApplicationByUUID(uuid, tenantId);
List<String> uuids = applicationDTO.getApplicationReleaseDTOs().stream().map(ApplicationReleaseDTO::getUuid)
.collect(Collectors.toList());
List<Integer> appRatings = this.reviewDAO.getAllAppRatingValues(uuids, tenantId);
double appAverageRatingValue = appRatings.stream().mapToDouble(x -> x).average().orElse(Double.NaN);
this.applicationDAO.updateApplicationRating(uuid, appAverageRatingValue, tenantId);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred when getting application data or updating application rating value.";
log.error(msg);
throw new ApplicationManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
String msg = "Error occurred when getting application rating values";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
}
} }

@ -388,7 +388,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred when adding subscription data for application release UUID: " String msg = "Error occurred when adding subscription data for application release ID: "
+ applicationReleaseId; + applicationReleaseId;
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
@ -398,7 +398,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
String msg = String msg =
"SQL Error occurred when adding new device subscription to application release which has UUID: " "SQL Error occurred when adding new device subscription to application release which has ID: "
+ applicationReleaseId; + applicationReleaseId;
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);

@ -190,13 +190,13 @@ public class APIUtil {
try { try {
deviceTypes = DAOUtil.getDeviceManagementService().getDeviceTypes(); deviceTypes = DAOUtil.getDeviceManagementService().getDeviceTypes();
if(deviceTypeAttr instanceof String){ if (deviceTypeAttr instanceof String) {
for (DeviceType dt : deviceTypes) { for (DeviceType dt : deviceTypes) {
if (dt.getName().equals(deviceTypeAttr)) { if (dt.getName().equals(deviceTypeAttr)) {
return dt; return dt;
} }
} }
} else if (deviceTypeAttr instanceof Integer){ } else if (deviceTypeAttr instanceof Integer) {
for (DeviceType dt : deviceTypes) { for (DeviceType dt : deviceTypes) {
if (dt.getId() == (Integer) deviceTypeAttr) { if (dt.getId() == (Integer) deviceTypeAttr) {
return dt; return dt;

@ -234,6 +234,8 @@ public class DAOUtil {
reviewDTO.setImmediateParentId(rs.getInt("IMMEDIATE_PARENT_ID")); reviewDTO.setImmediateParentId(rs.getInt("IMMEDIATE_PARENT_ID"));
reviewDTO.setUsername(rs.getString("USERNAME")); reviewDTO.setUsername(rs.getString("USERNAME"));
reviewDTO.setRating(rs.getInt("RATING")); reviewDTO.setRating(rs.getInt("RATING"));
reviewDTO.setReleaseUuid(rs.getString("UUID"));
reviewDTO.setReleaseVersion(rs.getString("VERSION"));
reviewDTOs.add(reviewDTO); reviewDTOs.add(reviewDTO);
} }
return reviewDTOs; return reviewDTOs;

@ -92,13 +92,13 @@ public interface ReviewManagementAPI {
String SCOPE = "scope"; String SCOPE = "scope";
@GET @GET
@Path("/{uuid}") @Path("/release/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "get reviews", value = "get app release reviews",
notes = "Get all reviews", notes = "Get all app release reviews",
tags = "Store Management", tags = "Store Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ -111,7 +111,7 @@ public interface ReviewManagementAPI {
value = { value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully retrieved reviews.", message = "OK. \n Successfully retrieved app release reviews.",
response = PaginationResult.class, response = PaginationResult.class,
responseContainer = "PaginationResult"), responseContainer = "PaginationResult"),
@ApiResponse( @ApiResponse(
@ -123,7 +123,7 @@ public interface ReviewManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response getAllReviews( Response getAllReleaseReviews(
@ApiParam( @ApiParam(
name="uuid", name="uuid",
value="uuid of the application release.", value="uuid of the application release.",
@ -140,6 +140,106 @@ public interface ReviewManagementAPI {
defaultValue = "20") defaultValue = "20")
@QueryParam("limit") int limit); @QueryParam("limit") int limit);
@GET
@Path("/app/user/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get app reviews",
notes = "Get all app reviews",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:review:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved app reviews.",
response = PaginationResult.class,
responseContainer = "PaginationResult"),
@ApiResponse(
code = 404,
message = "Not Found. \n Not found an application release associated with requested "
+ "UUID."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the review list.",
response = ErrorResponse.class)
})
Response getUserReviews(
@ApiParam(
name="uuid",
value="uuid of the application release.",
required = true)
@PathParam("uuid") String uuid,
@ApiParam(
name="offset",
value="Starting review number.",
defaultValue = "0")
@QueryParam("offSet") int offSet,
@ApiParam(
name="limit",
value = "Limit of paginated reviews",
defaultValue = "20")
@QueryParam("limit") int limit);
@GET
@Path("/app/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get app reviews",
notes = "Get all app reviews",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:review:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved app reviews.",
response = PaginationResult.class,
responseContainer = "PaginationResult"),
@ApiResponse(
code = 404,
message = "Not Found. \n Not found an application release associated with requested "
+ "UUID."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the review list.",
response = ErrorResponse.class)
})
Response getAllAppReviews(
@ApiParam(
name="uuid",
value="uuid of the application release.",
required = true)
@PathParam("uuid") String uuid,
@ApiParam(
name="offset",
value="Starting review number.",
defaultValue = "0")
@QueryParam("offSet") int offSet,
@ApiParam(
name="limit",
value = "Limit of paginated reviews",
defaultValue = "20")
@QueryParam("limit") int limit);
@POST @POST
@Path("/{uuid}") @Path("/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -342,7 +442,7 @@ public interface ReviewManagementAPI {
@PathParam("reviewId") int reviewId); @PathParam("reviewId") int reviewId);
@GET @GET
@Path("/{uuid}/rating") @Path("/{uuid}/release-rating")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -374,11 +474,52 @@ public interface ReviewManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response getRating( Response getAppReleaseRating(
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "uuid of the application release", value = "uuid of the application release",
required = true) required = true)
@PathParam("uuid") @PathParam("uuid")
String uuid); String uuid);
@GET
@Path("/{uuid}/app-rating")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get app ratings",
notes = "Get all app ratings",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:review:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved ratings.",
response = List.class,
responseContainer = "List"),
@ApiResponse(
code = 404,
message = "Not Found. \n No Application found which has application release of UUID.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting ratings",
response = ErrorResponse.class)
})
Response getAppRating(
@ApiParam(
name = "uuid",
value = "uuid of the application release",
required = true)
@PathParam("uuid")
String uuid);
} }

@ -55,15 +55,15 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@Override @Override
@GET @GET
@Path("/{uuid}") @Path("/release/{uuid}")
public Response getAllReviews( public Response getAllReleaseReviews(
@PathParam("uuid") String uuid, @PathParam("uuid") String uuid,
@DefaultValue("0") @QueryParam("offset") int offSet, @DefaultValue("0") @QueryParam("offset") int offSet,
@DefaultValue("20") @QueryParam("limit") int limit) { @DefaultValue("20") @QueryParam("limit") int limit) {
ReviewManager reviewManager = APIUtil.getReviewManager(); ReviewManager reviewManager = APIUtil.getReviewManager();
PaginationRequest request = new PaginationRequest(offSet, limit); PaginationRequest request = new PaginationRequest(offSet, limit);
try { try {
PaginationResult paginationResult = reviewManager.getAllReviews(request, uuid); PaginationResult paginationResult = reviewManager.getAllReleaseReviews(request, uuid);
return Response.status(Response.Status.OK).entity(paginationResult).build(); return Response.status(Response.Status.OK).entity(paginationResult).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Couldn't find an application release for UUID: " + uuid; String msg = "Couldn't find an application release for UUID: " + uuid;
@ -80,6 +80,62 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
} }
} }
@Override
@GET
@Path("/app/user/{uuid}")
public Response getUserReviews(
@PathParam("uuid") String uuid,
@DefaultValue("0") @QueryParam("offset") int offSet,
@DefaultValue("20") @QueryParam("limit") int limit) {
ReviewManager reviewManager = APIUtil.getReviewManager();
PaginationRequest request = new PaginationRequest(offSet, limit);
try {
PaginationResult paginationResult = reviewManager.getAllAppReviewsOfUser(request, uuid);
return Response.status(Response.Status.OK).entity(paginationResult).build();
} catch (NotFoundException e) {
String msg = "Couldn't find an application which has application release of UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ReviewManagementException e) {
String msg = "Error occurred while retrieving reviews for application which has application release for "
+ "UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while retrieving application release details for application UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@GET
@Path("/app/{uuid}")
public Response getAllAppReviews(
@PathParam("uuid") String uuid,
@DefaultValue("0") @QueryParam("offset") int offSet,
@DefaultValue("20") @QueryParam("limit") int limit) {
ReviewManager reviewManager = APIUtil.getReviewManager();
PaginationRequest request = new PaginationRequest(offSet, limit);
try {
PaginationResult paginationResult = reviewManager.getAllAppReviews(request, uuid);
return Response.status(Response.Status.OK).entity(paginationResult).build();
} catch (NotFoundException e) {
String msg = "Couldn't find an application which has application release of UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ReviewManagementException e) {
String msg = "Error occurred while retrieving reviews for application which has application release for "
+ "UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while retrieving application release details for application UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override @Override
@POST @POST
@Consumes("application/json") @Consumes("application/json")
@ -89,7 +145,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@PathParam("uuid") String uuid) { @PathParam("uuid") String uuid) {
ReviewManager reviewManager = APIUtil.getReviewManager(); ReviewManager reviewManager = APIUtil.getReviewManager();
try { try {
boolean isReviewCreated = reviewManager.addReview(reviewWrapper, uuid); boolean isReviewCreated = reviewManager.addReview(reviewWrapper, uuid, false);
if (isReviewCreated) { if (isReviewCreated) {
return Response.status(Response.Status.CREATED).entity(reviewWrapper).build(); return Response.status(Response.Status.CREATED).entity(reviewWrapper).build();
} else { } else {
@ -227,13 +283,13 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@Override @Override
@GET @GET
@Path("/{uuid}/rating") @Path("/{uuid}/release-rating")
public Response getRating( public Response getAppReleaseRating(
@PathParam("uuid") String uuid) { @PathParam("uuid") String uuid) {
ReviewManager reviewManager = APIUtil.getReviewManager(); ReviewManager reviewManager = APIUtil.getReviewManager();
Rating rating; Rating rating;
try { try {
rating = reviewManager.getRating(uuid); rating = reviewManager.getAppReleaseRating(uuid);
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Couldn't found an application release for UUID: " + uuid; String msg = "Couldn't found an application release for UUID: " + uuid;
log.error(msg, e); log.error(msg, e);
@ -246,4 +302,25 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
return Response.status(Response.Status.OK).entity(rating).build(); return Response.status(Response.Status.OK).entity(rating).build();
} }
@Override
@GET
@Path("/{uuid}/app-rating")
public Response getAppRating(
@PathParam("uuid") String uuid) {
ReviewManager reviewManager = APIUtil.getReviewManager();
Rating rating;
try {
rating = reviewManager.getAppRating(uuid);
} catch (NotFoundException e) {
String msg = "Couldn't found an application for application release UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ReviewManagementException | ApplicationManagementException e) {
String msg = "Error occured while getting review data for application release UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.OK).entity(rating).build();
}
} }

@ -58,7 +58,7 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
// @Test // @Test
// public void testGetAllCommentsWithValidDetails() throws Exception { // public void testGetAllCommentsWithValidDetails() throws Exception {
// PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); // PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
// Response response = this.commentManagementAPI.getAllReviews("a", 1, 2); // Response response = this.commentManagementAPI.getAllReleaseReviews("a", 1, 2);
// Assert.assertNotNull(response, "The response object is null."); // Assert.assertNotNull(response, "The response object is null.");
// Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), // Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
// "The response status should be 200."); // "The response status should be 200.");
@ -69,8 +69,8 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
// public void testGetAllCommentsInternalError() throws Exception { // public void testGetAllCommentsInternalError() throws Exception {
// PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); // PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
// Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager) // Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager)
// .getAllReviews(Mockito.any(), Mockito.anyString()); // .getAllReleaseReviews(Mockito.any(), Mockito.anyString());
// Response response = this.commentManagementAPI.getAllReviews("a", 1, 4); // Response response = this.commentManagementAPI.getAllReleaseReviews("a", 1, 4);
// Assert.assertNotNull(response, "The response object is null."); // Assert.assertNotNull(response, "The response object is null.");
// Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), // Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "The response status should be 500."); // "The response status should be 500.");
@ -80,7 +80,7 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
// @Test // @Test
// public void testGetAllCommentsNotFoundError() throws Exception { // public void testGetAllCommentsNotFoundError() throws Exception {
// PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); // PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
// Response response = this.commentManagementAPI.getAllReviews(null, 1, 3); // Response response = this.commentManagementAPI.getAllReleaseReviews(null, 1, 3);
// Assert.assertNotNull(response, "The response object is null."); // Assert.assertNotNull(response, "The response object is null.");
// Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), // Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
// "The response status should be 404."); // "The response status should be 404.");
@ -192,7 +192,7 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
// @Test // @Test
// public void testGetStars() throws Exception { // public void testGetStars() throws Exception {
// PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); // PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
// Response response = this.commentManagementAPI.getRating("a"); // Response response = this.commentManagementAPI.getAppReleaseRating("a");
// Assert.assertNotNull(response, "The response object is null."); // Assert.assertNotNull(response, "The response object is null.");
// Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), // Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
// "The response status should be 200."); // "The response status should be 200.");
@ -202,9 +202,9 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
// @Test // @Test
// public void testGetStarsCommentError() throws Exception { // public void testGetStarsCommentError() throws Exception {
// PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); // PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
// Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString())) // Mockito.when(this.commentManagementAPI.getAppReleaseRating(Mockito.anyString()))
// .thenThrow(new ReviewManagementException()); // .thenThrow(new ReviewManagementException());
// Response response = this.commentManagementAPI.getRating("a"); // Response response = this.commentManagementAPI.getAppReleaseRating("a");
// Assert.assertNotNull(response, "The response object is null."); // Assert.assertNotNull(response, "The response object is null.");
// Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), // Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "The response status should be 500."); // "The response status should be 500.");
@ -214,9 +214,9 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
// @Test // @Test
// public void testGetStarsApplicationError() throws Exception { // public void testGetStarsApplicationError() throws Exception {
// PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager); // PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
// Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString())) // Mockito.when(this.commentManagementAPI.getAppReleaseRating(Mockito.anyString()))
// .thenThrow(new ApplicationManagementException()); // .thenThrow(new ApplicationManagementException());
// Response response = this.commentManagementAPI.getRating("a"); // Response response = this.commentManagementAPI.getAppReleaseRating("a");
// Assert.assertNotNull(response, "The response object is null."); // Assert.assertNotNull(response, "The response object is null.");
// Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), // Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "The response status should be 500."); // "The response status should be 500.");

@ -61,6 +61,7 @@ CREATE TABLE IF NOT EXISTS AP_APP_REVIEW(
MODIFIED_AT TIMESTAMP NOT NULL, MODIFIED_AT TIMESTAMP NOT NULL,
RATING INTEGER NULL, RATING INTEGER NULL,
USERNAME VARCHAR(45) NOT NULL, USERNAME VARCHAR(45) NOT NULL,
ACTIVE_REVIEW BOOLEAN NOT NULL DEFAULT TRUE,
AP_APP_RELEASE_ID INTEGER NOT NULL, AP_APP_RELEASE_ID INTEGER NOT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_AP_APP_COMMENT_AP_APP_RELEASE1 CONSTRAINT fk_AP_APP_COMMENT_AP_APP_RELEASE1

Loading…
Cancel
Save