Merge pull request #1144 from NishadiPrasangini/AppManager

App manager
merge-requests/7/head
Rasika Perera 7 years ago committed by GitHub
commit de78869eea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -22,18 +22,18 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.api.beans.ErrorResponse; 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.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.ApplicationReleaseManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; 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.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; import javax.ws.rs.core.Response;
/** /**
* Holds util methods required for Application-Mgt API component. * Holds util methods required for Application-Mgt API component.
*/ */
@ -41,67 +41,37 @@ public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class); 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() { public static ApplicationManager getApplicationManager() {
if (applicationManager == null) {
synchronized (APIUtil.class) {
if (applicationManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
applicationManager = ApplicationManager applicationManager = (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
(ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
if (applicationManager == null) { if (applicationManager == null) {
String msg = "Application Manager service has not initialized."; String msg = "Application Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return applicationManager; return applicationManager;
} }
public static PlatformManager getPlatformManager() { public static PlatformManager getPlatformManager() {
if (platformManager == null) {
synchronized (APIUtil.class) {
if (platformManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
platformManager = PlatformManager platformManager = (PlatformManager) ctx.getOSGiService(PlatformManager.class, null);
(PlatformManager) ctx.getOSGiService(PlatformManager.class, null);
if (platformManager == null) { if (platformManager == null) {
String msg = "Platform Manager service has not initialized."; String msg = "Platform Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return platformManager; return platformManager;
} }
public static LifecycleStateManager getLifecycleStateManager() { public static LifecycleStateManager getLifecycleStateManager() {
if (lifecycleStateManager == null) {
synchronized (APIUtil.class) {
if (lifecycleStateManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
lifecycleStateManager = LifecycleStateManager lifecycleStateManager = (LifecycleStateManager) ctx
(LifecycleStateManager) ctx.getOSGiService(LifecycleStateManager.class, null); .getOSGiService(LifecycleStateManager.class, null);
if (lifecycleStateManager == null) { if (lifecycleStateManager == null) {
String msg = "Lifecycle Manager service has not initialized."; String msg = "Lifecycle Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return lifecycleStateManager; return lifecycleStateManager;
} }
@ -111,42 +81,31 @@ public class APIUtil {
* @return ApplicationRelease Manager instance in the current osgi context. * @return ApplicationRelease Manager instance in the current osgi context.
*/ */
public static ApplicationReleaseManager getApplicationReleaseManager() { public static ApplicationReleaseManager getApplicationReleaseManager() {
if (applicationReleaseManager == null) {
synchronized (APIUtil.class) {
if (applicationReleaseManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
applicationReleaseManager = (ApplicationReleaseManager) ctx ApplicationReleaseManager applicationReleaseManager = (ApplicationReleaseManager) ctx
.getOSGiService(ApplicationReleaseManager.class, null); .getOSGiService(ApplicationReleaseManager.class, null);
if (applicationReleaseManager == null) { if (applicationReleaseManager == null) {
String msg = "Application Release Manager service has not initialized."; String msg = "Application Release Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return applicationReleaseManager; return applicationReleaseManager;
} }
/** /**
* To get the Application Storage Manager from the osgi context. * To get the Application Storage Manager from the osgi context.
*
* @return ApplicationStoreManager instance in the current osgi context. * @return ApplicationStoreManager instance in the current osgi context.
*/ */
public static ApplicationStorageManager getApplicationStorageManager() { public static ApplicationStorageManager getApplicationStorageManager() {
if (applicationStorageManager == null) {
synchronized (APIUtil.class) {
if (applicationStorageManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
applicationStorageManager = (ApplicationStorageManager) ctx ApplicationStorageManager applicationStorageManager = (ApplicationStorageManager) ctx
.getOSGiService(ApplicationStorageManager.class, null); .getOSGiService(ApplicationStorageManager.class, null);
if (applicationStorageManager == null) { if (applicationStorageManager == null) {
String msg = "Application Storage Manager service has not initialized."; String msg = "Application Storage Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return applicationStorageManager; return applicationStorageManager;
} }
@ -156,43 +115,30 @@ public class APIUtil {
* @return PlatformStoreManager instance in the current osgi context. * @return PlatformStoreManager instance in the current osgi context.
*/ */
public static PlatformStorageManager getPlatformStorageManager() { public static PlatformStorageManager getPlatformStorageManager() {
if (platformStorageManager == null) {
synchronized (APIUtil.class) {
if (platformStorageManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
platformStorageManager = (PlatformStorageManager) ctx PlatformStorageManager platformStorageManager = (PlatformStorageManager) ctx
.getOSGiService(PlatformStorageManager.class, null); .getOSGiService(PlatformStorageManager.class, null);
if (platformStorageManager == null) { if (platformStorageManager == null) {
String msg = "Platform Storage Manager service has not initialized."; String msg = "Platform Storage Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return platformStorageManager; return platformStorageManager;
} }
/** /**
* To get the Category Manager from the osgi context. * To get the Category Manager from the osgi context.
* *
* @return CategoryManager instance in the current osgi context. * @return CategoryManager instance in the current osgi context.
*/ */
public static CategoryManager getCategoryManager() { public static CategoryManager getCategoryManager() {
if (categoryManager == null) {
synchronized (APIUtil.class) {
if (categoryManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
categoryManager = (CategoryManager) ctx.getOSGiService(CategoryManager.class, null); CategoryManager categoryManager = (CategoryManager) ctx.getOSGiService(CategoryManager.class, null);
if (categoryManager == null) { if (categoryManager == null) {
String msg = "Category Manager service has not initialized."; String msg = "Category Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
}
}
}
return categoryManager; return categoryManager;
} }
@ -212,24 +158,35 @@ public class APIUtil {
/** /**
* To get the Subscription Manager from the osgi context. * To get the Subscription Manager from the osgi context.
*
* @return SubscriptionManager instance in the current osgi context. * @return SubscriptionManager instance in the current osgi context.
*/ */
public static SubscriptionManager getSubscriptionManager() { public static SubscriptionManager getSubscriptionManager() {
if (subscriptionManager == null) {
synchronized (APIUtil.class) {
if (subscriptionManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
subscriptionManager = SubscriptionManager subscriptionManager = (SubscriptionManager) ctx
(SubscriptionManager) ctx.getOSGiService(SubscriptionManager.class, null); .getOSGiService(SubscriptionManager.class, null);
if (subscriptionManager == null) { if (subscriptionManager == null) {
String msg = "Subscription Manager service has not initialized."; String msg = "Subscription Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
} return subscriptionManager;
}
} }
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;
} }
} }

@ -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);
}

@ -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<Comment> 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();
}
}
}

@ -53,6 +53,26 @@ public class ApplicationRelease {
private boolean isDefault; 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() { public int getId() {
return id; return id;
} }

@ -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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -18,33 +18,44 @@
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
import java.sql.Timestamp;
import java.util.Date;
/** /**
* Represents a comment for an {@link Application}. * Represents a comment for an {@link Application}.
*/ */
public class Comment { public class Comment {
private String id; private int id;
private String comment; private String comment;
private int rating;
//TODO: Pagination, comment ID for child //TODO: Pagination, comment ID for child
private Comment parent; private int parent;
private int tenantId;
private String createdBy; 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; return id;
} }
public void setId(String id) { public void setId(int id) {
this.id = id; this.id = id;
} }
@ -56,19 +67,11 @@ public class Comment {
this.comment = comment; this.comment = comment;
} }
public int getRating() { public int getParent() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public Comment getParent() {
return parent; return parent;
} }
public void setParent(Comment parent) { public void setParent(int parent) {
this.parent = parent; this.parent = parent;
} }
@ -80,27 +83,29 @@ public class Comment {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getCreatedAt() { public Timestamp getCreatedAt() {
return createdAt; return createdAt;
} }
public void setCreatedAt(String createdAt) { public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt; this.createdAt = createdAt;
} }
public String getModifiedAt() { public String getModifiedBy() {
return modifiedAt; return modifiedBy;
} }
public void setModifiedAt(String modifiedAt) { public void setModifiedBy(String modifiedBy) {
this.modifiedAt = modifiedAt; this.modifiedBy = modifiedBy;
} }
public Application getApplication() { public Timestamp getModifiedAt() {
return application; return modifiedAt;
} }
public void setApplication(Application application) { public void setModifiedAt(Timestamp modifiedAt) {
this.application = application; this.modifiedAt = modifiedAt;
} }
} }

@ -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;
}
}

@ -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;
}
}

@ -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;
}
}

@ -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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * 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; 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 * 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 { 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<Comment> 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;
} }

@ -35,6 +35,8 @@ public class Configuration {
private Artifacts artifacts; private Artifacts artifacts;
private PaginationConfiguration paginationConfiguration;
@XmlElement(name = "DatasourceName", required = true) @XmlElement(name = "DatasourceName", required = true)
public String getDatasourceName() { public String getDatasourceName() {
return datasourceName; return datasourceName;
@ -53,6 +55,11 @@ public class Configuration {
public void setExtensions(List<Extension> extensions) { public void setExtensions(List<Extension> extensions) {
this.extensions = extensions; this.extensions = extensions;
} }
@XmlElement(name = "PaginationConfiguration", required = true)
public PaginationConfiguration getPaginationConfiguration() {
return paginationConfiguration;
}
} }

@ -97,4 +97,5 @@ public class ConfigurationManager {
} }
throw new InvalidConfigurationException("Expecting an extension with name - " + extName + " , but not found!"); throw new InvalidConfigurationException("Expecting an extension with name - " + extName + " , but not found!");
} }
} }

@ -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;
}
}

@ -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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * 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; 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. * 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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<Comment> 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;
} }

@ -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.");
}
}

@ -22,11 +22,16 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException; import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application; 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.Category;
import org.wso2.carbon.device.application.mgt.common.Lifecycle; 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.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.Platform; import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.User;
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.PreparedStatement;
import java.sql.ResultSet; 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;
}
} }

@ -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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
@ -17,10 +17,264 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.impl; 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. * This class is the default implementation for the Managing the comments.
*/ */
public class CommentsManagerImpl implements CommentsManager { 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<Comment> getAllComments(PaginationRequest request, String uuid)
throws CommentManagementException {
PaginationResult paginationResult = new PaginationResult();
List<Comment> 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();
}
}
} }
Loading…
Cancel
Save