diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/APIUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/APIUtil.java index 8be02fc146..6e2c1360f8 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/APIUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/APIUtil.java @@ -22,18 +22,18 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.application.mgt.api.beans.ErrorResponse; +import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; +import org.wso2.carbon.device.application.mgt.common.services.PlatformManager; +import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; -import org.wso2.carbon.device.application.mgt.common.services.CategoryManager; -import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager; -import org.wso2.carbon.device.application.mgt.common.services.PlatformManager; -import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; +import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager; +import org.wso2.carbon.device.application.mgt.common.services.CategoryManager; import javax.ws.rs.core.Response; - /** * Holds util methods required for Application-Mgt API component. */ @@ -41,66 +41,36 @@ public class APIUtil { private static Log log = LogFactory.getLog(APIUtil.class); - private static ApplicationManager applicationManager; - private static PlatformManager platformManager; - private static LifecycleStateManager lifecycleStateManager; - private static ApplicationReleaseManager applicationReleaseManager; - private static ApplicationStorageManager applicationStorageManager; - private static SubscriptionManager subscriptionManager; - private static PlatformStorageManager platformStorageManager; - private static CategoryManager categoryManager; - public static ApplicationManager getApplicationManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ApplicationManager applicationManager = (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null); if (applicationManager == null) { - synchronized (APIUtil.class) { - if (applicationManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - applicationManager = - (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null); - if (applicationManager == null) { - String msg = "Application Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Application Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } - return applicationManager; } public static PlatformManager getPlatformManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + PlatformManager platformManager = (PlatformManager) ctx.getOSGiService(PlatformManager.class, null); if (platformManager == null) { - synchronized (APIUtil.class) { - if (platformManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - platformManager = - (PlatformManager) ctx.getOSGiService(PlatformManager.class, null); - if (platformManager == null) { - String msg = "Platform Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Platform Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } return platformManager; } public static LifecycleStateManager getLifecycleStateManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + LifecycleStateManager lifecycleStateManager = (LifecycleStateManager) ctx + .getOSGiService(LifecycleStateManager.class, null); if (lifecycleStateManager == null) { - synchronized (APIUtil.class) { - if (lifecycleStateManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - lifecycleStateManager = - (LifecycleStateManager) ctx.getOSGiService(LifecycleStateManager.class, null); - if (lifecycleStateManager == null) { - String msg = "Lifecycle Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Lifecycle Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } return lifecycleStateManager; } @@ -111,41 +81,30 @@ public class APIUtil { * @return ApplicationRelease Manager instance in the current osgi context. */ public static ApplicationReleaseManager getApplicationReleaseManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ApplicationReleaseManager applicationReleaseManager = (ApplicationReleaseManager) ctx + .getOSGiService(ApplicationReleaseManager.class, null); if (applicationReleaseManager == null) { - synchronized (APIUtil.class) { - if (applicationReleaseManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - applicationReleaseManager = (ApplicationReleaseManager) ctx - .getOSGiService(ApplicationReleaseManager.class, null); - if (applicationReleaseManager == null) { - String msg = "Application Release Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Application Release Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } return applicationReleaseManager; } /** * To get the Application Storage Manager from the osgi context. + * * @return ApplicationStoreManager instance in the current osgi context. */ public static ApplicationStorageManager getApplicationStorageManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ApplicationStorageManager applicationStorageManager = (ApplicationStorageManager) ctx + .getOSGiService(ApplicationStorageManager.class, null); if (applicationStorageManager == null) { - synchronized (APIUtil.class) { - if (applicationStorageManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - applicationStorageManager = (ApplicationStorageManager) ctx - .getOSGiService(ApplicationStorageManager.class, null); - if (applicationStorageManager == null) { - String msg = "Application Storage Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Application Storage Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } return applicationStorageManager; } @@ -156,42 +115,29 @@ public class APIUtil { * @return PlatformStoreManager instance in the current osgi context. */ public static PlatformStorageManager getPlatformStorageManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + PlatformStorageManager platformStorageManager = (PlatformStorageManager) ctx + .getOSGiService(PlatformStorageManager.class, null); if (platformStorageManager == null) { - synchronized (APIUtil.class) { - if (platformStorageManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - platformStorageManager = (PlatformStorageManager) ctx - .getOSGiService(PlatformStorageManager.class, null); - if (platformStorageManager == null) { - String msg = "Platform Storage Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Platform Storage Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } return platformStorageManager; } - /** * To get the Category Manager from the osgi context. * * @return CategoryManager instance in the current osgi context. */ public static CategoryManager getCategoryManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + CategoryManager categoryManager = (CategoryManager) ctx.getOSGiService(CategoryManager.class, null); if (categoryManager == null) { - synchronized (APIUtil.class) { - if (categoryManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - categoryManager = (CategoryManager) ctx.getOSGiService(CategoryManager.class, null); - if (categoryManager == null) { - String msg = "Category Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Category Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } return categoryManager; } @@ -212,24 +158,35 @@ public class APIUtil { /** * To get the Subscription Manager from the osgi context. + * * @return SubscriptionManager instance in the current osgi context. */ public static SubscriptionManager getSubscriptionManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + SubscriptionManager subscriptionManager = (SubscriptionManager) ctx + .getOSGiService(SubscriptionManager.class, null); if (subscriptionManager == null) { - synchronized (APIUtil.class) { - if (subscriptionManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - subscriptionManager = - (SubscriptionManager) ctx.getOSGiService(SubscriptionManager.class, null); - if (subscriptionManager == null) { - String msg = "Subscription Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } + String msg = "Subscription Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } - return subscriptionManager; } + + /** + * To get the Comment Manager from the osgi context. + * + * @return CommentsManager instance in the current osgi context. + */ + + public static CommentsManager getCommentsManager() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + CommentsManager commentsManager = (CommentsManager) ctx.getOSGiService(CommentsManager.class, null); + if (commentsManager == null) { + String msg = "Comments Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return commentsManager; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/CommentManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/CommentManagementAPI.java new file mode 100644 index 0000000000..87a391758a --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/CommentManagementAPI.java @@ -0,0 +1,416 @@ +/* + * 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.api.services; + +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.Api; +import io.swagger.annotations.Info; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Tag; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.application.mgt.api.beans.ErrorResponse; +import org.wso2.carbon.device.application.mgt.common.Comment; +import javax.validation.Valid; +import javax.ws.rs.Path; +import javax.ws.rs.Consumes; +import javax.ws.rs.PUT; +import javax.ws.rs.GET; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.Produces; +import javax.ws.rs.POST; +import javax.ws.rs.DELETE; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + + /** + * APIs to handle comment management related tasks. + */ + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "Store Management Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "CommentManagementService"), + @ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/comments"), + }) + } + ), + tags = { + @Tag(name = "store_management", description = "Comment Management related " + + "APIs") + } +) +@Scopes( + scopes = { + @Scope( + name = "Get Comments Details", + description = "Get comments details", + key = "perm:comment:get", + permissions = {"/device-mgt/comment/get"} + ), + @Scope( + name = "Add a Comment", + description = "Add a comment", + key = "perm:comment:add", + permissions = {"/device-mgt/comment/add"} + ), + @Scope( + name = "Update a Comment", + description = "Update a Comment", + key = "perm:comment:update", + permissions = {"/device-mgt/comment/update"} + ), + + @Scope( + name = "Delete a Comment", + description = "Delete a comment", + key = "perm:comment:delete", + permissions = {"/device-mgt/comment/delete"} + ), + } +) + +@Path("/comments") +@Api(value = "Comments Management", description = "This API carries all comments management related operations " + + "such as get all the comments, add comment, etc.") +@Produces(MediaType.APPLICATION_JSON) + +public interface CommentManagementAPI { + String SCOPE = "scope"; + + @GET + @Path("/{uuid}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get comments", + notes = "Get all comments", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:store:get") + }) + } + ) + + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved comments.", + response = List.class, + responseContainer = "List"), + @ApiResponse( + code = 404, + message = "Not Found. \n No activity found with the given ID.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while getting the comment list.", + response = ErrorResponse.class) + }) + + Response getAllComments( + @ApiParam( + name="uuid", + value="uuid of the released version of application.", + required = true) + @PathParam("uuid") + String uuid, + @ApiParam( + name="offSet", + value="Starting comment number.",defaultValue = "1", + required = false) + @QueryParam("offSet") + int offSet, + @ApiParam( + name="limit", + value = "Limit of paginated comments",defaultValue = "20", + required = false) + @QueryParam("limit") + int limit); + + @POST + @Path("/{uuid}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Add a comment", + notes = "This will add a new comment", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:store:add") + }) + } + ) + + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully add a comment.", + response = Comment.class), + @ApiResponse( + code = 400, + message = + "Bad Request. \n"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred adding a comment.", + response = ErrorResponse.class) + }) + + Response addComments( + @ApiParam( + name = "comment", + value = "Comment details", + required = true) + Comment comment, + @ApiParam( + name="uuid", + value="uuid of the release version of the application", + required=true) + @PathParam("uuid") + String uuid); + + @PUT + @Path("/{CommentId}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Edit a comment", + notes = "This will edit the comment", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:store:edit") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully updated comment.", + response = Comment.class), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 404, + message = "Not Found. \n No activity found with the given ID.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while updating the new comment.", + response = ErrorResponse.class) + }) + Response updateComment( + @ApiParam( + name = "comment", + value = "The comment that need to be updated.", + required = true) + @Valid Comment comment, + @ApiParam( + name="commentId", + value = "comment id of the updating comment.", + required = true) + @QueryParam("commentId") + int commentId); + + @DELETE + @Path("/{CommentId}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Remove comment", + notes = "Remove comment", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:store:remove") + }) + } + ) + + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully deleted the comment"), + @ApiResponse( + code = 404, + message = "Not Found. \n No activity found with the given ID.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while deleting the comment.", + response = ErrorResponse.class) + }) + + Response deleteComment( + @ApiParam( + name="commentId", + value="Id of the comment.", + required = true) + @PathParam("commentId") + int commentId); + + @GET + @Path("/{uuid}/{stars}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get stars", + notes = "Get all stars", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:stars:get") + }) + } + ) + + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved stars.", + response = List.class, + responseContainer = "List"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while getting the stars", + response = ErrorResponse.class) + }) + + Response getStars( + @ApiParam( + name = "uuid", + value = "uuid of the application release", + required = true) + @PathParam("uuid") + String uuid); + + @GET + @Path("/{uuid}/{stars}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get rated users", + notes = "Get all users", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:user:get") + }) + } + ) + + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved user.", + response = List.class, + responseContainer = "List"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while getting the comment list.", + response = ErrorResponse.class) + }) + + Response getRatedUser( + @ApiParam( + name = "uuid", + value = "uuid of the application release", + required = true) + @PathParam("uuid") + String uuid); + + @POST + @Path("/uuid/{uuid}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Add a star value", + notes = "This will add star value", + tags = "Store Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:stars:add") + }) + } + ) + + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully rated to the application.", + response = Comment.class), + @ApiResponse( + code = 304, + message = "Not Modified. \n " + + "Empty body because the client already has the latest rating of the requested resource."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred rating for the application.", + response = ErrorResponse.class) + }) + + Response updateStars( + @ApiParam( + name = "stars", + value = "ratings for the application", + required = true) + int stars, + @ApiParam( + name="uuid", + value="uuid of the release version of the application", + required=true) + @PathParam("uuid") + String uuid); +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/CommentManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/CommentManagementAPIImpl.java new file mode 100644 index 0000000000..be1a7cfe85 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/CommentManagementAPIImpl.java @@ -0,0 +1,228 @@ +/* + * 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.api.services.impl; + +import io.swagger.annotations.ApiParam; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.application.mgt.api.APIUtil; +import org.wso2.carbon.device.application.mgt.api.services.CommentManagementAPI; +import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; + +import javax.ws.rs.Path; +import javax.ws.rs.Consumes; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.PUT; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.DELETE; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +/** + * Comment Management related jax-rs APIs. + */ +@Path("/comments") +public class CommentManagementAPIImpl implements CommentManagementAPI { + + private static Log log = LogFactory.getLog(CommentManagementAPIImpl.class); + + @Override + @GET + @Path("/{uuid}") + public Response getAllComments( + @PathParam("uuid") String uuid, + @QueryParam("offset") int offSet, @ + QueryParam("limit") int limit) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + List comments = new ArrayList<>(); + try { + PaginationRequest request = new PaginationRequest(offSet, limit); + if (request.validatePaginationRequest(offSet, limit)) { + commentsManager.getAllComments(request, uuid); + return Response.status(Response.Status.OK).entity(comments).build(); + } + } catch (NotFoundException e) { + log.error("Not found exception occurs to uuid " + uuid + " .", e); + return Response.status(Response.Status.NOT_FOUND).entity("Application with UUID " + uuid + " not found") + .build(); + } catch (CommentManagementException e) { + String msg = "Error occurred while retrieving comments."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(" Internal server error occurs").build(); + } + return Response.status(Response.Status.OK).entity(comments).build(); + } + + @Override + @POST + @Consumes("application/json") + @Path("/{uuid}") + public Response addComments( + @ApiParam Comment comment, + @PathParam("uuid") String uuid) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + Comment newComment = commentsManager.addComment(comment, uuid, tenantId); + if (comment != null) { + return Response.status(Response.Status.CREATED).entity(newComment).build(); + } else { + String msg = "Given comment is not valid "; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + } catch (CommentManagementException e) { + String msg = "Error occurred while creating the comment"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("Internal server error occurs").build(); + } + } + + @Override + @PUT + @Consumes("application/json") + @Path("/{commentId}") + public Response updateComment( + @ApiParam Comment comment, + @PathParam("commentId") int commentId) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + try { + if (commentId == 0) { + return Response.status(Response.Status.NOT_FOUND) + .entity("Comment not found").build(); + } else if (comment == null) { + String msg = "Given comment is not valid "; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).build(); + } else { + comment = commentsManager.updateComment(comment, commentId); + return Response.status(Response.Status.OK).entity(comment).build(); + } + } catch (CommentManagementException e) { + String msg = "Error occurred while retrieving comments."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(" Internal server error occurs").build(); + } + } + + @Override + @DELETE + @Path("/{commentId}") + public Response deleteComment( + @PathParam("commentId") int commentId) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + try { + commentsManager.deleteComment(commentId); + } catch (CommentManagementException e) { + String msg = "Error occurred while deleting the comment."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("Internal server error occurs").build(); + } catch (NotFoundException e) { + log.error("Not found exception occurs to comment id " + commentId + " .", e); + return Response.status(Response.Status.NOT_FOUND).entity("Comment not found").build(); + } + return Response.status(Response.Status.OK).entity("Comment is deleted successfully.").build(); + } + + @Override + @GET + @Path("/{uuid}") + public Response getStars( + @PathParam("uuid") String uuid) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + int Stars = 0; + try { + Stars = commentsManager.getStars(uuid); + } catch (CommentManagementException e) { + log.error("Comment Management Exception occurs", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (ApplicationManagementException e) { + log.error("Application Management Exception occurs", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("Internal server error occurs").build(); + } + return Response.status(Response.Status.OK).entity(Stars).build(); + } + + @Override + @GET + @Path("/{uuid}") + public Response getRatedUser( + @PathParam("uuid") String uuid) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + int ratedUsers = 0; + try { + ratedUsers = commentsManager.getRatedUser(uuid); + } catch (CommentManagementException e) { + log.error("Comment Management Exception occurs", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("Internal server error occurs").build(); + } catch (ApplicationManagementException e) { + log.error("Application Management Exception occurs", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("Application with UUID" + uuid + " Internal server error occurs").build(); + } + return Response.status(Response.Status.OK).entity(ratedUsers).build(); + } + + @Override + @POST + @Consumes("application/json") + public Response updateStars( + @ApiParam int stars, + @PathParam("uuid") String uuid) { + + CommentsManager commentsManager = APIUtil.getCommentsManager(); + int newStars = 0; + try { + newStars = commentsManager.updateStars(stars, uuid); + + if (stars != 0) { + return Response.status(Response.Status.CREATED).entity(newStars).build(); + } else { + String msg = "Given star value is not valid "; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + } catch (ApplicationManagementException e) { + log.error("Application Management Exception occurs", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(" Internal server error occurs").build(); + } + } +} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java index e43b4fda64..48215fb121 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java @@ -53,6 +53,26 @@ public class ApplicationRelease { private boolean isDefault; + private int noOfRatedUsers; + + private int stars; + + public int getNoOfRatedUsers() { + return noOfRatedUsers; + } + + public void setNoOfRatedUsers(int noOfRatedUsers) { + this.noOfRatedUsers = noOfRatedUsers; + } + + public int getStars() { + return stars; + } + + public void setStars(int stars) { + this.stars = stars; + } + public int getId() { return id; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java index 6d6d61cdef..ef6fab4543 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Comment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -18,33 +18,44 @@ */ package org.wso2.carbon.device.application.mgt.common; +import java.sql.Timestamp; +import java.util.Date; + /** * Represents a comment for an {@link Application}. */ public class Comment { - private String id; + private int id; private String comment; - private int rating; - //TODO: Pagination, comment ID for child - private Comment parent; + private int parent; + + private int tenantId; private String createdBy; - private String createdAt; + private Timestamp createdAt; - private String modifiedAt; + private String modifiedBy; - private Application application; + private Timestamp modifiedAt; + + public int getTenantId() { + return tenantId; + } - public String getId() { + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public int getId() { return id; } - public void setId(String id) { + public void setId(int id) { this.id = id; } @@ -56,19 +67,11 @@ public class Comment { this.comment = comment; } - public int getRating() { - return rating; - } - - public void setRating(int rating) { - this.rating = rating; - } - - public Comment getParent() { + public int getParent() { return parent; } - public void setParent(Comment parent) { + public void setParent(int parent) { this.parent = parent; } @@ -80,27 +83,29 @@ public class Comment { this.createdBy = createdBy; } - public String getCreatedAt() { + public Timestamp getCreatedAt() { return createdAt; } - public void setCreatedAt(String createdAt) { + public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; } - public String getModifiedAt() { - return modifiedAt; + public String getModifiedBy() { + return modifiedBy; } - public void setModifiedAt(String modifiedAt) { - this.modifiedAt = modifiedAt; + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; } - public Application getApplication() { - return application; + public Timestamp getModifiedAt() { + return modifiedAt; } - public void setApplication(Application application) { - this.application = application; + public void setModifiedAt(Timestamp modifiedAt) { + this.modifiedAt = modifiedAt; } + } + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/PaginationRequest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/PaginationRequest.java new file mode 100644 index 0000000000..915b3e40da --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/PaginationRequest.java @@ -0,0 +1,63 @@ +/* + * 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; + +/** + * This class holds required parameters for a querying a paginated device response. + */ +public class PaginationRequest { + + private int offSet; + private int limit; + + public PaginationRequest(int start, int limit) { + this.offSet = start; + this.limit = limit; + } + + public int getOffSet() { + return offSet; + } + + public void setOffSet(int offSet) { + this.offSet = offSet; + } + + public int getLimit() { + return limit; + } + + public void setLimit(int limit) { + this.limit = limit; + } + + public boolean validatePaginationRequest(int offSet, int limit) { + if (offSet < 0) { + throw new IllegalArgumentException("off set value can't be negative"); + } else if (limit < 0) { + throw new IllegalArgumentException("limit value can't be negative"); + } else { + return true; + } + } + + @Override public String toString() { + return "Off Set'" + this.offSet + "' row count '" + this.limit; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/PaginationResult.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/PaginationResult.java new file mode 100644 index 0000000000..df7354924f --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/PaginationResult.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.application.mgt.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.List; + +/** + * This class holds necessary data to represent a paginated result. + */ +@ApiModel(value = "PaginationResult", description = "This class carries all information related Pagination Result") +public class PaginationResult implements Serializable { + + private static final long serialVersionUID = 1998101711L; + + @ApiModelProperty(name = "recordsTotal", value = "The total number of records that are given before filtering", required = true) + private int recordsTotal; + + @ApiModelProperty(name = "recordsFiltered", value = "The total number of records that are given after filtering", required = true) + private int recordsFiltered; + + @ApiModelProperty(name = "draw", value = "The draw counter that this object is a response to, from the draw parameter sent as part of the data request", required = true) + private int draw; + + @ApiModelProperty(name = "data", value = "This holds the database records that matches given criteria", required = true) + private List data; + + public int getRecordsTotal() { + return recordsTotal; + } + + public int getRecordsFiltered() { + return recordsFiltered; + } + + public void setRecordsFiltered(int recordsFiltered) { + this.recordsFiltered = recordsFiltered; + } + + public void setRecordsTotal(int recordsTotal) { + this.recordsTotal = recordsTotal; + + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + + public int getDraw() { + return draw; + } + + public void setDraw(int draw) { + this.draw = draw; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/CommentManagementException.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/CommentManagementException.java new file mode 100644 index 0000000000..2f81f5144a --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/CommentManagementException.java @@ -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 CommentManagementException extends Exception { + private String message; + + public CommentManagementException(String message, Throwable throwable) { + super(message, throwable); + setMessage(message); + } + + public CommentManagementException(String message) { + super(message); + setMessage(message); + } + + public CommentManagementException() { + + } + + @Override public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java index b0e0f4bd82..6428f11ceb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CommentsManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -18,9 +18,104 @@ */ package org.wso2.carbon.device.application.mgt.common.services; +import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.PaginationResult; +import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; + +import java.util.List; + /** * CommentsManager is responsible for handling all the add/update/delete/get operations related with - * {@link org.wso2.carbon.device.application.mgt.common.Comment}. */ public interface CommentsManager { -} + + /** + * To add a comment to a application + * + * @param comment comment of the application. + * @param uuid uuid of the application release + * @param tenantId tenant id of the application + * @return {@link Comment} Comment added + * @throws CommentManagementException Exceptions of the comment management. + */ + Comment addComment(Comment comment, String uuid, int tenantId) throws CommentManagementException; + + /** + * To validate the pre-request of the comment + * + * @param commentId ID of the comment. + * @param comment comment needed to be validate. + * @return validated the comment. + * @throws CommentManagementException Exceptions of the comment management. + */ + Boolean validateComment(int commentId, String comment) throws CommentManagementException; + + /** + * Get all comments to pagination + * + * @param request Pagination request + * @param uuid uuid of the application release + * @return {@link PaginationResult} pagination result with starting offSet and limit + * @throws CommentManagementException Exceptions of the comment management. + */ + List getAllComments(PaginationRequest request, String uuid) throws CommentManagementException; + + /** + * To get the comment with id. + * + * @param commentId id of the comment + * @return {@link Comment}Comment of the comment id + * @throws CommentManagementException Exceptions of the comment management. + */ + Comment getComment(int commentId) throws CommentManagementException; + + /** + * To delete comment using comment id. + * + * @param commentId id of the comment + * @throws CommentManagementException Exceptions of the comment management + */ + void deleteComment(int commentId) throws CommentManagementException; + + /** + * To update a comment. + * + * @param comment comment of the application. + * @param commentId id of the comment + * @return {@link Comment}updated comment + * @throws CommentManagementException Exceptions of the comment management + */ + Comment updateComment(Comment comment, int commentId) throws CommentManagementException; + + /** + * To get number of rated users + * + * @param uuid uuid of the application + * @return number of rated users + * @throws CommentManagementException Exceptions of the comment management + * @throws ApplicationManagementException Application Management Exception. + */ + int getRatedUser(String uuid) throws CommentManagementException, ApplicationManagementException; + + /** + * To get the average of stars + * + * @param uuid uuid of the comment + * @return value of the stars of an application + * @throws CommentManagementException Exceptions of the comment management + * @throws ApplicationManagementException Application Management Exception. + */ + int getStars(String uuid) throws CommentManagementException, ApplicationManagementException; + + /** + * To update rating stars + * + * @param stars amount of stars + * @param uuid uuid of the application + * @return value of the added stars + * @throws ApplicationManagementException Application Management Exception. + */ + int updateStars(int stars, String uuid) throws ApplicationManagementException; +} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java index 4b085f8427..3ef617ff0e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/Configuration.java @@ -35,6 +35,8 @@ public class Configuration { private Artifacts artifacts; + private PaginationConfiguration paginationConfiguration; + @XmlElement(name = "DatasourceName", required = true) public String getDatasourceName() { return datasourceName; @@ -53,6 +55,11 @@ public class Configuration { public void setExtensions(List extensions) { this.extensions = extensions; } + + @XmlElement(name = "PaginationConfiguration", required = true) + public PaginationConfiguration getPaginationConfiguration() { + return paginationConfiguration; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java index 4e5ae24022..90675e0102 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java @@ -97,4 +97,5 @@ public class ConfigurationManager { } throw new InvalidConfigurationException("Expecting an extension with name - " + extName + " , but not found!"); } + } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/PaginationConfiguration.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/PaginationConfiguration.java new file mode 100644 index 0000000000..7205802517 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/PaginationConfiguration.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.application.mgt.core.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This class represents the information related to Pagination configuration. + */ +@XmlRootElement(name = "PaginationConfiguration") public class PaginationConfiguration { + + private int commentListPageSize; + + public int getCommentListPageSize() { + return commentListPageSize; + } + + @XmlElement(name = "commentListPageSize", required = true) public void setCommentListPageSize( + int commentListPageSize) { + this.commentListPageSize = commentListPageSize; + } + +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java index 27cbe337e3..90e3600744 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CommentDAO.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -18,8 +18,390 @@ */ package org.wso2.carbon.device.application.mgt.core.dao; +import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; +import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; + +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.List; + /** * This interface specifies the database access operations performed for comments. */ -public interface CommentDAO { -} + + public interface CommentDAO { + + /** + * To add a comment to a application. + * + * @param tenantId tenantId of the commented application. + * @param comment comment of the application. + * @param createdBy Username of the created person. + * @param parentId parent id of the parent comment. + * @param uuid uuid of the application + * @return Comment Id + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + */ + int addComment(int tenantId, Comment comment, String createdBy, int parentId, String uuid) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To add a comment to a application. + * + * @param comment comment of the application. + * @param createdBy Username of the created person. + * @param appType type of the commented application. + * @param appName name of the commented application. + * @param version version of the commented application. + * @return comment id + * @throws CommentManagementException Exceptions of the comment management. + */ + int addComment(int tenantId, Comment comment, String createdBy, String appType, String appName, String version) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To update already added comment. + * + * @param commentId id of the comment + * @param updatedComment comment after updated + * @param modifiedBy Username of the modified person. + * @param modifiedAt time of the modification. + * @return {@link Comment}Updated comment + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception + * @throws SQLException sql exception + */ + Comment updateComment(int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To update already added comment. + * + * @param uuid uuid of the comment + * @param commentId id of the comment + * @param updatedComment comment after updated + * @param modifiedBy Username of the modified person. + * @param modifiedAt time of the modification. + * @return {@link Comment}Updated comment + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception + * @throws SQLException sql exception + */ + Comment updateComment(String uuid, int commentId, String updatedComment, String modifiedBy, Timestamp modifiedAt) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get the comment with id. + * + * @param commentId id of the comment + * @return {@link Comment}Comment + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception + * @throws SQLException sql exception + */ + Comment getComment(int commentId) throws CommentManagementException, SQLException, DBConnectionException; + + /** + * To get the comment with id. + * + * @param uuid uuid of the comment + * @return {@link List} List of comments in the application + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception + * @throws SQLException sql exception + */ + List getComment(String uuid) throws CommentManagementException, SQLException, DBConnectionException; + + /** + * To get all the comments + * + * @param uuid uuid of the application + * @param request {@link PaginationRequest}pagination request with offSet and limit + * @return {@link List}List of all the comments in an application + * @throws CommentManagementException Exception of the comment management + * @throws DBConnectionException db connection exception + * @throws SQLException sql exception + **/ + List getAllComments(String uuid, PaginationRequest request) + throws CommentManagementException, SQLException, DBConnectionException; + + /** + * To get list of comments using release id and application id. + * + * @param appReleasedId Id of the released version of the application. + * @param appId id of the commented application. + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + */ + List getComments(int appReleasedId, int appId) throws CommentManagementException; + + /** + * To get list of comments using application type, application name and version of the application. + * + * @param appType type of the commented application. + * @param appName name of the commented application. + * @param version version of the commented application. + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getComments(String appType, String appName, String version) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get list of comments using tenant id. + * + * @param tenantId tenant id of the commented application + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getComments(int tenantId) throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get list of comments by created user. + * + * @param createdBy Username of the created person. + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getCommentsByUser(String createdBy) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get list of comments by created use and created time. + * + * @param createdBy Username of the created person. + * @param createdAt time of the comment created. + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getCommentsByUser(String createdBy, Timestamp createdAt) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get list of comments by modified users. + * + * @param modifiedBy Username of the modified person. + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getCommentsByModifiedUser(String modifiedBy) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get list of comments using modified user's name and modified time. + * + * @param modifiedBy Username of the modified person. + * @param modifiedAt time of the modification + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get list of comments using application type, application name , application version and parent id of the comment. + * + * @param appType type of the commented application. + * @param appName name of the commented application. + * @param version version of the commented application. + * @param parentId parent id of the parent comment. + * @return {@link List}List of comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + List getComments(String appType, String appName, String version, int parentId) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get a count of the comments by usernames. + * + * @param uuid uuid of the application + * @return Count of the comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + int getCommentCount(String uuid) throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get a count of the comments by usernames. + * + * @param createdBy Username of the created person. + * @return Count of the comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + int getCommentCountByUser(String createdBy) throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get the comment count by parent comment id. + * + * @param uuid uuid of the comment + * @param parentId id of the parent comment + * @return Count of the comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + int getCommentCountByParent(String uuid, int parentId) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get a count of comments by modification details. + * + * @param modifiedBy Username of the modified person. + * @param modifedAt time of the modification + * @return Count of the comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + int getCommentCountByUser(String modifiedBy, Timestamp modifedAt) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get count of comments by application versions. + * + * @param appId id of the commented application. + * @param appReleaseId Id of the released version of the application. + * @return Count of the comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + int getCommentCountByApp(int appId, int appReleaseId) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To get count of comments by application details. + * + * @param appType type of the commented application. + * @param appName name of the commented application. + * @param version version of the commented application. + * @return Count of the comments + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + int getCommentCountByApp(String appType, String appName, String version) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To delete comment using comment id. + * + * @param commentId id of the comment + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + void deleteComment(int commentId) throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To delete comment using comment id. + * + * @param uuid uuid of the comment + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + void deleteComment(String uuid) throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To delete comments using application details. + * + * @param appId id of the commented application. + * @param appReleaseID Id of the released version of the application. + * @throws CommentManagementException Exceptions of the comment management. + * @throws DBConnectionException db connection exception. + * @throws SQLException sql exception + */ + void deleteComments(int appId, int appReleaseID) + throws CommentManagementException, DBConnectionException, SQLException; + + /** + * To delete comments using application details. + * + * @param appType type of the commented application. + * @param appName name of the commented application. + * @param version version of the commented application. + * @throws CommentManagementException Exceptions of the comment management. + */ + void deleteComments(String appType, String appName, String version) throws CommentManagementException; + + /** + * To delete comments using users created and application details. + * + * @param appType type of the commented application. + * @param appName name of the commented application. + * @param version version of the commented application. + * @param createdBy Username of the created person. + * @throws CommentManagementException Exceptions of the comment management. + */ + void deleteComments(String appType, String appName, String version, String createdBy) + throws CommentManagementException; + + /** + * To delete comments by parent id of the comment. + * + * @param uuid uuid of the application + * @param parentId parent id of the parent comment. + * @throws CommentManagementException Exceptions of the comment management. + */ + void deleteComments(String uuid, int parentId) throws CommentManagementException; + + /** + * To add the star rating to the application. + * + * @param stars Star value + * @param uuid UUID of the application + * @return Star value + * @throws ApplicationManagementDAOException Application Management DAO Exception. + */ + int updateStars(int stars, String uuid) throws ApplicationManagementDAOException; + + /** + * To get the average star value of the application + * + * @param uuid uuid of the application + * @return Average of star values + * @throws ApplicationManagementDAOException Application Management DAO Exception. + */ + int getStars(String uuid) throws ApplicationManagementDAOException; + + /** + * To get number of rated users + * + * @param uuid uuid of the application + * @return Number of rated users + * @throws ApplicationManagementDAOException Application Management DAO Exception. + */ + int getRatedUser(String uuid) throws ApplicationManagementDAOException; + + /** + * To get comment count for pagination + * + * @param request + * @param uuid + * @return Comment count + * @throws CommentManagementException + */ + int getCommentCount(PaginationRequest request, String uuid) throws CommentManagementException; +} \ No newline at end of file diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java new file mode 100644 index 0000000000..2e37423458 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.application.mgt.core.dao.common; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException; +import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; +import org.wso2.carbon.device.application.mgt.core.dao.*; +import org.wso2.carbon.device.application.mgt.core.dao.impl.Comment.CommentDAOImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.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.OracleApplicationDAOImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.subscription.GenericSubscriptionDAOImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.visibility.GenericVisibilityDAOImpl; +import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.util.ApplicationMgtDatabaseCreator; +import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; +import org.wso2.carbon.device.application.mgt.core.util.Constants; +import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; +import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; +import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl; +import org.wso2.carbon.utils.dbcreator.DatabaseCreator; + +import javax.sql.DataSource; +import java.sql.SQLException; + +import static org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil.resolveDataSource; + +/** + * This class intends to act as the primary entity that hides all DAO instantiation related complexities and logic so + * that the business objection handling layer doesn't need to be aware of the same providing seamless plug-ability of + * different data sources, connection acquisition mechanisms as well as different forms of DAO implementations to the + * high-level implementations that require Application management related metadata persistence. + */ +public class ApplicationManagementDAOFactory { + + private static String databaseEngine; + private static DataSource dataSource; + private static final Log log = LogFactory.getLog(ApplicationManagementDAOFactory.class); + + public static void init(String datasourceName) { + ConnectionManagerUtil.resolveDataSource(datasourceName); + databaseEngine = ConnectionManagerUtil.getDatabaseType(); + } + public static void init(DataSource dtSource){ + dataSource=dtSource; + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + public static void init(DataSourceConfig config) { + dataSource = resolveDataSource(config); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + + + public static ApplicationDAO getApplicationDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new GenericApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleApplicationDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + public static LifecycleStateDAO getLifecycleStateDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + case Constants.DataBaseTypes.DB_TYPE_ORACLE: + return new GenericLifecycleStateImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + /** + * To get the instance of ApplicationReleaseDAOImplementation of the particular database engine. + * + * @return specific ApplicationReleaseDAOImplementation + */ + public static ApplicationReleaseDAO getApplicationReleaseDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + case Constants.DataBaseTypes.DB_TYPE_ORACLE: + return new GenericApplicationReleaseDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + /** + * To get the instance of VisibilityDAOImplementation of the particular database engine. + * + * @return specific VisibilityDAOImplementation + */ + public static VisibilityDAO getVisibilityDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericVisibilityDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + /** + * To get the instance of SubscriptionDAOImplementation of the particular database engine. + * + * @return GenericSubscriptionDAOImpl + */ + public static SubscriptionDAO getSubscriptionDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new GenericSubscriptionDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + /** + * To get the instance of DeviceTypeDAOImpl of the particular database engine. + * + * @return DeviceTypeDAOImpl + */ + public static DeviceTypeDAO getDeviceTypeDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new DeviceTypeDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + /** + * To get the instance of LifecycleDAOImplementation of the particular database engine. + * + * @return GenericLifecycleDAOImpl + */ + public static LifecycleStateDAO getLifecycleDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new GenericLifecycleStateImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + /** + * This method initializes the databases by creating the database. + * + * @throws ApplicationManagementDAOException Exceptions thrown during the creation of the tables + */ + public static void initDatabases() throws ApplicationManagementDAOException { + String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName(); + String validationQuery = "SELECT * from APPM_PLATFORM"; + try { + if (System.getProperty("setup") == null) { + if (log.isDebugEnabled()) { + log.debug("Application Management Database schema initialization check was skipped since " + + "\'setup\' variable was not given during startup"); + } + } else { + DatabaseCreator databaseCreator = new ApplicationMgtDatabaseCreator(dataSourceName); + if (!databaseCreator.isDatabaseStructureCreated(validationQuery)) { + databaseCreator.createRegistryDatabase(); + log.info("Application Management tables are created in the database"); + } else { + log.info("Application Management Database structure already exists. Not creating the database."); + } + } + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "Error while creating application-mgt database during the " + "startup ", e); + } catch (Exception e) { + throw new ApplicationManagementDAOException( + "Error while creating application-mgt database in the " + "startup ", e); + } + } + + public static CommentDAO getCommentDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new CommentDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + +} + + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java index 2743a120c6..1513951128 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java @@ -22,11 +22,16 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.wso2.carbon.device.application.mgt.common.Application; +import org.wso2.carbon.device.application.mgt.common.Platform; +import org.wso2.carbon.device.application.mgt.common.User; import org.wso2.carbon.device.application.mgt.common.Category; import org.wso2.carbon.device.application.mgt.common.Lifecycle; import org.wso2.carbon.device.application.mgt.common.LifecycleState; -import org.wso2.carbon.device.application.mgt.common.Platform; -import org.wso2.carbon.device.application.mgt.common.User; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; + +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.core.config.Configuration; +import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -123,4 +128,18 @@ public class Util { } } } + + public static PaginationRequest validateCommentListPageSize(PaginationRequest paginationRequest) throws + CommentManagementException{ + if (paginationRequest.getLimit() == 0) { + Configuration commentManagementConfig = ConfigurationManager.getInstance().getConfiguration(); + if (commentManagementConfig != null) { + paginationRequest.setLimit(commentManagementConfig.getPaginationConfiguration().getCommentListPageSize()); + } else { + throw new CommentManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/CommentDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/CommentDAOImpl.java new file mode 100644 index 0000000000..bf9da2448e --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/Comment/CommentDAOImpl.java @@ -0,0 +1,1003 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.application.mgt.core.dao.impl.Comment; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; +import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; +import org.wso2.carbon.device.application.mgt.core.dao.CommentDAO; +import org.wso2.carbon.device.application.mgt.core.dao.common.Util; +import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; +import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; + +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.ResultSet; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.ArrayList; +import java.util.List; + +/** + * This handles CommentDAO related operations. + */ + +public class CommentDAOImpl extends AbstractDAOImpl implements CommentDAO { + + private static final Log log = LogFactory.getLog(CommentDAOImpl.class); + String sql; + + @Override + public int addComment(int tenantId, Comment comment, String createdBy, int parentId, String uuid) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to add comment for application release (" + uuid + ")"); + } + Connection conn = this.getDBConnection(); + PreparedStatement statement = null; + ResultSet rs = null; + int commentId = -1; + sql = "INSERT INTO AP_APP_COMMENT (TENANT_ID, COMMENT_TEXT, CREATED_BY, PARENT_ID,AP_APP_RELEASE_ID," + + "AP_APP_ID) VALUES (?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?)," + + "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));"; + try { + statement = conn.prepareStatement(sql, new String[] { "id" }); + statement.setInt(1, tenantId); + statement.setString(2, comment.getComment()); + statement.setString(3, createdBy); + statement.setInt(4, parentId); + statement.setString(5, uuid); + statement.setString(6, uuid); + statement.executeUpdate(); + rs = statement.getGeneratedKeys(); + if (rs.next()) { + commentId = rs.getInt(1); + } + return commentId; + } finally { + Util.cleanupResources(statement, rs); + } + } + + @Override + public int addComment(int tenantId, Comment comment, String createdBy, String appType, String appName, + String version) throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to add to application (" + appName + ") and version (" + version + + ")"); + } + Connection conn = this.getDBConnection(); + PreparedStatement statement = null; + ResultSet rs; + int commentId = -1; + sql = "INSERT INTO AP_APP_COMMENT ( TENANT_ID,COMMENT_TEXT, CREATED_BY,AP_APP_RELEASE_ID,AP_APP_ID) " + + "VALUES (?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE VERSION =? AND (SELECT ID FROM AP_APP WHERE " + + "TYPE=? AND NAME=?)),(SELECT ID FROM AP_APP WHERE TYPE=? AND NAME=?));"; + try { + statement = conn.prepareStatement(sql, new String[] { "id" }); + statement.setInt(1, tenantId); + statement.setString(2, comment.getComment()); + statement.setString(3, createdBy); + statement.setString(4, version); + statement.setString(5, appType); + statement.setString(6, appName); + statement.setString(7, appType); + statement.setString(8, appName); + statement.executeUpdate(); + rs = statement.getGeneratedKeys(); + if (rs.next()) { + commentId = rs.getInt(1); + } + } finally { + Util.cleanupResources(statement, null); + } + return commentId; + } + + @Override + public Comment updateComment(int commentId, String updatedComment, String modifiedBy, + Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to update the comment with ID (" + commentId + ")"); + } + Connection connection; + PreparedStatement statement = null; + ResultSet rs = null; + sql = "UPDATE AP_APP_COMMENT SET COMMENT_TEXT=?, MODEFIED_BY=? WHERE ID=?;"; + try { + connection = this.getDBConnection(); + statement = connection.prepareStatement(sql); + statement.setString(1, updatedComment); + statement.setString(2, modifiedBy); + statement.setInt(3, commentId); + statement.executeUpdate(); + rs = statement.executeQuery(); + } finally { + Util.cleanupResources(statement, rs); + } + return getComment(commentId); + } + + @Override + public Comment updateComment(String uuid, int commentId, String updatedComment, String modifiedBy, + Timestamp modifiedAt) throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to update the comment with application (" + uuid + ") and " + + "comment id ( " + commentId + ")"); + } + Connection connection; + PreparedStatement statement = null; + ResultSet rs = null; + sql = "UPDATE AP_APP_COMMENT SET COMMENT_TEXT=?,MODEFIED_BY=? WHERE ID=?; "; + try { + connection = this.getDBConnection(); + statement = connection.prepareStatement(sql); + statement.setString(1, updatedComment); + statement.setString(2, modifiedBy); + statement.setInt(3, commentId); + statement.executeUpdate(); + rs = statement.getResultSet(); + } finally { + Util.cleanupResources(statement, rs); + } + return getComment(commentId); + } + + @Override + public Comment getComment(int commentId) throws CommentManagementException { + + if (log.isDebugEnabled()) { + log.debug("Getting comment with the comment id(" + commentId + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + Comment comment = new Comment(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE ID=?;"; + statement = conn.prepareStatement(sql); + statement.setInt(1, commentId); + rs = statement.executeQuery(); + if (rs.next()) { + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("MODEFIED_AT")); + comment.setParent(rs.getInt("PARENT_ID")); + Util.cleanupResources(statement, rs); + return comment; + } + } catch (SQLException e) { + throw new CommentManagementException( + "SQL Error occurred while retrieving information of the comment " + commentId, e); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while retrieving information of the comment " + commentId, e); + } finally { + Util.cleanupResources(statement, null); + } + return comment; + } + + @Override + public List getComment(String uuid) throws CommentManagementException { + + if (log.isDebugEnabled()) { + log.debug("Getting comment with the application release(" + uuid + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE (SELECT ID FROM AP_APP_RELEASE where UUID=?)AND " + + "(SELECT AP_APP_ID FROM AP_APP_RELEASE where UUID=?);"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + statement.setString(2, uuid); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("MODEFIED_AT")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while retrieving comments", e); + } catch (SQLException e) { + throw new CommentManagementException("SQL Error occurred while retrieving comments", e); + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getAllComments(String uuid, PaginationRequest request) + throws CommentManagementException, SQLException, DBConnectionException { + + if (log.isDebugEnabled()) { + log.debug("Getting comment of the application release (" + uuid + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs = null; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID " + + "AND AP_APP_RELEASE.UUID =? LIMIT ? OFFSET ?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + statement.setInt(2, request.getLimit()); + statement.setInt(3, request.getOffSet()); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("MODEFIED_BY")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, rs); + } + return comments; + } + + @Override + public int getCommentCount(PaginationRequest request, String uuid) throws CommentManagementException { + + int commentCount = 0; + Connection conn; + PreparedStatement statement = null; + ResultSet rs = null; + boolean isUuidProvided = false; + try { + conn = this.getDBConnection(); + if (uuid != null) { + isUuidProvided = true; + } + if (isUuidProvided) { + sql = "SELECT COUNT(AP_APP_COMMENT.ID) FROM AP_APP_COMMENT,AP_APP_RELEASE " + + "WHERE AP_APP_COMMENT.AP_APP_RELEASE_ID= AP_APP_RELEASE.ID AND " + + "AP_APP_COMMENT.AP_APP_ID= AP_APP_RELEASE.AP_APP_ID AND AP_APP_RELEASE.UUID=?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENTS_COUNT"); + } + } + } catch (SQLException e) { + throw new CommentManagementException("SQL Error occurred while retrieving count of comments", e); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while retrieving count of comments", e); + } finally { + Util.cleanupResources(statement, rs); + } + return commentCount; + } + + @Override + public List getComments(int appReleasedId, int appId) throws CommentManagementException { + + if (log.isDebugEnabled()) { + log.debug("Getting comments with the application release id(" + appReleasedId + ") and " + "application id(" + + appId + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? AND AP_APP_ID=?;"; + statement = conn.prepareStatement(sql); + statement.setInt(1, appReleasedId); + statement.setInt(2, appId); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while retrieving information of comments", e); + } catch (SQLException e) { + throw new CommentManagementException("SQL Error occurred while retrieving information of comments", e); + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getComments(String appType, String appName, String version) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Getting comments with the application name(" + appName + "),application type(" + appType + ") " + + "and application version (" + version + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID FROM AP_APP_COMMENT C ," + + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=?) R," + + "(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? AND TYPE=?)P" + + " WHERE AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND AP_APP_ID=RELEASE_AP_APP_ID" + + "ORDER BY CREATED_AT DESC;"; + statement = conn.prepareStatement(sql); + statement.setString(1, version); + statement.setString(2, appName); + statement.setString(3, appType); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getComments(int tenantId) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Getting comments with the tenant_id(" + tenantId + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE TENANT_ID='?';"; + statement = conn.prepareStatement(sql); + statement.setInt(1, tenantId); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getCommentsByUser(String createdBy) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Getting comments with the created by(" + createdBy + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT ,PARENT_ID,TENANT_ID,CREATED_AT FROM AP_APP_COMMENT WHERE CREATED_BY= ?" + + " ORDER BY CREATED_AT DESC;"; + statement = conn.prepareStatement(sql); + statement.setString(1, createdBy); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getCommentsByUser(String createdBy, Timestamp createdAt) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug( + "Getting comments with the created by(" + createdBy + ") at (" + createdAt + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID FROM AP_APP_COMMENT WHERE CREATED_BY=?" + + "AND CREATED_AT= ? ORDER BY CREATED_AT DESC;"; + statement = conn.prepareStatement(sql); + statement.setString(1, createdBy); + statement.setTimestamp(2, createdAt); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getCommentsByModifiedUser(String modifiedBy) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Getting comments with the modified by(" + modifiedBy + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID,CREATED_AT,MODEFIED_AT FROM AP_APP_COMMENT " + + "WHERE MODEFIED_BY= ? ORDER BY CREATED_AT DESC;"; + statement = conn.prepareStatement(sql); + statement.setString(1, modifiedBy); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getCommentsByModifiedUser(String modifiedBy, Timestamp modifiedAt) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug("Getting comments with the modified by(" + modifiedBy + ") at (" + modifiedAt + ") from the " + + "database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT,PARENT_ID,TENANT_ID,CREATED_AT FROM AP_APP_COMMENT WHERE MODEFIED_BY= ?," + + "MODEFIED_AT=? ORDER BY CREATED_AT DESC;"; + statement = conn.prepareStatement(sql); + statement.setString(1, modifiedBy); + statement.setTimestamp(2, modifiedAt); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public List getComments(String appType, String appName, String version, int parentId) + throws CommentManagementException, DBConnectionException, SQLException { + + if (log.isDebugEnabled()) { + log.debug( + "Getting comments with the application name(" + appName + "),application type(" + appType + ") and" + + "application version (" + version + ") from the database"); + } + Connection conn; + PreparedStatement statement = null; + ResultSet rs; + List comments = new ArrayList<>(); + try { + conn = this.getDBConnection(); + sql = "SELECT COMMENT_TEXT,TENANT_ID FROM AP_APP_COMMENT C ," + + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=? ) " + + "R,(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? AND TYPE=?)P " + + "WHERE PARENT_ID=? AND AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND " + + "AP_APP_ID=RELEASE_AP_APP_ID ORDER BY CREATED_AT DESC;"; + statement = conn.prepareStatement(sql); + statement.setString(1, version); + statement.setString(2, appName); + statement.setString(3, appType); + statement.setInt(4, parentId); + rs = statement.executeQuery(); + while (rs.next()) { + Comment comment = new Comment(); + comment.setId(rs.getInt("ID")); + comment.setTenantId(rs.getInt("TENANT_ID")); + comment.setComment(rs.getString("COMMENT_TEXT")); + comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); + comment.setCreatedBy(rs.getString("CREATED_BY")); + comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); + comment.setModifiedBy(rs.getString("modifiedBy")); + comment.setParent(rs.getInt("PARENT_ID")); + comments.add(comment); + } + } finally { + Util.cleanupResources(statement, null); + } + return comments; + } + + @Override + public int getCommentCount(String uuid) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + int commentCount = 0; + try { + conn = this.getDBConnection(); + sql = "SELECT COUNT(AP_APP_COMMENT.ID) FROM AP_APP_COMMENT,AP_APP_RELEASE WHERE " + + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_COMMENT.AP_APP_ID=" + + "AP_APP_RELEASE.AP_APP_ID AND AP_APP_RELEASE.UUID=?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("ID"); + } + } finally { + Util.cleanupResources(statement, null); + return commentCount; + } + } + + @Override + public int getCommentCountByUser(String createdBy) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + int commentCount = 0; + try { + conn = this.getDBConnection(); + sql = "SELECT COUNT(ID) FROM AP_APP_COMMENT WHERE CREATED_BY= ?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, createdBy); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENT_COUNT"); + } + } finally { + Util.cleanupResources(statement, null); + } + return commentCount; + } + + @Override + public int getCommentCountByUser(String modifiedBy, Timestamp modifedAt) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + int commentCount = 0; + try { + conn = this.getDBConnection(); + sql = "SELECT COUNT(ID) FROM AP_APP_COMMENT WHERE MODEFIED_BY= ? AND MODEFIED_AT=?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, modifiedBy); + statement.setTimestamp(2, modifedAt); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENT_COUNT"); + } + } finally { + Util.cleanupResources(statement, null); + } + return commentCount; + } + + @Override + public int getCommentCountByApp(int appId, int appReleaseId) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + int commentCount = 0; + try { + conn = this.getDBConnection(); + sql = "SELECT COUNT(ID) FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? AND AP_APP_ID=?;"; + statement = conn.prepareStatement(sql); + statement.setInt(1, appReleaseId); + statement.setInt(2, appId); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENT_COUNT"); + } + } finally { + Util.cleanupResources(statement, null); + } + return commentCount; + } + + @Override + public int getCommentCountByApp(String appType, String appName, String version) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + int commentCount = 0; + try { + conn = this.getDBConnection(); + sql = "SELECT COUNT(ID) AS COMMENT_COUNT FROM AP_APP_COMMENT C, " + + "(SELECT ID AS RELEASE_ID, AP_APP_ID AS RELEASE_AP_APP_ID FROM AP_APP_RELEASE R WHERE VERSION=? )R," + + "(SELECT ID AS APP_ID FROM AP_APP P WHERE NAME=? and TYPE=?)P " + + "WHERE AP_APP_RELEASE_ID=RELEASE_ID AND RELEASE_AP_APP_ID=APP_ID AND AP_APP_ID=RELEASE_AP_APP_ID;"; + statement = conn.prepareStatement(sql); + statement.setString(1, version); + statement.setString(2, appName); + statement.setString(3, appType); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENT_COUNT"); + } + } finally { + Util.cleanupResources(statement, null); + } + return commentCount; + } + + public int getCommentCountByParent(String uuid, int parentId) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + int commentCount = 0; + try { + conn = this.getDBConnection(); + sql = "SELECT COUNT(AP_APP_COMMENT.ID) FROM AP_APP_COMMENT,AP_APP_RELEASE WHERE " + + "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND " + + "AP_APP_COMMENT.AP_APP_ID=AP_APP_RELEASE.AP_APP_ID and AP_APP_RELEASE.UUID=? and PARENT_ID=?;"; + + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + statement.setInt(2, parentId); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + commentCount = rs.getInt("COMMENT_COUNT"); + } + } finally { + Util.cleanupResources(statement, null); + } + return commentCount; + } + + @Override + public void deleteComment(int commentId) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + try { + conn = this.getDBConnection(); + sql = "DELETE FROM AP_APP_COMMENT WHERE ID=?;"; + statement = conn.prepareStatement(sql); + statement.setInt(1, commentId); + statement.executeUpdate(); + } finally { + Util.cleanupResources(statement, null); + } + } + + public void deleteComment(String uuid) throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + try { + conn = this.getDBConnection(); + sql = "DELETE FROM AP_APP_COMMENT WHERE " + + "(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?)AND (SELECT AP_APP_ID FROM AP_APP_RELEASE " + + "WHERE UUID=?);"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + statement.setString(2, uuid); + statement.executeUpdate(); + } finally { + Util.cleanupResources(statement, null); + } + } + + @Override + public void deleteComments(int appId, int appReleaseID) + throws CommentManagementException, DBConnectionException, SQLException { + + Connection conn; + PreparedStatement statement = null; + try { + conn = this.getDBConnection(); + sql = "DELETE FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=? and AP_APP_ID=?;"; + statement = conn.prepareStatement(sql); + statement.setInt(1, appReleaseID); + statement.setInt(2, appId); + statement.executeUpdate(); + } finally { + Util.cleanupResources(statement, null); + } + } + + @Override + public void deleteComments(String appType, String appName, String version) + throws CommentManagementException { + + Connection conn; + PreparedStatement statement = null; + try { + conn = this.getDBConnection(); + sql = "DELETE FROM AP_APP_COMMENT WHERE " + + "(SELECT AP_APP_RELEASE_ID FROM AP_APP_RELEASE WHERE VERSION=? AND " + + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? AND TYPE=?)) AND " + + "(SELECT AP_APP_ID FROM AP_APP AND NAME=? AND TYPE=?);"; + statement = conn.prepareStatement(sql); + statement.setString(1, version); + statement.setString(2, appName); + statement.setString(3, appType); + statement.setString(4, appName); + statement.setString(5, appType); + statement.executeUpdate(); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while deleting comments", e); + } catch (SQLException e) { + throw new CommentManagementException("SQL Error occurred while deleting comments", e); + } finally { + Util.cleanupResources(statement, null); + } + } + + @Override + public void deleteComments(String appType, String appName, String version, String createdBy) + throws CommentManagementException { + + Connection conn; + PreparedStatement statement = null; + try { + conn = this.getDBConnection(); + sql = "DELETE FROM AP_APP_COMMENT WHERE " + + "(SELECT AP_APP_RELEASE_ID FROM AP_APP_RELEASE WHERE VERSION=? AND " + + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? AND TYPE=?)) AND " + + "(SELECT AP_APP_ID FROM AP_APP WHERE NAME=? and TYPE=?) AND CREATED_BY=?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, version); + statement.setString(2, appName); + statement.setString(3, appType); + statement.setString(4, appName); + statement.setString(5, appType); + statement.setString(6, createdBy); + statement.executeUpdate(); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while deleting comments ", e); + } catch (SQLException e) { + throw new CommentManagementException("Error occurred while deleting comments", e); + } finally { + Util.cleanupResources(statement, null); + } + } + + @Override + public void deleteComments(String uuid, int parentId) throws CommentManagementException { + + Connection conn; + PreparedStatement statement = null; + try { + conn = this.getDBConnection(); + sql = "DELETE FROM AP_APP_COMMENT WHERE AP_APP_RELEASE_ID=(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?) " + + "AND AP_APP_ID=(SELECT AP_APP_ID FROM AP_APP_RELEASE where UUID=?)AND PARENT_ID=?;"; + statement = conn.prepareStatement(sql); + statement.setString(1, uuid); + statement.setString(2, uuid); + statement.setInt(3, parentId); + statement.executeUpdate(); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurred while deleting comments.", e); + } catch (SQLException e) { + throw new CommentManagementException("Error occurred while deleting comments", e); + } finally { + Util.cleanupResources(statement, null); + } + } + + @Override + public int updateStars(int stars, String uuid) throws ApplicationManagementDAOException { + + Connection connection; + PreparedStatement statement = null; + ResultSet resultSet = null; + try { + connection = this.getDBConnection(); + sql = "UPDATE AP_APP_RELEASE SET STARS=?, NO_OF_RATED_USERS=(NO_OF_RATED_USERS+1) WHERE UUID=?;"; + statement = connection.prepareStatement(sql); + statement.setInt(1, stars); + statement.setString(2, uuid); + resultSet = statement.executeQuery(sql); + if (resultSet != null) { + resultSet.getInt("STARS"); + } + int numORows = resultSet.getRow(); + if (resultSet.next()) { + ApplicationRelease applicationRelease = new ApplicationRelease(); + applicationRelease.setStars(resultSet.getInt("STARS")); + Util.cleanupResources(statement, resultSet); + } + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "SQL Exception while trying to add stars to an application (UUID : " + uuid + "), by executing " + + "the query " + e); + } catch (DBConnectionException e) { + log.error("DB Connection Exception while trying to add stars to an application (UUID : " + uuid + "), ", + e); + } finally { + Util.cleanupResources(statement, null); + return getStars(uuid); + } + } + + @Override + public int getStars(String uuid) throws ApplicationManagementDAOException { + + Connection connection; + PreparedStatement statement = null; + ResultSet resultSet = null; + int Stars = 0; + try { + connection = this.getDBConnection(); + sql = "SELECT STARS FROM AP_APP_RELEASE WHERE UUID=?;"; + statement = connection.prepareStatement(sql); + statement.setString(1, uuid); + resultSet = statement.executeQuery(); + if (resultSet.next()) { + ApplicationRelease applicationRelease = new ApplicationRelease(); + Stars = resultSet.getInt("STARS"); + return Stars; + } + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "SQL Exception while trying to get stars from an application (UUID : " + uuid + "), by executing " + + "the query " + e); + } catch (DBConnectionException e) { + log.error( + "DB Connection Exception while trying to get stars from an application (UUID : " + uuid + ")," + e); + } finally { + Util.cleanupResources(statement, resultSet); + } + return Stars; + } + + @Override + public int getRatedUser(String uuid) throws ApplicationManagementDAOException { + + Connection connection; + PreparedStatement statement = null; + ResultSet resultSet = null; + int ratedUsers = 0; + try { + connection = this.getDBConnection(); + sql = "SELECT NO_OF_RATED_USERS FROM AP_APP_RELEASE WHERE UUID=?;"; + statement = connection.prepareStatement(sql); + statement.setString(1, uuid); + resultSet = statement.executeQuery(); + if (resultSet.next()) { + ApplicationRelease applicationRelease = new ApplicationRelease(); + ratedUsers = resultSet.getInt("NO_OF_RATED_USERS"); + applicationRelease.setNoOfRatedUsers(ratedUsers); + Util.cleanupResources(statement, resultSet); + return ratedUsers; + } + } catch (SQLException e) { + log.error("SQL Exception occurs.", e); + } catch (DBConnectionException e) { + log.error("DB Connection Exception occurs.", e); + } finally { + Util.cleanupResources(statement, resultSet); + } + return ratedUsers; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java index 23c5903344..4a5ab8b1c9 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CommentsManagerImpl.java @@ -1,5 +1,5 @@ /* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* 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. @@ -17,10 +17,264 @@ */ package org.wso2.carbon.device.application.mgt.core.impl; -import org.wso2.carbon.device.application.mgt.common.services.CommentsManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.application.mgt.common.Comment; +import org.wso2.carbon.device.application.mgt.common.PaginationRequest; +import org.wso2.carbon.device.application.mgt.common.PaginationResult; +import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; +import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; +import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException; +import org.wso2.carbon.device.application.mgt.common.services.*; +import org.wso2.carbon.device.application.mgt.core.dao.CommentDAO; +import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; +import org.wso2.carbon.device.application.mgt.core.dao.common.Util; +import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; + +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.List; /** * This class is the default implementation for the Managing the comments. */ public class CommentsManagerImpl implements CommentsManager { -} + + private static final Log log = LogFactory.getLog(CommentsManagerImpl.class); + private CommentDAO commentDAO; + + public CommentsManagerImpl() { + initDataAccessObjects(); + } + + private void initDataAccessObjects() { + this.commentDAO = ApplicationManagementDAOFactory.getCommentDAO(); + } + + @Override + public Comment addComment(Comment comment, String uuid, int tenantId) throws CommentManagementException { + + if (log.isDebugEnabled()) { + log.debug("Request for comment is received for uuid" + uuid); + } + comment.setCreatedAt(Timestamp.from(Instant.now())); + try { + ConnectionManagerUtil.beginDBTransaction(); + commentDAO.addComment(tenantId, comment, comment.getCreatedBy(), comment.getParent(), uuid); + ConnectionManagerUtil.commitDBTransaction(); + return comment; + } catch (DBConnectionException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new CommentManagementException( + "DB Connection error occurs ,Comment for application with UUID " + uuid + "cannot add.", e); + } catch (SQLException e) { + throw new CommentManagementException( + "SQL Exception occurs,Comment for application with UUID " + uuid + "cannot add.", e); + } catch (TransactionManagementException e) { + throw new CommentManagementException( + "Transaction Management Exception occurs,Comment for application with UUID " + uuid + "cannot add.", + e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + /** + * To validate the pre-request of the comment + * + * @param commentId ID of the comment. + * @param comment comment needed to be validate. + * @return Application related with the UUID. + * @throws CommentManagementException Exceptions of the comment management. + */ + + public Boolean validateComment(int commentId, String comment) throws CommentManagementException { + + if (commentId <= 0) { + throw new CommentManagementException( + "Comment ID is null or negative. Comment id is a required parameter to get the " + + "relevant comment."); + } + if (comment == null) { + log.error("Comment can not be null, but Comment at comment id " + commentId + " is null."); + return false; + } + return true; + } + + @Override + public List getAllComments(PaginationRequest request, String uuid) + throws CommentManagementException { + + PaginationResult paginationResult = new PaginationResult(); + List comments; + request = Util.validateCommentListPageSize(request); + if (log.isDebugEnabled()) { + log.debug("get all comments of the application release" + uuid); + } + try { + ConnectionManagerUtil.openDBConnection(); + comments = commentDAO.getAllComments(uuid, request); + int count = commentDAO.getCommentCount(request, uuid); + paginationResult.setData(comments); + paginationResult.setRecordsFiltered(count); + paginationResult.setRecordsTotal(count); + + return comments; + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs ,Comments of application with UUID " + uuid + "cannot get.", e); + } catch (SQLException e) { + throw new CommentManagementException( + "SQL Exception occurs,Comments of application with UUID " + uuid + "cannot get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Comment getComment(int commentId) throws CommentManagementException { + + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + Comment comment = null; + if (log.isDebugEnabled()) { + log.debug("Comment retrieval request is received for the comment id " + commentId); + } + try { + ConnectionManagerUtil.openDBConnection(); + comment = commentDAO.getComment(commentId); + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs ,Comment with comment id " + commentId + "cannot get.", e); + } catch (SQLException e) { + throw new CommentManagementException( + "SQL Exception occurs,Comment with comment id " + commentId + "cannot get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + return comment; + } + + @Override + public void deleteComment(int commentId) throws CommentManagementException { + + Comment comment; + comment = getComment(commentId); + if (comment == null) { + throw new CommentManagementException( + "Cannot delete a non-existing comment for the application with comment id" + commentId); + } + try { + ConnectionManagerUtil.beginDBTransaction(); + commentDAO.deleteComment(commentId); + ConnectionManagerUtil.commitDBTransaction(); + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs deleting comment with comment id " + commentId + ".", e); + } catch (SQLException e) { + throw new CommentManagementException("SQL error occurs deleting comment with comment id " + commentId + ".", + e); + } catch (TransactionManagementException e) { + throw new CommentManagementException( + "Transaction Management Exception occurs deleting comment with comment id " + commentId + ".", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Comment updateComment(Comment comment, int commentId) throws CommentManagementException { + + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + validateComment(commentId, comment.getComment()); + if (log.isDebugEnabled()) { + log.debug("Comment retrieval request is received for the comment id " + commentId); + } + comment.setModifiedAt(Timestamp.from(Instant.now())); + try { + ConnectionManagerUtil.openDBConnection(); + commentDAO.getComment(commentId); + return commentDAO + .updateComment(commentId, comment.getComment(), comment.getModifiedBy(), comment.getModifiedAt()); + } catch (SQLException e) { + throw new CommentManagementException("SQL Error occurs updating comment with comment id " + commentId + ".", + e); + } catch (DBConnectionException e) { + throw new CommentManagementException( + "DB Connection error occurs updating comment with comment id " + commentId + ".", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public int getRatedUser(String uuid) throws ApplicationManagementException { + + int ratedUsers = 0; + if (log.isDebugEnabled()) { + log.debug("Get the rated users for the application release number" + uuid); + } + try { + ConnectionManagerUtil.openDBConnection(); + ratedUsers = commentDAO.getRatedUser(uuid); + } catch (ApplicationManagementDAOException e) { + throw new ApplicationManagementException( + "Rated Users of the Application with UUID " + uuid + " can not get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + return ratedUsers; + } + + @Override + public int getStars(String uuid) throws ApplicationManagementException { + + int stars = 0; + if (log.isDebugEnabled()) { + log.debug("Get the average of rated stars for the application " + uuid); + } + try { + ConnectionManagerUtil.openDBConnection(); + stars = commentDAO.getStars(uuid); + } catch (ApplicationManagementDAOException e) { + throw new ApplicationManagementException( + "Average stars of the Application with UUID " + uuid + " can not get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + return stars; + } + + @Override + public int updateStars(int stars, String uuid) throws ApplicationManagementException { + + if (log.isDebugEnabled()) { + log.debug("Stars are received for the application " + uuid); + } + int newStars = 0; + try { + ConnectionManagerUtil.beginDBTransaction(); + int ratedUsers = commentDAO.getRatedUser(uuid); + int oldStars = commentDAO.getStars(uuid); + if (ratedUsers == 0) { + newStars = commentDAO.updateStars(stars, uuid); + return newStars; + } else { + int avgStars = ((oldStars * ratedUsers) + stars) / (ratedUsers + 1); + newStars = commentDAO.updateStars(avgStars, uuid); + ConnectionManagerUtil.commitDBTransaction(); + return newStars; + } + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw new ApplicationManagementException( + "Updated average stars of the Application with UUID " + uuid + " can not get.", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } +} \ No newline at end of file