fixing conflicts

feature/appm-store/pbac
inoshperera 6 years ago
commit 874a83cee5

@ -1,110 +0,0 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common;
import java.sql.Timestamp;
/**
* Represents a commentText for an {@link Application}.
*/
public class Comment {
private int id;
private String commentText;
//TODO: Pagination, commentText ID for child
private int parent;
private int tenantId;
private String createdBy;
private Timestamp createdAt;
private String modifiedBy;
private Timestamp modifiedAt;
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
public int getParent() {
return parent;
}
public void setParent(int parent) {
this.parent = parent;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Timestamp getModifiedAt() {
return modifiedAt;
}
public void setModifiedAt(Timestamp modifiedAt) {
this.modifiedAt = modifiedAt;
}
}

@ -18,21 +18,50 @@
*/
package org.wso2.carbon.device.application.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Filter represents a criteria that can be used for searching applications.
*/
@ApiModel(value = "Filter", description = "This is related to the application filtering.")
public class Filter {
@ApiModelProperty(
name = "appName",
value = "Name of the application",
required = false)
private String appName;
@ApiModelProperty(
name = "appType",
value = "Type of the application",
required = false)
private String appType;
@ApiModelProperty(
name = "isFullMatch",
value = "Checking the application name matches fully with given name",
required = false)
private boolean isFullMatch;
@ApiModelProperty(
name = "limit",
value = "Limit of the applications",
required = false)
private int limit;
@ApiModelProperty(
name = "offset",
value = "Started from",
required = false)
private int offset;
@ApiModelProperty(
name = "sortBy",
value = "Ascending or descending order",
required = false)
private String sortBy;
public int getLimit() {

@ -24,7 +24,7 @@ import io.swagger.annotations.ApiModelProperty;
import java.util.List;
@ApiModel(value = "LifecycleState", description = "LifecycleState represents the an Lifecycle state for an application release")
@ApiModel(value = "LifecycleState", description = "LifecycleState represents the Lifecycle state for an application release")
public class LifecycleState {
@ApiModelProperty(name = "id",

@ -0,0 +1,66 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common;
import java.util.TreeMap;
/**
* Rating represents the an overall rating value and number of users who has rated for an application release.
*/
public class Rating {
/**
* Rating value of the application release.
*/
private double ratingValue;
/**
* Number of users who has rated for the application release.
*/
private int noOfUsers;
/**
* Represent the rating variety for the application release
*/
private TreeMap<Integer, Integer> ratingVariety;
public double getRatingValue() {
return ratingValue;
}
public void setRatingValue(double ratingValue) {
this.ratingValue = ratingValue;
}
public int getNoOfUsers() {
return noOfUsers;
}
public void setNoOfUsers(int noOfUsers) {
this.noOfUsers = noOfUsers;
}
public TreeMap<Integer, Integer> getRatingVariety() {
return ratingVariety;
}
public void setRatingVariety(TreeMap<Integer, Integer> ratingVariety) {
this.ratingVariety = ratingVariety;
}
}

@ -0,0 +1,126 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.sql.Timestamp;
@ApiModel(value = "Review", description = "Review represents the user's review for an application release")
public class Review {
@ApiModelProperty(name = "id",
value = "The Id given to the comment when it store to the App manager")
private int id;
@ApiModelProperty(name = "comment",
value = "Comment of the review")
private String comment;
@ApiModelProperty(name = "parentId",
value = "Parent id of the review")
private int parentId;
@ApiModelProperty(name = "username",
value = "Username odf the Review creator",
required = true)
private String username;
@ApiModelProperty(name = "createdAt",
value = "Timestamp fo the review is created")
private Timestamp createdAt;
@ApiModelProperty(name = "modifiedAt",
value = "Timestamp of the review is modified")
private Timestamp modifiedAt;
@ApiModelProperty(name = "rating",
value = "Rating value of the application release")
private int rating;
@ApiModelProperty(name = "replyReview",
value = "Replying review")
private Review replyReview;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public Timestamp getModifiedAt() {
return modifiedAt;
}
public void setModifiedAt(Timestamp modifiedAt) {
this.modifiedAt = modifiedAt;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public Review getReplyReview() {
return replyReview;
}
public void setReplyReview(Review replyReview) {
this.replyReview = replyReview;
}
}

@ -18,20 +18,20 @@
*/
package org.wso2.carbon.device.application.mgt.common.exception;
public class CommentManagementException extends Exception {
public class ReviewManagementException extends Exception {
private String message;
public CommentManagementException(String message, Throwable throwable) {
public ReviewManagementException(String message, Throwable throwable) {
super(message, throwable);
setMessage(message);
}
public CommentManagementException(String message) {
public ReviewManagementException(String message) {
super(message);
setMessage(message);
}
public CommentManagementException() {
public ReviewManagementException() {
}

@ -150,7 +150,7 @@ public interface ApplicationManager {
* @param applicationUuid UUID of the Application Release.
* @throws ApplicationManagementException Application Management Exception.
*/
void addLifecycleState(int applicationId, String applicationUuid, LifecycleState state) throws ApplicationManagementException;
void changeLifecycleState(int applicationId, String applicationUuid, LifecycleState state) throws ApplicationManagementException;
/**
* Get the application if application is an accessible one.

@ -1,120 +0,0 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.Comment;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException;
import java.util.List;
/**
* CommentsManager is responsible for handling all the add/update/delete/get operations related with
*/
public interface CommentsManager {
/**
* To add a comment to a application
*
* @param comment comment of the application.
* @param uuid uuid of the application release\
* @return {@link Comment} Comment added
* @throws CommentManagementException Exceptions of the comment management.
*/
Comment addComment(Comment comment, String uuid) throws CommentManagementException;
/**
* To validate the pre-request of the comment
*
* @param commentId ID of the comment.
* @param comment comment needed to be validate.
* @return validated the comment.
* @throws CommentManagementException Exceptions of the comment management.
*/
Boolean validateComment(int commentId, String comment) throws CommentManagementException;
/**
* Get all comments to pagination
*
* @param request Pagination request
* @param uuid uuid of the application release
* @return {@link PaginationResult} pagination result with starting offSet and limit
* @throws CommentManagementException Exceptions of the comment management.
*/
PaginationResult getAllComments(PaginationRequest request, String uuid) throws CommentManagementException;
/**
* To get the comment with id.
*
* @param commentId id of the comment
* @return {@link Comment}Comment of the comment id
* @throws CommentManagementException Exceptions of the comment management.
*/
Comment getComment(int commentId) throws CommentManagementException;
/**
* To delete comment using comment id.
*
* @param commentId id of the comment
* @throws CommentManagementException Exceptions of the comment management
*/
void deleteComment(int commentId) throws CommentManagementException;
/**
* To update a comment.
*
* @param comment comment of the application.
* @param commentId id of the comment
* @return {@link Comment}updated comment
* @throws CommentManagementException Exceptions of the comment management
*/
Comment updateComment(Comment comment, int commentId) throws CommentManagementException;
/**
* To get number of rated users
*
* @param uuid uuid of the application
* @return number of rated users
* @throws CommentManagementException Exceptions of the comment management
* @throws ApplicationManagementException Application Management Exception.
*/
int getRatedUser(String uuid) throws CommentManagementException, ApplicationManagementException;
/**
* To get the average of stars
*
* @param uuid uuid of the comment
* @return value of the stars of an application
* @throws CommentManagementException Exceptions of the comment management
* @throws ApplicationManagementException Application Management Exception.
*/
int getStars(String uuid) throws CommentManagementException, ApplicationManagementException;
/**
* To update rating stars
*
* @param stars amount of stars
* @param uuid uuid of the application
* @return value of the added stars
* @throws ApplicationManagementException Application Management Exception.
*/
int updateStars(int stars, String uuid) throws ApplicationManagementException;
}

@ -0,0 +1,88 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.Review;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
/**
* ReviewManager is responsible for handling all the add/update/delete/get operations related with
*/
public interface ReviewManager {
/**
* To add a review to a application
*
* @param review review of the application.
* @param appId id of the application.
* @param appReleaseId id of the application release
* @return {@link Review} Review added
* @throws ReviewManagementException Exceptions of the review management.
*/
boolean addReview(Review review,int appId, int appReleaseId) throws ReviewManagementException;
/**
* Get all comments to pagination
*
* @param request Pagination request {@link PaginationRequest}
* @param uuid uuid of the application release
* @return {@link PaginationResult} pagination result with starting offSet and limit
* @throws ReviewManagementException Exceptions of the comment management.
*/
PaginationResult getAllReviews(PaginationRequest request, String uuid) throws ReviewManagementException;
/**
* To get the comment with id.
*
* @param commentId id of the comment
* @return {@link Review}Review of the comment id
* @throws ReviewManagementException Exceptions of the comment management.
*/
Review getReview(int commentId) throws ReviewManagementException;
/**
* To delete review using review id.
*
* @param commentId id of the comment
* @throws ReviewManagementException Exceptions of the comment management
*/
void deleteReview(String loggedInUser, int commentId) throws ReviewManagementException;
/**
* To update a review.
*
* @param review review of the application.
* @param reviewId id of the review
* @return {@link Review}updated review
* @throws ReviewManagementException Exceptions of the review management
*/
boolean updateReview(Review review, int reviewId, boolean checkExistence) throws ReviewManagementException;
/**
* To get the overall rating for a application release
*
* @param appReleaseUuuid UUID of the application release.
* @return {@link Review}updated review
* @throws ReviewManagementException Exceptions of the review management
*/
Rating getRating(String appReleaseUuuid) throws ReviewManagementException;
}

@ -42,7 +42,6 @@
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.1</version>
<extensions>true</extensions>
<configuration>
<instructions>
@ -50,9 +49,7 @@
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Application Management Core Bundle</Bundle-Description>
<Private-Package>
org.wso2.carbon.device.application.mgt.core.internal
</Private-Package>
<Private-Package>org.wso2.carbon.device.application.mgt.core.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
@ -81,7 +78,8 @@
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}",
org.wso2.carbon.base,
net.dongliu.apk.parser.*
com.dd.*,
org.apache.commons.validator.routines
</Import-Package>
<Embed-Dependency>apk-parser;scope=compile|runtime;inline=false</Embed-Dependency>
<!--<Embed-Transitive>true</Embed-Transitive>-->

@ -18,6 +18,8 @@
*/
package org.wso2.carbon.device.application.mgt.core.config;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
@ -37,6 +39,8 @@ public class Configuration {
private PaginationConfiguration paginationConfiguration;
private List<LifecycleState> lifecycleStates;
@XmlElement(name = "DatasourceName", required = true)
public String getDatasourceName() {
return datasourceName;
@ -60,6 +64,17 @@ public class Configuration {
public PaginationConfiguration getPaginationConfiguration() {
return paginationConfiguration;
}
@XmlElementWrapper(name = "LifecycleStates")
@XmlElement(name = "LifecycleState")
public List<LifecycleState> getLifecycleStates() {
return lifecycleStates;
}
public void setLifecycleStates(
List<LifecycleState> lifecycleStates) {
this.lifecycleStates = lifecycleStates;
}
}

@ -81,7 +81,7 @@ public class Extension {
ApplicationManager,
ApplicationReleaseManager,
CategoryManager,
CommentsManager,
ReviewManager,
LifecycleStateManager,
PlatformManager,
VisibilityTypeManager,

@ -18,7 +18,9 @@
*/
package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.util.List;
@ -80,10 +82,18 @@ public interface ApplicationReleaseDAO {
/**
* To update an Application release.
* @param id id of the ApplicationRelease that need to be updated.
* @param stars given stars for the application.
* @param rating given stars for the application.
* @param ratedUsers number of users who has rated for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception
*/
void updateStars(int id, int stars) throws ApplicationManagementDAOException;
int updateRatingValue(int id, double rating, int ratedUsers) throws ApplicationManagementDAOException;
/**
* To retrieve rating of an application release.
* @param id Id of the application Release.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
Rating getRating(int id) throws ApplicationManagementDAOException;
/**

@ -1,405 +0,0 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.core.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 {
/**
* 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 If comment is added successfully, it return true otherwise false
* @throws CommentManagementException Exceptions of the comment management.
* @throws DBConnectionException db connection exception.
*/
boolean 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 DBConnectionException db connection exception
* @throws SQLException sql exception
**/
List<Comment> getAllComments(String uuid, PaginationRequest request) throws 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,136 @@
/*
* 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;
import org.wso2.carbon.device.application.mgt.common.Review;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException;
import java.sql.SQLException;
import java.util.List;
/**
* This interface specifies the database access operations performed for comments.
*/
public interface ReviewDAO {
/**
* To add a review to a application.
*
* @param tenantId tenantId of the commented application.
* @param review review of the application.
* @return If review is added successfully, it return true otherwise false
* @throws ReviewManagementDAOException Exceptions of the review management DAO.
*/
boolean addReview(Review review, int appId, int appReleaseId, int tenantId) throws ReviewManagementDAOException;
Review isExistReview(int appId, int appReleaseId, String username, int tenantId)
throws DBConnectionException, SQLException;
/**
* To update already added comment.
*
* @return {@link Review}Updated comment
* @throws ReviewManagementException Exceptions of the comment management.
* @throws DBConnectionException db connection exception
* @throws SQLException sql exception
*/
boolean updateReview(Review review, int reviewId, int tenantId)
throws ReviewManagementException, DBConnectionException, SQLException;
/**
* To get the comment with id.
*
* @param commentId id of the comment
* @return {@link Review}Review
* @throws ReviewManagementException Exceptions of the comment management.
* @throws DBConnectionException db connection exception
* @throws SQLException sql exception
*/
Review getComment(int commentId) throws ReviewManagementException, SQLException, DBConnectionException;
/**
* To get all the comments
*
* @param uuid uuid of the application
* @param request {@link PaginationRequest}pagination request with offSet and limit
* @param tenantId Tenant id
* @return {@link List}List of all the comments in an application
* @throws ReviewManagementDAOException Review management DAO exception
**/
List<Review> getAllReviews(String uuid, PaginationRequest request, int tenantId)
throws ReviewManagementDAOException;
/**
* To get list of comments using release id and application id.
*
* @return {@link List}List of comments
* @throws ReviewManagementException Exceptions of the comment management.
*/
List<Integer> getAllRatingValues(String uuid)throws SQLException, DBConnectionException;
/**
* 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 ReviewManagementException Exceptions of the comment management.
* @throws DBConnectionException db connection exception.
* @throws SQLException sql exception
*/
int getCommentCountByApp(String appType, String appName, String version)
throws ReviewManagementException, DBConnectionException, SQLException;
/**
* To delete comment using comment id.
*
* @param commentId id of the comment
* @throws ReviewManagementException Exceptions of the comment management.
* @throws DBConnectionException db connection exception.
* @throws SQLException sql exception
*/
void deleteComment(int commentId) throws ReviewManagementException, 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 ReviewManagementException Exceptions of the comment management.
*/
void deleteComments(String appType, String appName, String version) throws ReviewManagementException;
/**
* To get comment count for pagination
*
* @param request
* @param uuid
* @return Review count
* @throws ReviewManagementException
*/
int getCommentCount(PaginationRequest request, String uuid) throws ReviewManagementException;
}

@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.dao.*;
import org.wso2.carbon.device.application.mgt.core.dao.impl.Comment.CommentDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.Comment.ReviewDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.release.GenericApplicationReleaseDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.OracleApplicationDAOImpl;
@ -162,13 +162,13 @@ public class ApplicationManagementDAOFactory {
throw new IllegalStateException("Database engine has not initialized properly.");
}
public static CommentDAO getCommentDAO() {
public static ReviewDAO getCommentDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2:
case Constants.DataBaseTypes.DB_TYPE_MYSQL:
case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new CommentDAOImpl();
return new ReviewDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}

@ -25,7 +25,7 @@ import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import org.wso2.carbon.device.application.mgt.core.config.Configuration;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
@ -202,14 +202,14 @@ public class Util {
}
public static PaginationRequest validateCommentListPageSize(PaginationRequest paginationRequest) throws
CommentManagementException {
ReviewManagementException {
if (paginationRequest.getLimit() == 0) {
Configuration commentManagementConfig = ConfigurationManager.getInstance().getConfiguration();
if (commentManagementConfig != null) {
paginationRequest.setLimit(
commentManagementConfig.getPaginationConfiguration().getCommentListPageSize());
} else {
throw new CommentManagementException(
throw new ReviewManagementException(
"Application Management configuration has not initialized. Please check the application-mgt.xml file.");
}
}

@ -0,0 +1,366 @@
/*
* 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.Review;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
/**
* This handles ReviewDAO related operations.
*/
public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
private static final Log log = LogFactory.getLog(ReviewDAOImpl.class);
private String sql;
@Override
public boolean addReview(Review review, int appId, int appReleaseId, int tenantId)
throws ReviewManagementDAOException {
//todo
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add review for application release. Application id: " + appId
+ "Application Release id: " + appReleaseId);
}
PreparedStatement statement = null;
ResultSet rs = null;
sql = "INSERT INTO AP_APP_Review (TENANT_ID, COMMENT, PARENT_ID, USERNAME, AP_APP_RELEASE_ID, AP_APP_ID) "
+ "VALUES (?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?),"
+ "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));";
try {
Connection conn = this.getDBConnection();
statement = conn.prepareStatement(sql, new String[] { "id" });
statement.setInt(1, tenantId);
statement.setString(2, review.getComment());
statement.setInt(3, review.getParentId());
statement.setString(4, review.getUsername());
statement.setString(5,"");
statement.setString(6,"");
statement.executeUpdate();
rs = statement.getGeneratedKeys();
return rs.next();
}
catch (DBConnectionException e) {
throw new ReviewManagementDAOException("Error occurred while obtaining the DB connection while "
+ "adding review for application UUID: "+ "Tenant Id: " + tenantId, e);
}catch (SQLException e) {
throw new ReviewManagementDAOException("Error occurred while getting application list for the tenant"
+ " " + tenantId + ". While executing " + sql, e);
} finally {
Util.cleanupResources(statement, rs);
}
}
@Override
public Review isExistReview(int appId, int appReleaseId, String username, int tenantId)
throws DBConnectionException, SQLException {
if (log.isDebugEnabled()) {
log.debug(
"Request received in DAO Layer to check whether review exist or not rein the IoTS APPM. Application id: "
+ appId + " Application release id: " + appReleaseId + " comment owner: " + username);
}
Connection conn;
PreparedStatement statement = null;
ResultSet rs = null;
Review review = null;
sql = "SELECT ID, COMMENT, CREATED_AT, MODEFIED_AT, USERNAME, PARENT_ID, RATING FROM AP_APP_REVIEW WHERE "
+ "AP_APP_ID = ? AND AP_APP_RELEASE_ID = ? AND USERNAME = ? AND TENANT_ID = ?;";
try {
conn = this.getDBConnection();
statement = conn.prepareStatement(sql);
statement.setInt(1, appId);
statement.setInt(2, appReleaseId);
statement.setString(3, username);
statement.setInt(4, tenantId);
rs = statement.executeQuery();
if (rs.next()){
review = new Review();
review.setId(rs.getInt("ID"));
review.setComment(rs.getString("COMMENT"));
review.setParentId(rs.getInt("PARENT_ID"));
review.setCreatedAt(rs.getTimestamp("CREATED_AT"));
review.setModifiedAt(rs.getTimestamp("MODIFIED_AT"));
review.setUsername(rs.getString("USERNAME"));
review.setRating(rs.getInt("RATING"));
}
return review;
} finally {
Util.cleanupResources(statement, rs);
}
}
@Override
public boolean updateReview(Review review, int reviewId, int tenantId) throws ReviewManagementException, DBConnectionException, SQLException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to update the comment with ID (" + reviewId + ")");
}
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, reviewId);
statement.executeUpdate();
rs = statement.executeQuery();
} finally {
Util.cleanupResources(statement, rs);
}
// todo
return false;
}
@Override
public Review getComment(int commentId) throws ReviewManagementException {
if (log.isDebugEnabled()) {
log.debug("Getting review with the review id(" + commentId + ") from the database");
}
Connection conn;
PreparedStatement statement = null;
ResultSet rs;
Review review = new Review();
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()) {
review.setId(rs.getInt("ID"));
// review.setTenantId(rs.getInt("TENANT_ID"));
review.setComment(rs.getString("COMMENT_TEXT"));
review.setCreatedAt(rs.getTimestamp("CREATED_AT"));
review.setUsername(rs.getString("CREATED_BY"));
review.setModifiedAt(rs.getTimestamp("MODEFIED_AT"));
Util.cleanupResources(statement, rs);
return review;
}
} catch (SQLException e) {
throw new ReviewManagementException(
"SQL Error occurred while retrieving information of the review " + commentId, e);
} catch (DBConnectionException e) {
log.error("DB Connection Exception occurred while retrieving information of the review " + commentId, e);
} finally {
Util.cleanupResources(statement, null);
}
return review;
}
@Override
public List<Review> getAllReviews(String uuid, PaginationRequest request, int tenantId)
throws ReviewManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting comment of the application release (" + uuid + ") from the database");
}
Connection conn;
PreparedStatement statement = null;
ResultSet rs = null;
List<Review> reviews = new ArrayList<>();
try {
conn = this.getDBConnection();
sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS COMMENT_TEXT, "
+ "AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS MODIFIED_BY, "
+ "AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE "
+ "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND "
+ "AP_APP_COMMENT.TENANT_ID = ? AND AP_APP_COMMENT.TENANT_ID = AP_APP_RELEASE.TENANT_ID "
+ "LIMIT ? OFFSET ?;";
statement = conn.prepareStatement(sql);
statement.setString(1, uuid);
statement.setInt(2, tenantId);
statement.setInt(3, request.getLimit());
statement.setInt(4, request.getOffSet());
rs = statement.executeQuery();
while (rs.next()) {
Review review = new Review();
review.setId(rs.getInt("ID"));
review.setComment(rs.getString("COMMENT_TEXT"));
review.setUsername(rs.getString("CREATED_BY"));
reviews.add(review);
}
} catch (DBConnectionException e) {
throw new ReviewManagementDAOException(
"Error occurred while obtaining the DB connection when verifying application existence", e);
} catch (SQLException e) {
throw new ReviewManagementDAOException("Error occurred while adding unrestricted roles", e);
}finally {
Util.cleanupResources(statement, rs);
}
return reviews;
}
@Override
public List<Integer> getAllRatingValues(String uuid)throws SQLException, DBConnectionException {
if (log.isDebugEnabled()) {
log.debug("Getting comment of the application release (" + uuid + ") from the database");
}
Connection conn;
PreparedStatement statement = null;
ResultSet rs = null;
List<Integer> reviews = new ArrayList<>();
try {
conn = this.getDBConnection();
// todo
sql = "SELECT AP_APP_COMMENT.ID AS ID, AP_APP_COMMENT.COMMENT_TEXT AS "
+ "COMMENT_TEXT, AP_APP_COMMENT.CREATED_BY AS CREATED_BY, AP_APP_COMMENT.MODIFIED_BY AS "
+ "MODIFIED_BY, AP_APP_COMMENT.PARENT_ID AS PARENT_ID FROM AP_APP_COMMENT, AP_APP_RELEASE WHERE "
+ "AP_APP_COMMENT.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND "
+ "AP_APP_COMMENT.TENANT_ID = ? AND AP_APP_COMMENT.TENANT_ID = AP_APP_RELEASE.TENANT_ID;";
statement = conn.prepareStatement(sql);
statement.setString(1, uuid);
rs = statement.executeQuery();
while (rs.next()) {
reviews.add(rs.getInt("RATING"));
}
} finally {
Util.cleanupResources(statement, rs);
}
return reviews;
}
@Override
public int getCommentCount(PaginationRequest request, String uuid) throws ReviewManagementException {
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 ReviewManagementException("SQL Error occurred while retrieving count of comments", e);
} catch (DBConnectionException e) {
log.error("DB Connection Exception occurred while retrieving count of comments", e);
} finally {
Util.cleanupResources(statement, rs);
}
return commentCount;
}
@Override
public int getCommentCountByApp(String appType, String appName, String version)
throws ReviewManagementException, 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;
}
@Override
public void deleteComment(int commentId)
throws ReviewManagementException, 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);
}
}
@Override
public void deleteComments(String appType, String appName, String version)
throws ReviewManagementException {
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 ReviewManagementException("SQL Error occurred while deleting comments", e);
} finally {
Util.cleanupResources(statement, null);
}
}
}

@ -380,7 +380,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
Boolean isAppExist = false;
try {
conn = this.getDBConnection();
String sql =
@ -396,13 +395,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application with the application ID " + appId);
}
if (rs.next()) {
isAppExist = true;
}
return isAppExist;
return rs.next();
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application details with app ID " + appId + " While executing query ",

@ -19,11 +19,17 @@
package org.wso2.carbon.device.application.mgt.core.dao.impl.application.release;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.sql.Connection;
@ -39,6 +45,9 @@ import java.util.List;
*/
public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO {
private static final Log log = LogFactory.getLog(GenericApplicationReleaseDAOImpl.class);
/**
* To insert the Application Release Details.
*
@ -268,20 +277,21 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* To Update starts of an application release.
*
* @param id Id of the application Release.
* @param stars given stars for the application release.
* @param rating given stars for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
@Override
public void updateStars(int id, int stars) throws ApplicationManagementDAOException {
public int updateRatingValue(int id, double rating, int ratedUsers) throws ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
String sql = "UPDATE AP_APP_RELEASE SET STARS = ? WHERE ID = ?;";
String sql = "UPDATE AP_APP_RELEASE SET RATING = ? AND RATED_USERS = ? WHERE ID = ?;";
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
statement.setInt(1, stars);
statement.setDouble(1, rating);
statement.setInt(2, ratedUsers);
statement.setInt(2, id);
statement.executeUpdate();
return statement.executeUpdate();
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database connection exception while trying to update the application release", e);
@ -293,6 +303,42 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
}
}
/**
* To retrieve rating of an application release.
*
* @param id Id of the application Release.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
@Override
public Rating getRating(int id) throws ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
ResultSet resultSet = null;
Rating rating = null;
String sql = "SELECT RATING, RATED_USERS FROM AP_APP_RELEASE WHERE ID = ?;";
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
statement.setInt(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()){
rating = new Rating();
rating.setRatingValue(resultSet.getDouble("RATING"));
rating.setNoOfUsers(resultSet.getInt("RATED_USERS"));
}
return rating;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database connection exception while trying to update the application release", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"SQL exception while updating the release ,while executing the query " + sql, e);
} finally {
Util.cleanupResources(statement, resultSet);
}
}
/**
* To insert the application release properties.
*
@ -369,7 +415,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
}
/**
* This method is capable to construct {@ApplicationRelease} and return the object
* This method is capable to construct {@link ApplicationRelease} and return the object
* @param resultSet result set obtained from the query executing.
* @throws SQLException SQL exception while accessing result set data.
*/

@ -0,0 +1,35 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.core.exception;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
/**
* Exception thrown during the Review Management DAO operations.
*/
public class ReviewManagementDAOException extends ReviewManagementException {
public ReviewManagementDAOException(String message, Throwable throwable) {
super(message, throwable);
}
public ReviewManagementDAOException(String message) {
super(message, new Exception());
}
}

@ -37,7 +37,6 @@ import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole;
import org.wso2.carbon.device.application.mgt.common.User;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
@ -49,6 +48,7 @@ import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagement
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.exception.ValidationException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
@ -73,10 +73,12 @@ public class ApplicationManagerImpl implements ApplicationManager {
private ApplicationDAO applicationDAO;
private ApplicationReleaseDAO applicationReleaseDAO;
private LifecycleStateDAO lifecycleStateDAO;
private LifecycleStateManger lifecycleStateManger;
public ApplicationManagerImpl() {
initDataAccessObjects();
lifecycleStateManger = DataHolder.getInstance().getLifecycleStateManager();
}
private void initDataAccessObjects() {
@ -139,7 +141,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString());
lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString());
addLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState);
changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState);
applicationRelease.setLifecycleState(lifecycleState);
applicationReleases.add(applicationRelease);
@ -216,7 +218,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString());
lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString());
addLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState);
changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState);
ConnectionManagerUtil.commitDBTransaction();
return applicationRelease;
@ -406,7 +408,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState newAppLifecycleState = new LifecycleState();
newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState());
newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString());
addLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState);
changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState);
storedLocations.add(applicationRelease.getAppHashValue());
}
ConnectionManagerUtil.openDBConnection();
@ -437,7 +439,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState newAppLifecycleState = new LifecycleState();
newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState());
newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString());
addLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState);
changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState);
}else{
throw new ApplicationManagementException("Can't delete the application release, You have to move the " +
"lifecycle state from "+ currentState + " to acceptable " +
@ -689,7 +691,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
+ applicationUuid);
}
lifecycleState.setNextStates(getNextLifecycleStates(lifecycleState.getCurrentState()));
lifecycleState.setNextStates(new ArrayList<>(lifecycleStateManger.
getNextLifecycleStates(lifecycleState.getCurrentState())));
} catch (ApplicationManagementDAOException e) {
throw new ApplicationManagementException("Failed to get lifecycle state", e);
} catch (ApplicationManagementException e) {
@ -701,7 +704,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
@Override
public void addLifecycleState(int applicationId, String applicationUuid, LifecycleState state)
public void changeLifecycleState(int applicationId, String applicationUuid, LifecycleState state)
throws ApplicationManagementException {
try {
ConnectionManagerUtil.openDBConnection();
@ -712,9 +715,14 @@ public class ApplicationManagerImpl implements ApplicationManager {
state.setUpdatedBy(userName);
if (state.getCurrentState() != null && state.getPreviousState() != null) {
validateLifecycleState(state);
this.lifecycleStateDAO
.addLifecycleState(state, application.getId(), applicationRelease.getId(), tenantId);
if (lifecycleStateManger.isValidStateChange(state.getPreviousState(), state.getCurrentState())) {
this.lifecycleStateDAO
.addLifecycleState(state, application.getId(), applicationRelease.getId(), tenantId);
} else {
log.error("Invalid lifecycle state transition from '" + state.getPreviousState() + "'"
+ " to '" + state.getCurrentState() + "'");
throw new ApplicationManagementException("Lifecycle State Validation failed");
}
}
} catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new ApplicationManagementException("Failed to add lifecycle state", e);
@ -725,99 +733,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
}
private List<String> getNextLifecycleStates(String currentLifecycleState) {
List<String> nextLifecycleStates = new ArrayList<>();
if (AppLifecycleState.CREATED.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.IN_REVIEW.toString());
}
if (AppLifecycleState.IN_REVIEW.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.APPROVED.toString());
nextLifecycleStates.add(AppLifecycleState.REJECTED.toString());
}
if (AppLifecycleState.REJECTED.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.IN_REVIEW.toString());
nextLifecycleStates.add(AppLifecycleState.REMOVED.toString());
}
if (AppLifecycleState.APPROVED.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.PUBLISHED.toString());
}
if (AppLifecycleState.PUBLISHED.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.UNPUBLISHED.toString());
nextLifecycleStates.add(AppLifecycleState.DEPRECATED.toString());
}
if (AppLifecycleState.UNPUBLISHED.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.PUBLISHED.toString());
nextLifecycleStates.add(AppLifecycleState.REMOVED.toString());
}
if (AppLifecycleState.DEPRECATED.toString().equals(currentLifecycleState)) {
nextLifecycleStates.add(AppLifecycleState.REMOVED.toString());
}
return nextLifecycleStates;
}
private void validateLifecycleState(LifecycleState state) throws LifecycleManagementException {
if (AppLifecycleState.CREATED.toString().equals(state.getCurrentState())) {
throw new LifecycleManagementException("Current State Couldn't be " + state.getCurrentState());
}
if (AppLifecycleState.IN_REVIEW.toString().equals(state.getCurrentState()) && !AppLifecycleState.CREATED
.toString().equals(state.getPreviousState()) && !AppLifecycleState.REJECTED.toString()
.equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be either "
+ AppLifecycleState.CREATED.toString() + " or " + AppLifecycleState.REJECTED.toString());
}
if (AppLifecycleState.APPROVED.toString().equals(state.getCurrentState()) && !AppLifecycleState.IN_REVIEW
.toString().equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be "
+ AppLifecycleState.IN_REVIEW.toString());
}
if (AppLifecycleState.PUBLISHED.toString().equals(state.getCurrentState()) && !AppLifecycleState.APPROVED
.toString().equals(state.getPreviousState()) && !AppLifecycleState.UNPUBLISHED.toString()
.equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be either "
+ AppLifecycleState.APPROVED.toString() + " or " + AppLifecycleState.UNPUBLISHED
.toString());
}
if (AppLifecycleState.UNPUBLISHED.toString().equals(state.getCurrentState()) && !AppLifecycleState.PUBLISHED
.toString().equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be "
+ AppLifecycleState.PUBLISHED.toString());
}
if (AppLifecycleState.REJECTED.toString().equals(state.getCurrentState()) && !AppLifecycleState.IN_REVIEW
.toString().equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be "
+ AppLifecycleState.IN_REVIEW.toString());
}
if (AppLifecycleState.DEPRECATED.toString().equals(state.getCurrentState()) && !AppLifecycleState.PUBLISHED
.toString().equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be "
+ AppLifecycleState.PUBLISHED.toString());
}
if (AppLifecycleState.REMOVED.toString().equals(state.getCurrentState()) && !AppLifecycleState.DEPRECATED
.toString().equals(state.getPreviousState()) && !AppLifecycleState.REJECTED.toString()
.equals(state.getPreviousState()) && !AppLifecycleState.UNPUBLISHED.toString()
.equals(state.getPreviousState())) {
throw new LifecycleManagementException(
"If Current State is " + state.getCurrentState() + "Previous State should be either "
+ AppLifecycleState.DEPRECATED.toString() + " or " + AppLifecycleState.REJECTED.toString()
+ " or " + AppLifecycleState.UNPUBLISHED.toString());
}
}
@Override
public Application updateApplication(Application application) throws ApplicationManagementException {

@ -1,289 +0,0 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.Comment;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.common.services.*;
import org.wso2.carbon.device.application.mgt.core.dao.CommentDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* This class is the default implementation for the Managing the comments.
*/
public class CommentsManagerImpl implements CommentsManager {
private static final Log log = LogFactory.getLog(CommentsManagerImpl.class);
private CommentDAO commentDAO;
public CommentsManagerImpl() {
initDataAccessObjects();
}
private void initDataAccessObjects() {
this.commentDAO = ApplicationManagementDAOFactory.getCommentDAO();
}
@Override
public Comment addComment(Comment comment, String uuid) throws CommentManagementException {
if (log.isDebugEnabled()) {
log.debug("Request for comment is received for uuid" + uuid);
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
comment.setCreatedAt(Timestamp.from(Instant.now()));
try {
ConnectionManagerUtil.beginDBTransaction();
if (commentDAO.addComment(tenantId, comment, comment.getCreatedBy(), comment.getParent(), uuid)) {
ConnectionManagerUtil.commitDBTransaction();
return comment;
} else {
ConnectionManagerUtil.rollbackDBTransaction();
return null;
}
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new CommentManagementException(
"DB Connection error occurs ,Comment for application with UUID " + uuid + "cannot add.", e);
} catch (SQLException e) {
throw new CommentManagementException(
"SQL Exception occurs,Comment for application with UUID " + uuid + "cannot add.", e);
} catch (TransactionManagementException e) {
throw new CommentManagementException(
"Transaction Management Exception occurs,Comment for application with UUID " + uuid + "cannot add.",
e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/**
* To validate the pre-request of the comment
*
* @param commentId ID of the comment.
* @param comment comment needed to be validate.
* @return Application related with the UUID.
* @throws CommentManagementException Exceptions of the comment management.
*/
public Boolean validateComment(int commentId, String comment) throws CommentManagementException {
if (commentId <= 0) {
throw new CommentManagementException(
"Comment ID is null or negative. Comment id is a required parameter to get the "
+ "relevant comment.");
}
if (comment == null) {
log.error("Comment can not be null, but Comment at comment id " + commentId + " is null.");
return false;
}
return true;
}
@Override
public PaginationResult getAllComments(PaginationRequest request, String uuid) throws CommentManagementException {
PaginationResult paginationResult = new PaginationResult();
int numOfComments;
List<Comment> comments;
if (log.isDebugEnabled()) {
log.debug("get all comments of the application release" + uuid);
}
try {
ConnectionManagerUtil.openDBConnection();
comments = commentDAO.getAllComments(uuid, Util.validateCommentListPageSize(request));
numOfComments = comments.size();
paginationResult.setData(comments);
if (numOfComments > 0) {
paginationResult.setRecordsFiltered(numOfComments);
paginationResult.setRecordsTotal(numOfComments);
} else {
paginationResult.setRecordsFiltered(0);
paginationResult.setRecordsTotal(0);
}
return paginationResult;
} catch (DBConnectionException e) {
throw new CommentManagementException(
"DB Connection error occurs , while getting comments of application release UUID: " + uuid, e);
} catch (SQLException e) {
throw new CommentManagementException(
"SQL Exception occurs, while getting comments of application release UUID: " + uuid, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public Comment getComment(int commentId) throws CommentManagementException {
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Comment comment;
if (log.isDebugEnabled()) {
log.debug("Comment retrieval request is received for the comment id " + commentId);
}
try {
ConnectionManagerUtil.openDBConnection();
comment = commentDAO.getComment(commentId);
} catch (DBConnectionException e) {
throw new CommentManagementException(
"DB Connection error occurs ,Comment with comment id " + commentId + "cannot get.", e);
} catch (SQLException e) {
throw new CommentManagementException(
"SQL Exception occurs,Comment with comment id " + commentId + "cannot get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
return comment;
}
@Override
public void deleteComment(int commentId) throws CommentManagementException {
Comment comment;
comment = getComment(commentId);
if (comment == null) {
throw new CommentManagementException(
"Cannot delete a non-existing comment for the application with comment id" + commentId);
}
try {
ConnectionManagerUtil.beginDBTransaction();
commentDAO.deleteComment(commentId);
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) {
throw new CommentManagementException(
"DB Connection error occurs deleting comment with comment id " + commentId + ".", e);
} catch (SQLException e) {
throw new CommentManagementException("SQL error occurs deleting comment with comment id " + commentId + ".",
e);
} catch (TransactionManagementException e) {
throw new CommentManagementException(
"Transaction Management Exception occurs deleting comment with comment id " + commentId + ".", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public Comment updateComment(Comment comment, int commentId) throws CommentManagementException {
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
validateComment(commentId, comment.getCommentText());
if (log.isDebugEnabled()) {
log.debug("Comment retrieval request is received for the comment id " + commentId);
}
comment.setModifiedAt(Timestamp.from(Instant.now()));
try {
ConnectionManagerUtil.openDBConnection();
commentDAO.getComment(commentId);
return commentDAO
.updateComment(commentId, comment.getCommentText(), comment.getModifiedBy(), comment.getModifiedAt());
} catch (SQLException e) {
throw new CommentManagementException("SQL Error occurs updating comment with comment id " + commentId + ".",
e);
} catch (DBConnectionException e) {
throw new CommentManagementException(
"DB Connection error occurs updating comment with comment id " + commentId + ".", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public int getRatedUser(String uuid) throws ApplicationManagementException {
int ratedUsers;
if (log.isDebugEnabled()) {
log.debug("Get the rated users for the application release number" + uuid);
}
try {
ConnectionManagerUtil.openDBConnection();
ratedUsers = commentDAO.getRatedUser(uuid);
} catch (ApplicationManagementDAOException e) {
throw new ApplicationManagementException(
"Rated Users of the Application with UUID " + uuid + " can not get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
return ratedUsers;
}
@Override
public int getStars(String uuid) throws ApplicationManagementException {
int stars;
if (log.isDebugEnabled()) {
log.debug("Get the average of rated stars for the application " + uuid);
}
try {
ConnectionManagerUtil.openDBConnection();
stars = commentDAO.getStars(uuid);
} catch (ApplicationManagementDAOException e) {
throw new ApplicationManagementException(
"Average stars of the Application with UUID " + uuid + " can not get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
return stars;
}
@Override
public int updateStars(int stars, String uuid) throws ApplicationManagementException {
if (log.isDebugEnabled()) {
log.debug("Stars are received for the application " + uuid);
}
int newStars;
try {
ConnectionManagerUtil.beginDBTransaction();
int ratedUsers = commentDAO.getRatedUser(uuid);
int oldStars = commentDAO.getStars(uuid);
if (ratedUsers == 0) {
newStars = commentDAO.updateStars(stars, uuid);
return newStars;
} else {
int avgStars = ((oldStars * ratedUsers) + stars) / (ratedUsers + 1);
newStars = commentDAO.updateStars(avgStars, uuid);
ConnectionManagerUtil.commitDBTransaction();
return newStars;
}
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException(
"Updated average stars of the Application with UUID " + uuid + " can not get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -0,0 +1,372 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.Review;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.common.services.*;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
/**
* This class is the default implementation for the Managing the comments.
*/
public class ReviewManagerImpl implements ReviewManager {
private static final Log log = LogFactory.getLog(ReviewManagerImpl.class);
private ReviewDAO reviewDAO;
private ApplicationReleaseDAO applicationReleaseDAO;
public ReviewManagerImpl() {
initDataAccessObjects();
}
private void initDataAccessObjects() {
this.reviewDAO = ApplicationManagementDAOFactory.getCommentDAO();
this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO();
}
@Override public boolean addReview(Review review, int appId, int appReleaseId) throws ReviewManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
boolean isSuccess;
try {
ConnectionManagerUtil.beginDBTransaction();
Review existingReview = reviewDAO.isExistReview(appId, appReleaseId, username, tenantId);
if (existingReview != null && review.getRating() > 0 && review.getRating() != existingReview.getRating()) {
Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating());
new Thread(task).start();
isSuccess = updateReview(review, existingReview.getId(), false);
if (isSuccess) {
ConnectionManagerUtil.commitDBTransaction();
} else {
ConnectionManagerUtil.rollbackDBTransaction();
}
} else {
if (review.getRating() > 0) {
Runnable task = () -> calculateRating(review.getRating(), -12345);
new Thread(task).start();
}
review.setUsername(username);
isSuccess = this.reviewDAO.addReview(review, appId, appReleaseId, tenantId);
if (isSuccess) {
ConnectionManagerUtil.commitDBTransaction();
} else {
ConnectionManagerUtil.rollbackDBTransaction();
}
}
return isSuccess;
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException(
"DB Connection error occurs ,Review for application with app id: " + appId + " and app release id: "
+ appReleaseId + " is failed", e);
} catch (SQLException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException(
"SQL Exception occurs,Review for application with app id:" + appId + " and app release id:"
+ appReleaseId + " is failed", e);
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException(
"Transaction Management Exception occurs,Review for application with app id:" + appId
+ " and app release id:" + appReleaseId + " is failed ", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override public boolean updateReview(Review review, int reviewId, boolean checkExistence)
throws ReviewManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Review existingReview;
boolean isSuccess;
if (log.isDebugEnabled()) {
log.debug("Review updating request is received for the review id " + reviewId);
}
try {
ConnectionManagerUtil.openDBConnection();
// todo
if (!username.equals(review.getUsername())) {
throw new ReviewManagementException(
"User " + review.getUsername() + "doesn't match with the logged in user: " + username);
}
if (checkExistence) {
existingReview = this.reviewDAO.getComment(reviewId);
if (existingReview != null) {
if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) {
Runnable task = () -> calculateRating(review.getRating(), existingReview.getRating());
new Thread(task).start();
}
} else {
throw new ReviewManagementException("Couldn't find a review for review id: " + reviewId);
}
}
ConnectionManagerUtil.beginDBTransaction();
isSuccess = this.reviewDAO.updateReview(review, reviewId, tenantId);
if (isSuccess) {
ConnectionManagerUtil.commitDBTransaction();
} else {
ConnectionManagerUtil.rollbackDBTransaction();
}
return isSuccess;
} catch (SQLException e) {
throw new ReviewManagementException("SQL Error occurs updating review with review id " + reviewId + ".",
e);
} catch (DBConnectionException e) {
throw new ReviewManagementException(
"DB Connection error occurs updating review with review id " + reviewId + ".", e);
} catch (TransactionManagementException e) {
throw new ReviewManagementException(
"Transaction management error occurs when updating review with review id " + reviewId + ".", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public PaginationResult getAllReviews(PaginationRequest request, String uuid)
throws ReviewManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
PaginationResult paginationResult = new PaginationResult();
int numOfComments;
List<Review> reviews;
TreeMap<Integer, Review> hierarchicalReviewSet = new TreeMap<>();
if (log.isDebugEnabled()) {
log.debug("Get all reviews of the application release uuid: " + uuid);
}
try {
ConnectionManagerUtil.openDBConnection();
reviews = this.reviewDAO.getAllReviews(uuid, Util.validateCommentListPageSize(request), tenantId);
for (Review review : reviews) {
if (hierarchicalReviewSet.containsKey(review.getParentId())) {
Review parentReview = hierarchicalReviewSet.get(review.getParentId());
parentReview.setReplyReview(review);
hierarchicalReviewSet.replace(review.getParentId(), parentReview);
} else {
hierarchicalReviewSet.put(review.getId(), review);
}
}
numOfComments = hierarchicalReviewSet.size();
if (numOfComments > 0) {
paginationResult.setData(new ArrayList<>(hierarchicalReviewSet.values()));
paginationResult.setRecordsFiltered(numOfComments);
paginationResult.setRecordsTotal(numOfComments);
} else {
paginationResult.setData(new ArrayList<Review>());
paginationResult.setRecordsFiltered(0);
paginationResult.setRecordsTotal(0);
}
return paginationResult;
} catch (ReviewManagementDAOException e) {
throw new ReviewManagementException("Error occured while getting all reviews for application uuid: " + uuid,
e);
} catch (DBConnectionException e) {
throw new ReviewManagementException("Error occured while getting the DB connection.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override public Review getReview(int commentId) throws ReviewManagementException {
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Review review;
if (log.isDebugEnabled()) {
log.debug("Review retrieval request is received for the review id " + commentId);
}
try {
ConnectionManagerUtil.openDBConnection();
review = this.reviewDAO.getComment(commentId);
} catch (DBConnectionException e) {
throw new ReviewManagementException(
"DB Connection error occurs ,Review with review id " + commentId + "cannot get.", e);
} catch (SQLException e) {
throw new ReviewManagementException(
"SQL Exception occurs,Review with review id " + commentId + "cannot get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
return review;
}
@Override public void deleteReview(String loggedInUser, int commentId) throws ReviewManagementException {
Review existingReview;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
try {
if (!loggedInUser.equals(username) && !isAdminUser(username, tenantId,
CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
throw new ReviewManagementException(
"You don't have permission to delete the review. Please contact the administrator. Review Id: "
+ commentId);
}
existingReview = getReview(commentId);
if (existingReview == null) {
throw new ReviewManagementException(
"Cannot delete a non-existing review for the application with review id" + commentId);
}
Runnable task = () -> calculateRating(0, existingReview.getRating());
new Thread(task).start();
ConnectionManagerUtil.beginDBTransaction();
this.reviewDAO.deleteComment(commentId);
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) {
throw new ReviewManagementException(
"DB Connection error occurs deleting review with review id " + commentId + ".", e);
} catch (SQLException e) {
throw new ReviewManagementException("SQL error occurs deleting review with review id " + commentId + ".",
e);
} catch (TransactionManagementException e) {
throw new ReviewManagementException(
"Transaction Management Exception occurs deleting review with review id " + commentId + ".", e);
} catch (UserStoreException e) {
throw new ReviewManagementException(
"User-store exception while checking whether the user " + username + " of tenant " + tenantId
+ " has the publisher permission");
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override public Rating getRating(String appReleaseUuuid) throws ReviewManagementException {
//todo
int appReleaseId = 0;
try {
ConnectionManagerUtil.openDBConnection();
Rating rating = this.applicationReleaseDAO.getRating(appReleaseId);
if (rating == null) {
throw new ReviewManagementException("Couldn't find rating for application release id: " + appReleaseId
+ ". Please check the existence of the application relese");
}
List<Integer> ratingValues = this.reviewDAO.getAllRatingValues(appReleaseUuuid);
TreeMap<Integer, Integer> ratingVariety = rating.getRatingVariety();
for (Integer ratingVal : ratingValues) {
if (ratingVariety.containsKey(ratingVal)) {
ratingVariety.replace(ratingVal, ratingVariety.get(ratingVal) + 1);
} else {
ratingVariety.put(ratingVal, 1);
}
}
rating.setRatingVariety(ratingVariety);
return rating;
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException(
"Error occured while updated the rating value of the application release id: " + appReleaseId
+ " can not get.", e);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ReviewManagementException(
"DB Connection error occured while updated the rating value of the application release id: "
+ appReleaseId + " can not get.", e);
} catch (SQLException e) {
throw new ReviewManagementException(
"DB Connection error occured while updated the rating value of the application release id: "
+ appReleaseId + " can not get.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
private void calculateRating(int newRatingVal, int oldRatingVal) {
// todo need to pass app release id
int appReleaseId = 0;
try {
ConnectionManagerUtil.beginDBTransaction();
Rating rating = this.applicationReleaseDAO.getRating(appReleaseId);
if (rating == null) {
log.error("Couldn't find rating for application release id: " + appReleaseId);
} else {
double updatedRating;
int numOfUsers = rating.getNoOfUsers();
double currentRating = rating.getRatingValue() * numOfUsers;
if (oldRatingVal == -12345) {
updatedRating = (currentRating + newRatingVal) / (numOfUsers + 1);
this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers + 1);
} else if (newRatingVal == 0) {
updatedRating = (currentRating - newRatingVal) / (numOfUsers - 1);
this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers - 1);
} else {
double tmpVal;
tmpVal = currentRating - oldRatingVal;
updatedRating = (tmpVal + newRatingVal) / numOfUsers;
this.applicationReleaseDAO.updateRatingValue(appReleaseId, updatedRating, numOfUsers);
}
}
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
log.error("Error occured while updated the rating value of the application release id: " + appReleaseId
+ " can not get.");
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
log.error(
"Transaction Management Exception occured while updated the rating value of the application release id: "
+ appReleaseId + " can not get.");
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
log.error("DB Connection error occured while updated the rating value of the application release id: "
+ appReleaseId + " can not get.");
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/**
* To check whether current user has the permission to do some secured operation.
*
* @param username Name of the User.
* @param tenantId ID of the tenant.
* @param permission Permission that need to be checked.
* @return true if the current user has the permission, otherwise false.
* @throws UserStoreException UserStoreException
*/
private boolean isAdminUser(String username, int tenantId, String permission) throws UserStoreException {
UserRealm userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
return userRealm != null && userRealm.getAuthorizationManager() != null && userRealm.getAuthorizationManager()
.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission,
CarbonConstants.UI_PERMISSION_ACTION);
}
}

@ -28,7 +28,7 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.dao.SubscriptionDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.mgt.common.Device;
@ -69,7 +69,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
if (log.isDebugEnabled()) {
log.debug("Install application: " + applicationUUID + " to " + deviceList.size() + "devices.");
}
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID);
return installApplication(application, deviceList);
@ -81,7 +81,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
if (log.isDebugEnabled()) {
log.debug("Install application: " + applicationUUID + " to " + userList.size() + " users.");
}
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID);
List<DeviceIdentifier> deviceList = new ArrayList<>();
for (String user : userList) {
@ -122,7 +122,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
if (log.isDebugEnabled()) {
log.debug("Install application: " + applicationUUID + " to " + roleList.size() + " roles.");
}
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID);
List<DeviceIdentifier> deviceList = new ArrayList<>();
for (String role : roleList) {
@ -163,7 +163,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
if (log.isDebugEnabled()) {
log.debug("Install application: " + applicationUUID + " to " + deviceGroupList.size() + " groups.");
}
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID);
GroupManagementProviderService groupManagementProviderService = HelperUtil.getGroupManagementProviderService();
List<DeviceGroup> groupList = new ArrayList<>();

@ -25,18 +25,21 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.user.core.service.RealmService;
import javax.naming.NamingException;
import java.util.List;
/**
* @scr.component name="org.wso2.carbon.application.mgt.service" immediate="true"
@ -60,23 +63,28 @@ import javax.naming.NamingException;
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
*/
public class ServiceComponent {
public class ApplicationManagementServiceComponent {
private static Log log = LogFactory.getLog(ServiceComponent.class);
private static Log log = LogFactory.getLog(ApplicationManagementServiceComponent.class);
protected void activate(ComponentContext componentContext) throws NamingException {
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
log.info("CALLING ACTIVATE .............");
BundleContext bundleContext = componentContext.getBundleContext();
try {
String datasourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
ApplicationManagementDAOFactory.init(dataSourceName);
// ApplicationManagementDAOFactory.initDatabases();
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
DataHolder.getInstance().setApplicationManager(applicationManager);
bundleContext.registerService(ApplicationManager.class.getName(), applicationManager, null);
CommentsManager commentsManager = ApplicationManagementUtil.getCommentsManagerInstance();
DataHolder.getInstance().setCommentsManager(commentsManager);
bundleContext.registerService(CommentsManager.class.getName(), commentsManager, null);
ReviewManager reviewManager = ApplicationManagementUtil.getReviewManagerInstance();
DataHolder.getInstance().setReviewManager(reviewManager);
bundleContext.registerService(ReviewManager.class.getName(), reviewManager, null);
SubscriptionManager subscriptionManager = ApplicationManagementUtil.getSubscriptionManagerInstance();
DataHolder.getInstance().setSubscriptionManager(subscriptionManager);
@ -91,13 +99,14 @@ public class ServiceComponent {
DataHolder.getInstance().setApplicationStorageManager(applicationStorageManager);
bundleContext.registerService(ApplicationStorageManager.class.getName(), applicationStorageManager, null);
ApplicationManagementDAOFactory.init(datasourceName);
ApplicationManagementDAOFactory.initDatabases();
List<LifecycleState> lifecycleStates = ConfigurationManager.getInstance().
getConfiguration().getLifecycleStates();
LifecycleStateManger lifecycleStateManger = new LifecycleStateManger(lifecycleStates);
DataHolder.getInstance().setLifecycleStateManger(lifecycleStateManger);
log.info("ApplicationManagement core bundle has been successfully initialized");
} catch (InvalidConfigurationException e) {
log.error("Error while activating Application Management core component. ", e);
} catch (ApplicationManagementDAOException e) {
log.error("Error while activating Application Management core component.Failed to create the database ", e);
} catch (Throwable e) {
log.error("Error occurred while initializing app management core bundle", e);
}
}

@ -20,9 +20,10 @@ package org.wso2.carbon.device.application.mgt.core.internal;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.user.core.service.RealmService;
@ -37,7 +38,7 @@ public class DataHolder {
private ApplicationManager applicationManager;
private CommentsManager commentsManager;
private ReviewManager reviewManager;
private SubscriptionManager subscriptionManager;
@ -45,6 +46,8 @@ public class DataHolder {
private ApplicationStorageManager applicationStorageManager;
private LifecycleStateManger lifecycleStateManger;
private static final DataHolder applicationMgtDataHolder = new DataHolder();
private DataHolder() {
@ -71,12 +74,12 @@ public class DataHolder {
this.applicationManager = applicationManager;
}
public CommentsManager getCommentsManager() {
return commentsManager;
public ReviewManager getReviewManager() {
return reviewManager;
}
public void setCommentsManager(CommentsManager commentsManager) {
this.commentsManager = commentsManager;
public void setReviewManager(ReviewManager reviewManager) {
this.reviewManager = reviewManager;
}
public SubscriptionManager getSubscriptionManager() {
@ -110,4 +113,12 @@ public class DataHolder {
public ApplicationStorageManager getApplicationStorageManager() {
return applicationStorageManager;
}
public LifecycleStateManger getLifecycleStateManager() {
return lifecycleStateManger;
}
public void setLifecycleStateManger(LifecycleStateManger lifecycleStateManger) {
this.lifecycleStateManger = lifecycleStateManger;
}
}

@ -0,0 +1,34 @@
package org.wso2.carbon.device.application.mgt.core.lifecycle;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This class represents the activities related to lifecycle management
*/
public class LifecycleStateManger {
private Map<String, State> lifecycleStates;
public LifecycleStateManger(List<LifecycleState> states) {
lifecycleStates = new HashMap<>();
for (LifecycleState s : states) {
lifecycleStates.put(s.getName(), new State(s.getName(), s.getProceedingStates()));
}
}
public Set<String> getNextLifecycleStates(String currentLifecycleState) {
return lifecycleStates.get(currentLifecycleState).getProceedingStates();
}
public boolean isValidStateChange(String currentState, String nextState) {
if (lifecycleStates.get(currentState).getProceedingStates().contains(nextState)) {
return true;
}
return false;
}
}

@ -0,0 +1,30 @@
package org.wso2.carbon.device.application.mgt.core.lifecycle;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class represents the state of the lifecycle
*/
public class State {
private Set<String> proceedingStates;
private String stateName;
public State(String stateName, List<String> states) {
this.stateName = stateName;
if (states != null && !states.isEmpty()) {
proceedingStates = new HashSet<>(states);
}
}
public String getState() {
return stateName;
}
public Set<String> getProceedingStates() {
return proceedingStates;
}
}

@ -0,0 +1,35 @@
package org.wso2.carbon.device.application.mgt.core.lifecycle.config;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.List;
/**
* This class represents the lifecycle state config
*/
public class LifecycleState {
private String name;
private List<String> proceedingStates;
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "ProceedingStates")
@XmlElement(name = "State")
public List<String> getProceedingStates() {
return proceedingStates;
}
public void setProceedingStates(List<String> proceedingStates) {
this.proceedingStates = proceedingStates;
}
}

@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
@ -45,10 +45,10 @@ public class ApplicationManagementUtil {
return getInstance(extension, ApplicationManager.class);
}
public static CommentsManager getCommentsManagerInstance() throws InvalidConfigurationException {
public static ReviewManager getReviewManagerInstance() throws InvalidConfigurationException {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Extension extension = configurationManager.getExtension(Extension.Name.CommentsManager);
return getInstance(extension, CommentsManager.class);
Extension extension = configurationManager.getExtension(Extension.Name.ReviewManager);
return getInstance(extension, ReviewManager.class);
}
public static UnrestrictedRoleManager getVisibilityManagerInstance() throws InvalidConfigurationException {

@ -17,25 +17,30 @@
*/
package org.wso2.carbon.device.application.mgt.core;
import org.junit.BeforeClass;
import org.junit.Test;
import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException;
import org.junit.Assert;
import org.testng.annotations.Test;
import org.wso2.carbon.device.application.mgt.core.config.Configuration;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
import java.io.File;
import java.util.List;
public class ConfigurationTest {
@BeforeClass
public static void init() throws InvalidConfigurationException {
File configPath = new File("src/test/resources/application-mgt.xml");
ConfigurationManager.setConfigLocation(configPath.getAbsolutePath());
@Test
public void validateConfiguration() {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Configuration configuration = configurationManager.getConfiguration();
Assert.assertNotNull("Invalid app manager configuration", configuration);
}
@Test
public void validateConfiguration() {
public void validateLifecycleStateConfiguration() {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Configuration configuration = configurationManager.getConfiguration();
List<LifecycleState> lifecycleStates = configuration.getLifecycleStates();
Assert.assertNotNull("Invalid lifecycle states configuration", lifecycleStates);
Assert.assertTrue("Invalid lifecycle states configuration. Lifecycle states cannot be empty",
!lifecycleStates.isEmpty());
}
}

@ -0,0 +1,20 @@
package org.wso2.carbon.device.application.mgt.core;
import org.testng.annotations.BeforeSuite;
import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import java.io.File;
/**
* This class initializes the required configurations prior running the tests
*/
public class InitTest {
@BeforeSuite
public void init() throws InvalidConfigurationException {
File configPath = new File("src/test/resources/application-mgt.xml");
ConfigurationManager.setConfigLocation(configPath.getAbsolutePath());
}
}

@ -0,0 +1,57 @@
package org.wso2.carbon.device.application.mgt.core;
import org.junit.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.application.mgt.core.config.Configuration;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
import java.util.List;
import java.util.Set;
public class LifecycleManagementTest {
private List<LifecycleState> lifecycleStates;
private LifecycleStateManger lifecycleStateManger;
private final String CURRENT_STATE = "Approved";
private final String NEXT_STATE = "Published";
private final String BOGUS_STATE = "Removed";
@BeforeClass
public void init() {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Configuration configuration = configurationManager.getConfiguration();
lifecycleStates = configuration.getLifecycleStates();
lifecycleStateManger = new LifecycleStateManger(lifecycleStates);
}
@Test
public void checkValidNextLifecycleState() {
Set<String> proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE);
Assert.assertTrue("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(NEXT_STATE));
}
@Test
public void checkInvalidNextLifecycleState() {
Set<String> proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE);
Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(BOGUS_STATE));
}
@Test
public void checkValidStateChange() {
Assert.assertTrue("Invalid state transition from: " + CURRENT_STATE + " to: " + NEXT_STATE,
lifecycleStateManger.isValidStateChange(CURRENT_STATE, NEXT_STATE));
}
@Test
public void checkInvalidStateChange() {
Assert.assertFalse("Invalid state transition from: " + CURRENT_STATE + " to: " + BOGUS_STATE,
lifecycleStateManger.isValidStateChange(CURRENT_STATE, BOGUS_STATE));
}
}

@ -39,7 +39,7 @@
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.CategoryManagerImpl</ClassName>
</Extension>
<Extension name="CommentsManager">
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.CommentsManagerImpl</ClassName>
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.ReviewManagerImpl</ClassName>
</Extension>
<Extension name="LifecycleStateManager">
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.LifecycleStateManagerImpl</ClassName>
@ -58,4 +58,47 @@
</Extension>
</Extensions>
<LifecycleStates>
<LifecycleState name="Created">
<ProceedingStates>
<State>In-Review</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="In-Review">
<ProceedingStates>
<State>Rejected</State>
<State>Approved</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Approved">
<ProceedingStates>
<State>Published</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Rejected">
<ProceedingStates>
<State>In-Review</State>
<State>Removed</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Published">
<ProceedingStates>
<State>Unpublished</State>
<State>Deprecated</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Unpublished">
<ProceedingStates>
<State>Removed</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Deprecated">
<ProceedingStates>
<State>Removed</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Removed">
</LifecycleState>
</LifecycleStates>
</ApplicationManagementConfiguration>

@ -22,8 +22,11 @@
<suite name="ApplicationManagementCore">
<test name="Util classes tests" preserve-order="true">
<classes>
<class name="org.wso2.carbon.device.application.mgt.core.InitTest"/>
<class name="org.wso2.carbon.device.application.mgt.core.ArtifactParserTest"/>
<class name="org.wso2.carbon.device.application.mgt.core.StorageManagementUtilTest"/>
<class name="org.wso2.carbon.device.application.mgt.core.ConfigurationTest"/>
<class name="org.wso2.carbon.device.application.mgt.core.LifecycleManagementTest"/>
</classes>
</test>
</suite>

@ -0,0 +1,120 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.application.mgt.publisher.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import javax.validation.*;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
public class ValidationInterceptor extends AbstractPhaseInterceptor<Message> {
private Log log = LogFactory.getLog(getClass());
private Validator validator = null; //validator interface is thread-safe
public ValidationInterceptor() {
super(Phase.PRE_INVOKE);
ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory();
validator = defaultFactory.getValidator();
if (validator == null) {
log.warn("Bean Validation provider could not be found, no validation will be performed");
} else {
log.debug("Validation In-Interceptor initialized successfully");
}
}
@Override
public void handleMessage(Message message) throws Fault {
final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
if (operationResource == null) {
log.info("OperationResourceInfo is not available, skipping validation");
return;
}
final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
if (classResource == null) {
log.info("ClassResourceInfo is not available, skipping validation");
return;
}
final ResourceProvider resourceProvider = classResource.getResourceProvider();
if (resourceProvider == null) {
log.info("ResourceProvider is not available, skipping validation");
return;
}
final List<Object> arguments = MessageContentsList.getContentsList(message);
final Method method = operationResource.getAnnotatedMethod();
final Object instance = resourceProvider.getInstance(message);
if (method != null && arguments != null) {
//validate the parameters(arguments) over the invoked method
validate(method, arguments.toArray(), instance);
//validate the fields of each argument
for (Object arg : arguments) {
if (arg != null)
validate(arg);
}
}
}
public <T> void validate(final Method method, final Object[] arguments, final T instance) {
if (validator == null) {
log.warn("Bean Validation provider could not be found, no validation will be performed");
return;
}
ExecutableValidator methodValidator = validator.forExecutables();
Set<ConstraintViolation<T>> violations = methodValidator.validateParameters(instance,
method, arguments);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
public <T> void validate(final T object) {
if (validator == null) {
log.warn("Bean Validation provider could be found, no validation will be performed");
return;
}
Set<ConstraintViolation<T>> violations = validator.validate(object);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
public void handleFault(org.apache.cxf.message.Message messageParam) {
}
}

@ -73,32 +73,14 @@ import javax.ws.rs.core.Response;
@Scope(
name = "Get Application Details",
description = "Get application details",
key = "perm:application:get",
permissions = {"/device-mgt/application/get"}
),
@Scope(
name = "Create an Application",
description = "Create an application",
key = "perm:application:create",
permissions = {"/device-mgt/application/create"}
key = "perm:app:publisher:view",
permissions = {"/device-mgt/application/view"}
),
@Scope(
name = "Update an Application",
description = "Update an application",
key = "perm:application:update",
key = "perm:app:publisher:update",
permissions = {"/device-mgt/application/update"}
),
@Scope(
name = "Login to Application Management",
description = "Login to Application Management",
key = "perm:application-mgt:login",
permissions = {"/device-mgt/application-mgt/login"}
),
@Scope(
name = "Delete an Application",
description = "Delete an application",
key = "perm:application:delete",
permissions = {"/device-mgt/application/delete"}
)
}
)
@ -122,7 +104,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view")
})
}
)
@ -172,7 +154,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view")
})
}
)
@ -215,7 +197,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:update")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ -254,7 +236,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ -313,7 +295,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:delete")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ -349,7 +331,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ -393,7 +375,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ -436,7 +418,7 @@ public interface ApplicationManagementAPI {
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:update")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ -475,7 +457,7 @@ public interface ApplicationManagementAPI {
tags = "Lifecycle Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:lifecycle:get")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view")
})
}
)
@ -507,7 +489,7 @@ public interface ApplicationManagementAPI {
tags = "Lifecycle Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:lifecycle:add")
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)

@ -448,7 +448,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
LifecycleState state) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
try {
applicationManager.addLifecycleState(applicationId, applicationUuid, state);
applicationManager.changeLifecycleState(applicationId, applicationUuid, state);
} catch (ApplicationManagementException e) {
String msg = "Error occurred while adding lifecycle state.";
log.error(msg, e);

@ -18,29 +18,50 @@
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<jaxrs:server id="applicationMgtService" address="/">
<jaxrs:serviceBeans>
<ref bean="applicationMgtServiceBean"/>
<ref bean="lifecycleMgtServiceBean"/>
<ref bean="subscriptionMgtServiceBean"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="multipartProvider"/>
<ref bean="swaggerWriter"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig">
<property name="resourcePackage" value="org.wso2.carbon.device.application.mgt"/>
<property name="version" value="1.0"/>
<property name="host" value="localhost:9443"/>
<property name="schemes" value="https" />
<property name="basePath" value="/api/application-mgt-publisher/v1.0"/>
<property name="title" value="Application Management Admin Service API Definitions"/>
<property name="contact" value="dev@wso2.org"/>
<property name="license" value="Apache 2.0"/>
<property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<property name="scan" value="true"/>
</bean>
<bean id="ValidationInterceptor" class="org.wso2.carbon.device.application.mgt.publisher.api.ValidationInterceptor"/>
<bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers" />
<bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource" />
<bean id="applicationMgtServiceBean" class="org.wso2.carbon.device.application.mgt.publisher.api.services.impl.ApplicationManagementAPIImpl"/>
<bean id="lifecycleMgtServiceBean" class="org.wso2.carbon.device.application.mgt.publisher.api.services.impl.LifecycleManagementAPIImpl" />
<bean id="subscriptionMgtServiceBean" class="org.wso2.carbon.device.application.mgt.publisher.api.services.impl.SubscriptionManagementAPIImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.publisher.api.JSONMessageHandler"/>
<bean id="multipartProvider" class="org.wso2.carbon.device.application.mgt.publisher.api.MultipartCustomProvider"/>
<cxf:bus>
<cxf:inInterceptors>
<ref bean="ValidationInterceptor"/>
</cxf:inInterceptors>
</cxf:bus>
</beans>

@ -27,6 +27,12 @@
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<!-- configure a security filter -->
<init-param>
<param-name>swagger.security.filter</param-name>
<param-value>ApiAuthorizationFilterImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>

@ -21,7 +21,7 @@ package org.wso2.carbon.device.application.mgt.store.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
@ -87,20 +87,20 @@ public class APIUtil {
}
/**
* To get the Comment Manager from the osgi context.
* To get the Review Manager from the osgi context.
*
* @return CommentsManager instance in the current osgi context.
* @return ReviewManager instance in the current osgi context.
*/
public static CommentsManager getCommentsManager() {
public static ReviewManager getReviewManager() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
CommentsManager commentsManager = (CommentsManager) ctx.getOSGiService(CommentsManager.class, null);
if (commentsManager == null) {
ReviewManager reviewManager = (ReviewManager) ctx.getOSGiService(ReviewManager.class, null);
if (reviewManager == null) {
String msg = "Comments Manager service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return commentsManager;
return reviewManager;
}
public static Response getResponse(Exception ex, Response.Status status) {

@ -31,7 +31,7 @@ import io.swagger.annotations.ApiResponses;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.publisher.api.beans.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.Comment;
import org.wso2.carbon.device.application.mgt.common.Review;
import javax.validation.Valid;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
@ -62,7 +62,7 @@ import java.util.List;
}
),
tags = {
@Tag(name = "store_management", description = "Comment Management related "
@Tag(name = "store_management", description = "Review Management related "
+ "APIs")
}
)
@ -75,20 +75,20 @@ import java.util.List;
permissions = {"/device-mgt/comment/get"}
),
@Scope(
name = "Add a Comment",
name = "Add a Review",
description = "Add a comment",
key = "perm:comment:add",
permissions = {"/device-mgt/comment/add"}
),
@Scope(
name = "Update a Comment",
description = "Update a Comment",
name = "Update a Review",
description = "Update a Review",
key = "perm:comment:update",
permissions = {"/device-mgt/comment/update"}
),
@Scope(
name = "Delete a Comment",
name = "Delete a Review",
description = "Delete a comment",
key = "perm:comment:delete",
permissions = {"/device-mgt/comment/delete"}
@ -96,7 +96,7 @@ import java.util.List;
}
)
@Path("/reviews")
@Path("/review")
@Api(value = "Comments Management", description = "This API carries all comments management related operations " +
"such as get all the comments, add comment, etc.")
@Produces(MediaType.APPLICATION_JSON)
@ -137,7 +137,7 @@ public interface ReviewManagementAPI {
response = ErrorResponse.class)
})
Response getAllComments(
Response getAllReviews(
@ApiParam(
name="uuid",
value="uuid of the released version of application.",
@ -165,8 +165,8 @@ public interface ReviewManagementAPI {
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a comment",
notes = "This will add a new comment",
value = "Add a review",
notes = "This will add a new review",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ -179,41 +179,39 @@ public interface ReviewManagementAPI {
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully add a comment.",
response = Comment.class),
message = "OK. \n Successfully add a review.",
response = Review.class),
@ApiResponse(
code = 400,
message =
"Bad Request. \n"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred adding a comment.",
message = "Internal Server Error. \n Error occurred adding a review.",
response = ErrorResponse.class)
})
Response addComment(
Response addReview(
@ApiParam(
name = "comment",
value = "Comment details",
required = true)
Comment comment,
name = "review",
value = "Review details",
required = true) Review review,
@ApiParam(
name="uuid",
value="uuid of the release version of the application",
required=true)
@PathParam("uuid")
String uuid);
@PathParam("uuid") String uuid);
@PUT
@Path("/{CommentId}")
@Path("/{uuid}/{reviewId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Edit a comment",
notes = "This will edit the comment",
value = "Edit a review",
notes = "This will edit the review",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ -225,8 +223,8 @@ public interface ReviewManagementAPI {
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully updated comment.",
response = Comment.class),
message = "OK. \n Successfully updated review.",
response = Review.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ -236,24 +234,28 @@ public interface ReviewManagementAPI {
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while updating the new comment.",
message = "Internal Server Error. \n Error occurred while updating the new review.",
response = ErrorResponse.class)
})
Response updateComment(
Response updateReview(
@ApiParam(
name = "review",
value = "The review that need to be updated.",
required = true)
@Valid Review review,
@ApiParam(
name = "comment",
value = "The comment that need to be updated.",
name="uuid",
value = "uuid of the application release",
required = true)
@Valid Comment comment,
@PathParam("uuid") String uuid,
@ApiParam(
name="commentId",
value = "comment id of the updating comment.",
name="reviewId",
value = "review id of the updating review.",
required = true)
@QueryParam("commentId")
int commentId);
@PathParam("reviewId") int reviewId);
@DELETE
@Path("/{CommentId}")
@Path("/{commentId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
@ -291,7 +293,12 @@ public interface ReviewManagementAPI {
value="Id of the comment.",
required = true)
@PathParam("commentId")
int commentId);
int commentId,
@ApiParam(
name="username",
value="logged in username",
required = true)
@QueryParam("username") String username);
@GET
@Path("/{uuid}/{stars}")
@ -329,88 +336,4 @@ public interface ReviewManagementAPI {
required = true)
@PathParam("uuid")
String uuid);
@GET
@Path("/{uuid}/{stars}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get rated users",
notes = "Get all users",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:user:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved user.",
response = List.class,
responseContainer = "List"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the comment list.",
response = ErrorResponse.class)
})
Response getNumOfRatedUsers(
@ApiParam(
name = "uuid",
value = "uuid of the application release",
required = true)
@PathParam("uuid")
String uuid);
@POST
@Path("/uuid/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a star value",
notes = "This will add star value",
tags = "Store Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:stars:add")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully rated to the application.",
response = Comment.class),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest rating of the requested resource."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred rating for the application.",
response = ErrorResponse.class)
})
Response updateRatings(
@ApiParam(
name = "stars",
value = "ratings for the application",
required = true)
int stars,
@ApiParam(
name="uuid",
value="uuid of the release version of the application",
required=true)
@PathParam("uuid")
String uuid);
}

@ -21,14 +21,17 @@ package org.wso2.carbon.device.application.mgt.store.api.services.impl;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.Review;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.store.api.APIUtil;
import org.wso2.carbon.device.application.mgt.store.api.services.ReviewManagementAPI;
import org.wso2.carbon.device.application.mgt.common.Comment;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
@ -39,11 +42,9 @@ import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.DELETE;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* Comment Management related jax-rs APIs.
* Review Management related jax-rs APIs.
*/
@Path("/review")
public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@ -52,171 +53,124 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@Override
@GET
@Path("/application/{uuid}/comments")
public Response getAllComments(
@Path("/{uuid}")
public Response getAllReviews(
@PathParam("uuid") String uuid,
@QueryParam("offset") int offSet,
@QueryParam("limit") int limit) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
ReviewManager reviewManager = APIUtil.getReviewManager();
PaginationRequest request = new PaginationRequest(offSet, limit);
try {
PaginationResult paginationResult = commentsManager.getAllComments(request, uuid);
PaginationResult paginationResult = reviewManager.getAllReviews(request, uuid);
return Response.status(Response.Status.OK).entity(paginationResult).build();
} catch (CommentManagementException e) {
String msg = "Error occurred while retrieving comments.";
} catch (ReviewManagementException e) {
String msg = "Error occurred while retrieving reviews for application UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg)
.build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@POST
@Consumes("application/json")
@Path("/application/{uuid}/comment")
public Response addComment(
@ApiParam Comment comment,
@Path("/{uuid}")
public Response addReview(
@ApiParam Review review,
@PathParam("uuid") String uuid) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
ReviewManager reviewManager = APIUtil.getReviewManager();
ApplicationManager applicationManager = APIUtil.getApplicationManager();
Application application;
try {
if (commentsManager.addComment(comment, uuid) != null) {
return Response.status(Response.Status.CREATED).entity(comment).build();
application = applicationManager.getApplicationByRelease(uuid);
if (application.getApplicationReleases().isEmpty()){
String msg = "Couldn't Found an one application release for the UUID: " + uuid;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
if (application.getApplicationReleases().size()>1){
String msg = "Found more than one application release for the UUID: " + uuid;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
boolean isReviewCreated = reviewManager
.addReview(review, application.getId(), application.getApplicationReleases().get(0).getId());
if (isReviewCreated) {
return Response.status(Response.Status.CREATED).entity(review).build();
} else {
String msg = "Given comment is not valid ";
String msg = "Given review is not valid. Please check the review payload.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
} catch (CommentManagementException e) {
String msg = "Error occurred while creating the comment";
} catch (ReviewManagementException e) {
String msg = "Error occurred while creating the review";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
log.error("Error occured while getting the application for application UUID: " + uuid);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(msg).build();
.entity("").build();
}
}
@Override
@PUT
@Consumes("application/json")
@Path("/comment/{commentId}")
public Response updateComment(
@ApiParam Comment comment,
@PathParam("commentId") int commentId) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
@Path("/{uuid}/{reviewId}")
public Response updateReview(
@ApiParam Review review,
@PathParam("uuid") String uuid,
@PathParam("reviewId") int reviewId) {
ReviewManager reviewManager = APIUtil.getReviewManager();
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();
if (reviewManager.updateReview(review, reviewId, true)) {
return Response.status(Response.Status.OK).entity(review).build();
} else {
comment = commentsManager.updateComment(comment, commentId);
return Response.status(Response.Status.OK).entity(comment).build();
String msg = "Review updating failed. Please contact the administrator";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} catch (CommentManagementException e) {
} catch (ReviewManagementException e) {
String msg = "Error occurred while retrieving comments.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(msg).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@DELETE
@Path("/comment/{commentId}")
@Path("/{commentId}")
public Response deleteComment(
@PathParam("commentId") int commentId) {
@PathParam("commentId") int commentId,
@QueryParam("username") String username) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
ReviewManager reviewManager = APIUtil.getReviewManager();
try {
if (commentId == 0) {
return Response.status(Response.Status.NOT_FOUND).entity("Comment not found").build();
return Response.status(Response.Status.NOT_FOUND).entity("Review not found").build();
} else {
commentsManager.deleteComment(commentId);
reviewManager.deleteReview(username, commentId);
}
} catch (CommentManagementException e) {
} catch (ReviewManagementException e) {
String msg = "Error occurred while deleting the comment.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg)
.build();
}
return Response.status(Response.Status.OK).entity("Comment is deleted successfully.").build();
return Response.status(Response.Status.OK).entity("Review is deleted successfully.").build();
}
@Override
@GET
@Path("/application/{uuid}/rating")
@Path("/{uuid}/rating")
public Response getRating(
@PathParam("uuid") String uuid) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
int stars;
ReviewManager reviewManager = APIUtil.getReviewManager();
Rating rating;
try {
stars = commentsManager.getStars(uuid);
} catch (CommentManagementException e) {
log.error("Comment Management Exception occurs", e);
rating = reviewManager.getRating(uuid);
} catch (ReviewManagementException e) {
log.error("Review Management Exception occurs", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (ApplicationManagementException e) {
String msg="Application Management Exception occurs";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(msg).build();
}
return Response.status(Response.Status.OK).entity(stars).build();
return Response.status(Response.Status.OK).entity(rating).build();
}
@Override
@GET
@Path("/application/{uuid}/total-rated-users")
public Response getNumOfRatedUsers(
@PathParam("uuid") String uuid) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
int ratedUsers;
try {
ratedUsers = commentsManager.getRatedUser(uuid);
} catch (CommentManagementException e) {
String msg="Comment Management Exception occurs";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(msg).build();
} catch (ApplicationManagementException e) {
String msg="Application Management Exception occurs";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Application with UUID" + uuid + " Internal server error occurs").build();
}
return Response.status(Response.Status.OK).entity(ratedUsers).build();
}
@Override
@PUT
@Consumes("application/json")
@Path("/application/{uuid}/rating")
public Response updateRatings(
@ApiParam int stars,
@PathParam("uuid") String uuid) {
CommentsManager commentsManager = APIUtil.getCommentsManager();
int newStars;
try {
newStars = commentsManager.updateStars(stars, uuid);
if (stars != 0) {
return Response.status(Response.Status.CREATED).entity(newStars).build();
} else {
String msg = "Given star value is not valid ";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
}
} catch (ApplicationManagementException e) {
String msg="Application Management Exception occurs";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(msg).build();
}
}
}

@ -32,10 +32,10 @@ import org.testng.IObjectFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import org.wso2.carbon.device.application.mgt.common.Comment;
import org.wso2.carbon.device.application.mgt.common.Review;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.store.api.APIUtil;
import org.wso2.carbon.device.application.mgt.store.api.services.impl.ReviewManagementAPIImpl;
import org.wso2.carbon.device.application.mgt.store.api.services.util.CommentMgtTestHelper;
@ -47,14 +47,15 @@ import static org.mockito.MockitoAnnotations.initMocks;
@PowerMockIgnore("javax.ws.rs.*")
@SuppressStaticInitializationFor({
"org.wso2.carbon.device.application.mgt.api.APIUtil" })
@PrepareForTest({ APIUtil.class, CommentsManager.class,
CommentManagementAPITest.class})
@Ignore("Since comment manager logic is invalid temporarily added Ignore annotation to skip running comment management test cases") public class CommentManagementAPITest extends
@PrepareForTest({ APIUtil.class, ReviewManager.class,
ReviewManagementAPITest.class})
@Ignore("Since comment manager logic is invalid temporarily added Ignore annotation to skip running comment management test cases") public class ReviewManagementAPITest
extends
TestCase {
private static final Log log = LogFactory.getLog(ReviewManagementAPI.class);
private ReviewManagementAPI commentManagementAPI;
private CommentsManager commentsManager;
private ReviewManager reviewManager;
@ObjectFactory
public IObjectFactory getObjectFactory() {
@ -62,85 +63,85 @@ import static org.mockito.MockitoAnnotations.initMocks;
}
@BeforeClass
void init() throws CommentManagementException {
void init() throws ReviewManagementException {
log.info("Initializing ReviewManagementAPI tests");
initMocks(this);
this.commentsManager = Mockito.mock(CommentsManager.class, Mockito.RETURNS_DEFAULTS);
this.reviewManager = Mockito.mock(ReviewManager.class, Mockito.RETURNS_DEFAULTS);
this.commentManagementAPI = new ReviewManagementAPIImpl();
}
@Test
public void testGetAllCommentsWithValidDetails() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.getAllComments("a", 1, 2);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.getAllReviews("a", 1, 2);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testGetAllCommentsInternalError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.doThrow(new CommentManagementException()).when(this.commentsManager)
.getAllComments(Mockito.any(), Mockito.anyString());
Response response = this.commentManagementAPI.getAllComments("a", 1, 4);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager)
.getAllReviews(Mockito.any(), Mockito.anyString());
Response response = this.commentManagementAPI.getAllReviews("a", 1, 4);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testGetAllCommentsNotFoundError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.getAllComments(null, 1, 3);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.getAllReviews(null, 1, 3);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
"The response status should be 404.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testAddComments() throws Exception {
Comment comment = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.addComment(comment, "a");
Review review = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.addReview(review, "a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(),
"The response status should be 201.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testAddNullComment() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.addComment(null, "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.addReview(null, "a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testAddCommentsInternalError() throws Exception {
Comment comment = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.when(this.commentManagementAPI.addComment(Mockito.any(), Mockito.anyString()))
.thenThrow(new CommentManagementException());
Response response = this.commentManagementAPI.addComment(comment, null);
Review review = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Mockito.when(this.commentManagementAPI.addReview(Mockito.any(), Mockito.anyString()))
.thenThrow(new ReviewManagementException());
Response response = this.commentManagementAPI.addReview(review, null);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testUpdateComment() throws Exception {
Comment comment = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.updateComment(comment, 1);
Review review = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.updateReview(review, 1);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200.");
@ -148,8 +149,8 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testUpdateNullComment() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.updateComment(null, 1);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.updateReview(null, 1);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400.");
@ -157,9 +158,9 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testUpdateCommentWhenNullCommentId() throws Exception {
Comment comment = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.updateComment(comment, 0);
Review review = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.updateReview(review, 0);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
"The response status should be 404.");
@ -167,10 +168,10 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testUpdateCommentInternalServerError() throws Exception {
Comment comment = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.doThrow(new CommentManagementException()).when(this.commentsManager).updateComment(comment, 9);
Response response = this.commentManagementAPI.updateComment(comment, 9);
Review review = CommentMgtTestHelper.getDummyComment("a", "a");
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Mockito.doThrow(new ReviewManagementException()).when(this.reviewManager).updateReview(review, 9, true);
Response response = this.commentManagementAPI.updateReview(review, 9);
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
@ -178,8 +179,8 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testDeleteComment() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.deleteComment(1);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.deleteComment(1,"");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200.");
@ -187,9 +188,9 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testDeleteCommentInternalError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.when(this.commentManagementAPI.deleteComment(1)).thenThrow(new CommentManagementException());
Response response = this.commentManagementAPI.deleteComment(1);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Mockito.when(this.commentManagementAPI.deleteComment(1,"")).thenThrow(new ReviewManagementException());
Response response = this.commentManagementAPI.deleteComment(1,"");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
@ -197,8 +198,8 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testDeleteCommentNotFoundError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.deleteComment(0);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.deleteComment(0,"");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
"The response status should be 404.");
@ -206,101 +207,35 @@ import static org.mockito.MockitoAnnotations.initMocks;
@Test
public void testGetStars() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Response response = this.commentManagementAPI.getRating("a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testGetStarsCommentError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString()))
.thenThrow(new CommentManagementException());
.thenThrow(new ReviewManagementException());
Response response = this.commentManagementAPI.getRating("a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
@Test
public void testGetStarsApplicationError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getReviewManager")).toReturn(this.reviewManager);
Mockito.when(this.commentManagementAPI.getRating(Mockito.anyString()))
.thenThrow(new ApplicationManagementException());
Response response = this.commentManagementAPI.getRating("a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
}
@Test
public void testGetRatedUser() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.getNumOfRatedUsers("a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200.");
Mockito.reset(commentsManager);
}
@Test
public void testGetRatedUserCommentError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.when(this.commentManagementAPI.getNumOfRatedUsers(Mockito.anyString()))
.thenThrow(new CommentManagementException());
Response response = this.commentManagementAPI.getNumOfRatedUsers("a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
}
@Test
public void testGetRatedUserApplicationError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.when(this.commentManagementAPI.getNumOfRatedUsers(Mockito.anyString()))
.thenThrow(new ApplicationManagementException());
Response response = this.commentManagementAPI.getNumOfRatedUsers("a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
}
@Test
public void testUpdateStars() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.updateRatings(3, "a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(),
"The response status should be 201.");
Mockito.reset(commentsManager);
}
@Test
public void testUpdateInvalidStars() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Response response = this.commentManagementAPI.updateRatings(0, "a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400.");
Mockito.reset(commentsManager);
}
@Test
public void testUpdateStarsApplicationError() throws Exception {
PowerMockito.stub(PowerMockito.method(APIUtil.class, "getCommentsManager")).toReturn(this.commentsManager);
Mockito.doThrow(new ApplicationManagementException()).when(this.commentsManager)
.updateStars(Mockito.anyInt(), Mockito.anyString());
Response response = this.commentManagementAPI.updateRatings(3, "a");
Assert.assertNotNull(response, "The response object is null.");
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"The response status should be 500.");
Mockito.reset(commentsManager);
Mockito.reset(reviewManager);
}
}

@ -17,36 +17,34 @@
*/
package org.wso2.carbon.device.application.mgt.store.api.services.util;
import org.wso2.carbon.device.application.mgt.common.Comment;
import org.wso2.carbon.device.application.mgt.common.Review;
/**
* Helper class for Comment Management API test cases.
* Helper class for Review Management API test cases.
*/
public class CommentMgtTestHelper {
private static final String COMMENT_TEXT = "Dummy Comment";
private static final String COMMENT_TEXT = "Dummy Review";
private static final String CREATED_BY = "TEST_CREATED_BY";
private static final String MODIFIED_BY = "TEST_MODIFIED_BY";
private static final int PARENT_ID = 123;
private static final int COMMENT_ID = 1;
/**
* Creates a Comment with given text and given uuid.
* If the text is null, the COMMENT_TEXT will be used as the Dummy Comment.
* Creates a Review with given text and given uuid.
* If the text is null, the COMMENT_TEXT will be used as the Dummy Review.
*
* @param commentText : Text of the Comment
* @return Comment
* @param commentText : Text of the Review
* @return Review
*/
public static Comment getDummyComment(String commentText, String uuid) {
Comment comment = new Comment();
comment.setId(COMMENT_ID);
comment.setCreatedBy(CREATED_BY);
comment.setModifiedBy(MODIFIED_BY);
comment.setParent(PARENT_ID);
comment.setCommentText(commentText != null ? commentText : COMMENT_TEXT);
return comment;
public static Review getDummyComment(String commentText, String uuid) {
Review review = new Review();
review.setId(COMMENT_ID);
review.setUsername(CREATED_BY);
review.setComment(commentText != null ? commentText : COMMENT_TEXT);
return review;
}
}

@ -23,7 +23,7 @@
<test name="API Unit Tests" preserve-order="true">
<classes>
<class name="org.wso2.carbon.device.application.mgt.store.api.services.CommentManagementAPITest"/>
<class name="org.wso2.carbon.device.application.mgt.store.api.services.ReviewManagementAPITest"/>
</classes>
</test>
</suite>

@ -78,12 +78,10 @@
<Private-Package>org.wso2.carbon.device.mgt.core.internal</Private-Package>
<Import-Package>
org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.apache.axiom.*; version="${axiom.osgi.version.range}",
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming,
javax.xml.*,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
javax.servlet.*,
org.xml.sax,

@ -149,6 +149,9 @@ public class DeviceManagementServiceComponent {
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
log.info("CALLING Crazy .............");
try {
if (log.isDebugEnabled()) {
log.debug("Initializing device management core bundle");

@ -154,7 +154,6 @@
javax.xml.namespace;resolution:=optional,
org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common.license.mgt,
org.wso2.carbon.registry.api,
org.wso2.carbon.registry.core,
org.wso2.carbon.registry.core.exceptions,

@ -56,7 +56,6 @@
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.xml.*,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
org.wso2.carbon.context,
org.wso2.carbon.utils.*,

@ -30,6 +30,7 @@
<artifactId>org.wso2.carbon.device.application.mgt.server.feature</artifactId>
<packaging>pom</packaging>
<version>3.1.40-SNAPSHOT</version>
<name>WSO2 Carbon - Application Management Server Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the core bundles required for Back-end Application Management functionality
@ -44,6 +45,18 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.application.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.plist</groupId>
<artifactId>dd-plist</artifactId>
<version>${googlecode.plist.version}</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>${commons-validator.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>javax.servlet.jsp</groupId>-->
<!--<artifactId>javax.servlet.jsp-api</artifactId>-->
@ -122,6 +135,12 @@
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.device.application.mgt.core:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
com.googlecode.plist:dd-plist:${googlecode.plist.version}
</bundleDef>
<bundleDef>
commons-validator:commons-validator:${commons-validator.version}
</bundleDef>
<!--<bundleDef>javax.servlet.jsp:javax.servlet.jsp-api</bundleDef>-->
<!--<bundleDef>org.wso2.orbit.org.scannotation:scannotation:${scannotation.version}</bundleDef>-->
</bundles>
@ -136,4 +155,7 @@
</plugin>
</plugins>
</build>
<properties>
<commons-validator.version>1.6</commons-validator.version>
</properties>
</project>

@ -31,8 +31,8 @@
<Extension name="CategoryManager">
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.CategoryManagerImpl</ClassName>
</Extension>
<Extension name="CommentsManager">
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.CommentsManagerImpl</ClassName>
<Extension name="ReviewManager">
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.ReviewManagerImpl</ClassName>
</Extension>
<Extension name="LifecycleStateManager">
<ClassName>org.wso2.carbon.device.application.mgt.core.impl.LifecycleStateManagerImpl</ClassName>
@ -60,4 +60,61 @@
</Parameters>
</Extension>
</Extensions>
<!-- This is for publisher lifecycle -->
<!-- The current lifecycle as follows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Created] -> [In-Review] -> [Approved] -> [Published] -> [Unpublished] -> [Removed]
^ | ^
| | |
| |-> [Deprecated] - - - - - - - -|
| |
|-> [Rejected] - - - - - - - - - - - - - - - - - - - - - - - - |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If there is a requirement to introduce a new state to the lifecycle, please refer above
diagram and add relevant state to the below configuration appropriately.
-->
<LifecycleStates>
<LifecycleState name="Created">
<ProceedingStates>
<State>In-Review</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="In-Review">
<ProceedingStates>
<State>Rejected</State>
<State>Approved</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Approved">
<ProceedingStates>
<State>Published</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Rejected">
<ProceedingStates>
<State>In-Review</State>
<State>Removed</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Published">
<ProceedingStates>
<State>Unpublished</State>
<State>Deprecated</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Unpublished">
<ProceedingStates>
<State>Removed</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Deprecated">
<ProceedingStates>
<State>Removed</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Removed">
</LifecycleState>
</LifecycleStates>
</ApplicationManagementConfiguration>

@ -1,350 +1,206 @@
-- -----------------------------------------------------
-- Schema WSO2DM_APPM_DB
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Table APPM_PLATFORM
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_PLATFORM (
ID INT NOT NULL AUTO_INCREMENT UNIQUE,
IDENTIFIER VARCHAR (100) NOT NULL,
TENANT_ID INT NOT NULL ,
NAME VARCHAR (255),
FILE_BASED BOOLEAN,
DESCRIPTION LONGVARCHAR,
IS_SHARED BOOLEAN,
IS_DEFAULT_TENANT_MAPPING BOOLEAN,
ICON_NAME VARCHAR (100),
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_PROPERTIES (
ID INT NOT NULL AUTO_INCREMENT,
PLATFORM_ID INT NOT NULL,
PROP_NAME VARCHAR (100) NOT NULL,
OPTIONAL BOOLEAN,
DEFAUL_VALUE VARCHAR (255),
FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE,
PRIMARY KEY (ID, PLATFORM_ID, PROP_NAME)
);
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_TENANT_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TENANT_ID INT NOT NULL ,
PLATFORM_ID INT NOT NULL,
FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE,
PRIMARY KEY (ID, TENANT_ID, PLATFORM_ID)
);
CREATE INDEX IF NOT EXISTS FK_PLATFROM_TENANT_MAPPING_PLATFORM ON APPM_PLATFORM_TENANT_MAPPING(PLATFORM_ID ASC);
-- -----------------------------------------------------
-- Table APPM_APPLICATION_CATEGORY
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_APPLICATION_CATEGORY (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL UNIQUE,
DESCRIPTION TEXT NULL,
-- Table AP_APP
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS AP_APP (
ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(45) NOT NULL,
TYPE VARCHAR(200) NOT NULL,
TENANT_ID VARCHAR(45) NOT NULL,
APP_CATEGORY VARCHAR(45) NULL DEFAULT NULL,
RESTRICTED INT(11) NOT NULL,
STATUS VARCHAR(45) NOT NULL DEFAULT 'ACTIVE',
SUB_TYPE VARCHAR(45) NOT NULL,
CURRENCY VARCHAR(45) NULL DEFAULT '$',
DM_DEVICE_TYPE_ID INT(11) NOT NULL,
PRIMARY KEY (ID));
INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Sports', 'Applications that involve sports.');
INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Education', 'Application related with education');
INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('News', 'Applications involving news');
-- -----------------------------------------------------
-- Table `APPM_LIFECYCLE_STATE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE (
ID INT NOT NULL AUTO_INCREMENT UNIQUE,
NAME VARCHAR(100) NOT NULL,
IDENTIFIER VARCHAR(100) NOT NULL,
DESCRIPTION TEXT NULL,
-- Table AP_APP_RELEASE
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS AP_APP_RELEASE (
ID INT(11) NOT NULL AUTO_INCREMENT,
VERSION VARCHAR(10) NOT NULL,
TENANT_ID VARCHAR(45) NOT NULL,
UUID VARCHAR(200) NOT NULL,
RELEASE_TYPE VARCHAR(45) NOT NULL,
APP_PRICE DECIMAL(6,2) NULL DEFAULT NULL,
STORED_LOCATION VARCHAR(45) NOT NULL,
BANNER_LOCATION VARCHAR(45) NOT NULL,
SC_1_LOCATION VARCHAR(45) NOT NULL,
SC_2_LOCATION VARCHAR(45) NULL DEFAULT NULL,
SC_3_LOCATION VARCHAR(45) NULL DEFAULT NULL,
APP_HASH_VALUE VARCHAR(1000) NOT NULL,
SHARED_WITH_ALL_TENANTS INT(11) NULL DEFAULT NULL,
APP_META_INFO VARCHAR(20000) NULL DEFAULT NULL,
RATING DOUBLE NULL DEFAULT NULL,
RATED_USERS INT(11) NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID, AP_APP_ID),
CONSTRAINT fk_AP_APP_RELEASE_AP_APP1
FOREIGN KEY (AP_APP_ID)
REFERENCES AP_APP (ID));
CREATE INDEX fk_AP_APP_RELEASE_AP_APP1_idx ON AP_APP_RELEASE (AP_APP_ID ASC);
-- -----------------------------------------------------
-- Table AP_APP_REVIEW
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS AP_APP_REVIEW (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
COMMENT VARCHAR(250) NOT NULL,
REPLY_COMMENT VARCHAR(250) NULL,
CREATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
MODEFIED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
RATING INT(11) NULL,
USERNAME VARCHAR(45) NOT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
UNIQUE INDEX APPM_LIFECYCLE_STATE_IDENTIFIER_UNIQUE (IDENTIFIER ASC));
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('CREATED', 'CREATED', 'Application creation
initial state');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('IN REVIEW', 'IN REVIEW', 'Application is in in-review state');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('APPROVED', 'APPROVED', 'State in which Application is approved after reviewing.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('REJECTED', 'REJECTED', 'State in which Application is rejected after reviewing.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,');
CONSTRAINT fk_AP_APP_COMMENT_AP_APP_RELEASE1
FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID)
REFERENCES AP_APP_RELEASE (ID , AP_APP_ID));
CREATE INDEX fk_AP_APP_COMMENT_AP_APP_RELEASE1_idx ON AP_APP_REVIEW (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC);
CREATE TABLE IF NOT EXISTS APPM_LC_STATE_TRANSITION
(
ID INT NOT NULL AUTO_INCREMENT UNIQUE,
INITIAL_STATE INT,
NEXT_STATE INT,
PERMISSION VARCHAR(1024),
DESCRIPTION VARCHAR(2048),
PRIMARY KEY (INITIAL_STATE, NEXT_STATE),
FOREIGN KEY (INITIAL_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE,
FOREIGN KEY (NEXT_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE
);
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(1, 2, null, 'Submit for review');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(2, 1, null, 'Revoke from review');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(2, 3, '/permission/admin/manage/device-mgt/application/review', 'APPROVE');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(2, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(3, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(3, 5, null, 'PUBLISH');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(5, 6, null, 'UN PUBLISH');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(6, 5, null, 'PUBLISH');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(4, 1, null, 'Return to CREATE STATE');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(6, 1, null, 'Return to CREATE STATE');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(6, 7, null, 'Retire');
-- -----------------------------------------------------
-- Table APPM_APPLICATION
-- Table AP_APP_LIFECYCLE_STATE
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_APPLICATION` (
`ID` INT NOT NULL AUTO_INCREMENT,
`UUID` VARCHAR(100) NOT NULL,
`NAME` VARCHAR(100) NOT NULL,
`SHORT_DESCRIPTION` VARCHAR(255) NULL,
`DESCRIPTION` TEXT NULL,
`SCREEN_SHOT_COUNT` INT DEFAULT 0,
`VIDEO_NAME` VARCHAR(100) NULL,
`CREATED_BY` VARCHAR(255) NULL,
`CREATED_AT` DATETIME NOT NULL,
`MODIFIED_AT` DATETIME NULL,
`IS_FREE` TINYINT(1) NULL,
`PAYMENT_CURRENCY` VARCHAR(45) NULL,
`PAYMENT_PRICE` DECIMAL(10,2) NULL,
`APPLICATION_CATEGORY_ID` INT NOT NULL,
`LIFECYCLE_STATE_ID` INT NOT NULL,
`LIFECYCLE_STATE_MODIFIED_BY` VARCHAR(255) NULL,
`LIFECYCLE_STATE_MODIFIED_AT` DATETIME NULL,
`TENANT_ID` INT NOT NULL,
`PLATFORM_ID` INT NOT NULL,
PRIMARY KEY (`ID`, `APPLICATION_CATEGORY_ID`, `LIFECYCLE_STATE_ID`, `PLATFORM_ID`),
UNIQUE INDEX `UUID_UNIQUE` (`UUID` ASC),
FOREIGN KEY (`APPLICATION_CATEGORY_ID`)
REFERENCES `APPM_APPLICATION_CATEGORY` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_APPLICATION_APPM_LIFECYCLE_STATE1`
FOREIGN KEY (`LIFECYCLE_STATE_ID`)
REFERENCES `APPM_LIFECYCLE_STATE` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_APPLICATION_APPM_PLATFORM1`
FOREIGN KEY (`PLATFORM_ID`)
REFERENCES `APPM_PLATFORM` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX IF NOT EXISTS FK_APPLICATION_APPLICATION_CATEGORY ON APPM_APPLICATION(APPLICATION_CATEGORY_ID ASC);
CREATE TABLE IF NOT EXISTS AP_APP_LIFECYCLE_STATE (
ID INT(11) NOT NULL AUTO_INCREMENT,
CURRENT_STATE VARCHAR(45) NOT NULL,
PREVIOUSE_STATE VARCHAR(45) NOT NULL,
TENANT_ID VARCHAR(45) NOT NULL,
UPDATED_BY VARCHAR(100) NOT NULL,
UPDATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID, AP_APP_RELEASE_ID, AP_APP_ID),
CONSTRAINT fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1
FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID)
REFERENCES AP_APP_RELEASE (ID , AP_APP_ID));
-- -----------------------------------------------------
-- Table APPM_APPLICATION_PROPERTY
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_APPLICATION_PROPERTY (
PROP_KEY VARCHAR(255) NOT NULL,
PROP_VAL TEXT NULL,
APPLICATION_ID INT NOT NULL,
PRIMARY KEY (PROP_KEY, APPLICATION_ID),
CONSTRAINT FK_APPLICATION_PROPERTY_APPLICATION
FOREIGN KEY (APPLICATION_ID)
REFERENCES APPM_APPLICATION (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1_idx ON AP_APP_LIFECYCLE_STATE (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC);
CREATE INDEX FK_APPLICATION_PROPERTY_APPLICATION ON APPM_APPLICATION_PROPERTY(APPLICATION_ID ASC);
-- -----------------------------------------------------
-- Table APPM_APPLICATION_RELEASE
-- Table AP_APP_TAG
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_APPLICATION_RELEASE (
ID INT NOT NULL AUTO_INCREMENT,
VERSION_NAME VARCHAR(100) NOT NULL,
RELEASE_RESOURCE TEXT NULL,
RELEASE_CHANNEL VARCHAR(50) DEFAULT 'ALPHA',
RELEASE_DETAILS TEXT NULL,
CREATED_AT DATETIME NOT NULL,
APPM_APPLICATION_ID INT NOT NULL,
IS_DEFAULT TINYINT NULL,
PRIMARY KEY (APPM_APPLICATION_ID, VERSION_NAME),
CONSTRAINT FK_APPLICATION_VERSION_APPLICATION
FOREIGN KEY (APPM_APPLICATION_ID)
REFERENCES APPM_APPLICATION (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX FK_APPLICATION_VERSION_APPLICATION ON APPM_APPLICATION_RELEASE(APPM_APPLICATION_ID ASC);
CREATE TABLE IF NOT EXISTS AP_APP_TAG (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
TAG VARCHAR(45) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_AP_APP_TAGS_AP_APP1
FOREIGN KEY (AP_APP_ID)
REFERENCES AP_APP (ID));
-- -----------------------------------------------------
-- Table APPM_RELEASE_PROPERTY
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_RELEASE_PROPERTY (
PROP_KEY VARCHAR(255) NOT NULL,
PROP_VALUE TEXT NULL,
APPLICATION_RELEASE_ID INT NOT NULL,
PRIMARY KEY (PROP_KEY, APPLICATION_RELEASE_ID),
CONSTRAINT FK_RELEASE_PROPERTY_APPLICATION_RELEASE
FOREIGN KEY (APPLICATION_RELEASE_ID)
REFERENCES APPM_APPLICATION_RELEASE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX fk_AP_APP_TAGS_AP_APP1_idx ON AP_APP_TAG (AP_APP_ID ASC);
CREATE INDEX FK_RELEASE_PROPERTY_APPLICATION_RELEASE ON APPM_RELEASE_PROPERTY(APPLICATION_RELEASE_ID ASC);
-- -----------------------------------------------------
-- Table APPM_RESOURCE_TYPE
-- Table AP_DEVICE_SUBSCRIPTION
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_RESOURCE_TYPE (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(45) NULL,
DESCRIPTION TEXT NULL,
PRIMARY KEY (ID));
CREATE TABLE IF NOT EXISTS AP_DEVICE_SUBSCRIPTION (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,
DM_ENROLMENT_ID INT(11) NOT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1
FOREIGN KEY (AP_APP_ID , AP_APP_RELEASE_ID)
REFERENCES AP_APP_RELEASE (AP_APP_ID , ID));
INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('PUBLIC', 'OPEN VISIBILITY, CAN BE VIEWED BY ALL LOGGED IN USERS');
INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('ROLES', 'ROLE BASED RESTRICTION, CAN BE VIEWED BY ONLY GIVEN
SET OF USER WHO HAVE THE SPECIFIED ROLE');
INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('DEVICE_GROUPS', 'DEVICE GROUP LEVEL RESTRICTION,
CAN BE VIEWED BY THE DEVICES/ROLES BELONG TO THE GROUP');
CREATE INDEX fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_DEVICE_SUBSCRIPTION (AP_APP_ID ASC, AP_APP_RELEASE_ID ASC);
-- -----------------------------------------------------
-- Table APPM_SUBSCRIPTION
-- Table AP_GROUP_SUBSCRIPTION
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_SUBSCRIPTION (
ID INT NOT NULL AUTO_INCREMENT,
VALUE VARCHAR(255) NOT NULL,
CREATED_AT DATETIME NOT NULL,
RESOURCE_TYPE_ID INT NOT NULL,
APPLICATION_ID INT NOT NULL,
APPLICATION_RELEASE_ID INT NULL,
PRIMARY KEY (ID, APPLICATION_ID, RESOURCE_TYPE_ID),
CONSTRAINT fk_APPM_APPLICATION_SUBSCRIPTION_APPM_RESOURCE_TYPE1
FOREIGN KEY (RESOURCE_TYPE_ID)
REFERENCES APPM_RESOURCE_TYPE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION1
FOREIGN KEY (APPLICATION_ID)
REFERENCES APPM_APPLICATION (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION_RELEASE1
FOREIGN KEY (APPLICATION_RELEASE_ID)
REFERENCES APPM_APPLICATION_RELEASE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX FK_APPLICATION_SUBSCRIPTION_RESOURCE_TYPE ON APPM_SUBSCRIPTION(RESOURCE_TYPE_ID ASC);
CREATE INDEX FK_APPLICATION_SUBSCRIPTION_APPLICATION ON APPM_SUBSCRIPTION(APPLICATION_ID ASC);
CREATE INDEX FK_APPLICATION_SUBSCRIPTION_APPLICATION_RELEASE ON APPM_SUBSCRIPTION(APPLICATION_RELEASE_ID ASC);
CREATE TABLE IF NOT EXISTS AP_GROUP_SUBSCRIPTION (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,
DM_GROUP_ID INT(11) NOT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1
FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID)
REFERENCES AP_APP_RELEASE (ID , AP_APP_ID));
-- -----------------------------------------------------
-- Table APPM_COMMENT
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_COMMENT (
ID INT NOT NULL AUTO_INCREMENT,
APPLICATION_RELEASE_ID INT NOT NULL,
COMMENT_SUBJECT VARCHAR(255) NULL,
COMMENT_BODY TEXT NULL,
RATING INT NULL,
PARENT_ID INT NULL,
CREATED_AT DATETIME NOT NULL,
CREATED_BY VARCHAR(45) NULL,
MODIFIED_AT DATETIME NULL,
PUBLISHED TINYINT NULL,
APPROVED TINYINT NULL,
PRIMARY KEY (ID, APPLICATION_RELEASE_ID),
CONSTRAINT FK_APPLICATION_COMMENTS_APPLICATION_RELEASE
FOREIGN KEY (APPLICATION_RELEASE_ID)
REFERENCES APPM_APPLICATION_RELEASE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_GROUP_SUBSCRIPTION (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC);
CREATE INDEX FK_APPLICATION_COMMENTS_APPLICATION_RELEASE ON APPM_COMMENT(APPLICATION_RELEASE_ID ASC);
-- -----------------------------------------------------
-- Table APPM_PLATFORM_TAG
-- Table AP_ROLE_SUBSCRIPTION
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_TAG (
NAME VARCHAR(100) NOT NULL,
PLATFORM_ID INT NOT NULL,
PRIMARY KEY (PLATFORM_ID, name),
CONSTRAINT fk_APPM_SUPPORTED_PLATFORM_TAGS_APPM_SUPPORTED_PLATFORM1
FOREIGN KEY (PLATFORM_ID)
REFERENCES APPM_PLATFORM (ID)
ON DELETE CASCADE
ON UPDATE CASCADE);
CREATE INDEX FK_PLATFORM_TAGS_PLATFORM ON APPM_PLATFORM_TAG(PLATFORM_ID ASC);
CREATE TABLE IF NOT EXISTS AP_ROLE_SUBSCRIPTION (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
ROLE_NAME VARCHAR(100) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1
FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID)
REFERENCES AP_APP_RELEASE (ID , AP_APP_ID));
-- -----------------------------------------------------
-- Table APPM_APPLICATION_TAG
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_APPLICATION_TAG (
name VARCHAR(45) NOT NULL,
APPLICATION_ID INT NOT NULL,
PRIMARY KEY (APPLICATION_ID, name),
CONSTRAINT fk_APPM_APPLICATION_TAG_APPM_APPLICATION1
FOREIGN KEY (APPLICATION_ID)
REFERENCES APPM_APPLICATION (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_ROLE_SUBSCRIPTION (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC);
CREATE INDEX FK_APPLICATION_TAG_APPLICATION ON APPM_APPLICATION_TAG(APPLICATION_ID ASC);
-- -----------------------------------------------------
-- Table APPM_VISIBILITY
-- Table AP_UNRESTRICTED_ROLE
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_VISIBILITY (
ID INT NOT NULL AUTO_INCREMENT,
VALUE VARCHAR(255),
RESOURCE_TYPE_ID INT NOT NULL,
APPLICATION_ID INT NULL,
CREATE TABLE IF NOT EXISTS AP_UNRESTRICTED_ROLE (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
ROLE VARCHAR(45) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_APPM_VISIBILITY_APPM_RESOURCE_TYPE1
FOREIGN KEY (RESOURCE_TYPE_ID)
REFERENCES APPM_RESOURCE_TYPE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_APPM_VISIBILITY_APPM_APPLICATION1
FOREIGN KEY (APPLICATION_ID)
REFERENCES APPM_APPLICATION (ID)
ON DELETE CASCADE
ON UPDATE CASCADE);
CONSTRAINT fk_AP_APP_VISIBILITY_AP_APP1
FOREIGN KEY (AP_APP_ID)
REFERENCES AP_APP (ID));
CREATE INDEX fk_AP_APP_VISIBILITY_AP_APP1_idx ON AP_UNRESTRICTED_ROLE (AP_APP_ID ASC);
CREATE INDEX FK_APPM_VISIBILITY_RESOURCE_TYPE ON APPM_VISIBILITY(RESOURCE_TYPE_ID ASC);
CREATE INDEX FK_VISIBILITY_APPLICATION ON APPM_VISIBILITY(APPLICATION_ID ASC);
-- -----------------------------------------------------
-- Table APPM_SUBSCRIPTION_PROPERTIES
-- Table AP_USER_SUBSCRIPTION
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_SUBSCRIPTION_PROPERTIES (
PROP_KEY VARCHAR(500) NOT NULL,
PROP_VALUE VARCHAR(500) NULL,
APPM_SUBSCRIPTION_ID INT NOT NULL,
PRIMARY KEY (PROP_KEY, APPM_SUBSCRIPTION_ID),
CONSTRAINT fk_APPM_SUBSCRIPTION_PROPERTIES_APPM_SUBSCRIPTION1
FOREIGN KEY (APPM_SUBSCRIPTION_ID)
REFERENCES APPM_SUBSCRIPTION (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE TABLE IF NOT EXISTS AP_USER_SUBSCRIPTION (
ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL,
USER_NAME VARCHAR(100) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1
FOREIGN KEY (AP_APP_RELEASE_ID , AP_APP_ID)
REFERENCES AP_APP_RELEASE (ID , AP_APP_ID));
CREATE INDEX FK_SUBSCRIPTION_PROPERTIES_SUBSCRIPTION ON APPM_SUBSCRIPTION_PROPERTIES(APPM_SUBSCRIPTION_ID ASC);
CREATE INDEX fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1_idx ON AP_USER_SUBSCRIPTION (AP_APP_RELEASE_ID ASC, AP_APP_ID ASC);

@ -1,5 +1,5 @@
-- MySQL Script generated by MySQL Workbench
-- 2017-06-14 12:46:43 +0530
-- Tue 18 Sep 2018 17:40:45 +0530
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
@ -7,401 +7,252 @@ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema WSO2DM_APPM_DB
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Table `APPM_PLATFORM`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_PLATFORM (
ID INT NOT NULL AUTO_INCREMENT UNIQUE,
IDENTIFIER VARCHAR (100) NOT NULL,
TENANT_ID INT NOT NULL ,
NAME VARCHAR (255),
FILE_BASED BOOLEAN,
DESCRIPTION VARCHAR (2048),
IS_SHARED BOOLEAN,
IS_DEFAULT_TENANT_MAPPING BOOLEAN,
ICON_NAME VARCHAR (100),
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_PROPERTIES (
ID INT NOT NULL AUTO_INCREMENT,
PLATFORM_ID INT NOT NULL,
PROP_NAME VARCHAR (100) NOT NULL,
OPTIONAL BOOLEAN,
DEFAUL_VALUE VARCHAR (255),
FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE,
PRIMARY KEY (ID, PLATFORM_ID, PROP_NAME)
);
-- -----------------------------------------------------
-- Table `APPM_PLATFORM_TENENT_MAPPING`
-- Table `AP_APP`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_PLATFORM_TENANT_MAPPING` (
`ID` INT NOT NULL AUTO_INCREMENT,
`PLATFORM_ID` INT NOT NULL,
`TENANT_ID` INT NOT NULL,
PRIMARY KEY (`ID`, `PLATFORM_ID`),
INDEX `FK_PLATFROM_TENANT_MAPPING_PLATFORM` (`PLATFORM_ID` ASC),
CONSTRAINT `fk_APPM_PLATFORM_TENANT_MAPPING_APPM_SUPPORTED_PLATFORM1`
FOREIGN KEY (`PLATFORM_ID`)
REFERENCES `APPM_PLATFORM` (`ID`)
ON DELETE CASCADE
ON UPDATE CASCADE )
ENGINE = InnoDB
COMMENT = 'This table contains the data related relationship between application platofrm and appication mappings';
-- -----------------------------------------------------
-- Table `APPM_APPLICATION_CATEGORY`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_CATEGORY` (
`ID` INT NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(100) NOT NULL UNIQUE,
`DESCRIPTION` TEXT NULL,
CREATE TABLE IF NOT EXISTS `AP_APP` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(45) NOT NULL,
`TYPE` VARCHAR(200) NOT NULL,
`TENANT_ID` VARCHAR(45) NOT NULL,
`APP_CATEGORY` VARCHAR(45) NULL DEFAULT NULL,
`RESTRICTED` INT(11) NOT NULL,
`STATUS` VARCHAR(45) NOT NULL DEFAULT 'ACTIVE',
`SUB_TYPE` VARCHAR(45) NOT NULL,
`CURRENCY` VARCHAR(45) NULL DEFAULT '$',
`DM_DEVICE_TYPE_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`))
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the application category';
INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Sports', 'Applications that involve sports.');
INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('Education', 'Application related with education');
INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES ('News', 'Applications involving news');
-- -----------------------------------------------------
-- Table `APPM_LIFECYCLE_STATE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE (
ID INT NOT NULL AUTO_INCREMENT UNIQUE,
NAME VARCHAR(100) NOT NULL,
IDENTIFIER VARCHAR(100) NOT NULL,
DESCRIPTION TEXT NULL,
PRIMARY KEY (ID),
UNIQUE INDEX APPM_LIFECYCLE_STATE_IDENTIFIER_UNIQUE (IDENTIFIER ASC));
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('CREATED', 'CREATED',
'Application creation initial state');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('IN REVIEW', 'IN REVIEW', 'Application is in in-review state');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('APPROVED', 'APPROVED', 'State in which Application is approved after reviewing.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('REJECTED', 'REJECTED', 'State in which Application is rejected after reviewing.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,');
CREATE TABLE IF NOT EXISTS APPM_LC_STATE_TRANSITION
(
ID INT NOT NULL AUTO_INCREMENT UNIQUE,
INITIAL_STATE INT,
NEXT_STATE INT,
PERMISSION VARCHAR(1024),
DESCRIPTION VARCHAR(2048),
PRIMARY KEY (INITIAL_STATE, NEXT_STATE),
FOREIGN KEY (INITIAL_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE,
FOREIGN KEY (NEXT_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE
);
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(1, 2, null, 'Submit for review');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(2, 1, null, 'Revoke from review');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(2, 3, '/permission/admin/manage/device-mgt/application/review', 'APPROVE');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(2, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(3, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(3, 5, null, 'PUBLISH');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(5, 6, null, 'UN PUBLISH');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(6, 5, null, 'PUBLISH');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(4, 1, null, 'Return to CREATE STATE');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(6, 1, null, 'Return to CREATE STATE');
INSERT INTO APPM_LC_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES
(6, 7, null, 'Retire');
-- -----------------------------------------------------
-- Table `APPM_APPLICATION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_APPLICATION` (
`ID` INT NOT NULL AUTO_INCREMENT,
`UUID` VARCHAR(100) NOT NULL,
`NAME` VARCHAR(100) NOT NULL,
`SHORT_DESCRIPTION` VARCHAR(255) NULL,
`DESCRIPTION` TEXT NULL,
`VIDEO_NAME` VARCHAR(100) NULL,
`SCREEN_SHOT_COUNT` INT DEFAULT 0,
`CREATED_BY` VARCHAR(255) NULL,
`CREATED_AT` DATETIME NOT NULL,
`MODIFIED_AT` DATETIME NULL,
`IS_FREE` TINYINT(1) NULL,
`PAYMENT_CURRENCY` VARCHAR(45) NULL,
`PAYMENT_PRICE` DECIMAL(10,2) NULL,
`APPLICATION_CATEGORY_ID` INT NOT NULL,
`LIFECYCLE_STATE_ID` INT NOT NULL,
`LIFECYCLE_STATE_MODIFIED_BY` VARCHAR(255) NULL,
`LIFECYCLE_STATE_MODIFIED_AT` DATETIME NULL,
`TENANT_ID` INT NULL,
`PLATFORM_ID` INT NOT NULL,
PRIMARY KEY (`ID`, `APPLICATION_CATEGORY_ID`, `LIFECYCLE_STATE_ID`, `PLATFORM_ID`),
UNIQUE INDEX `UUID_UNIQUE` (`UUID` ASC),
INDEX `FK_APPLICATION_APPLICATION_CATEGORY` (`APPLICATION_CATEGORY_ID` ASC),
INDEX `FK_APPLICATION_LIFECYCLE_STATE` (`LIFECYCLE_STATE_ID` ASC),
INDEX `FK_APPM_APPLICATION_APPM_PLATFORM` (`PLATFORM_ID` ASC),
CONSTRAINT `FK_APPLICATION_APPLICATION_CATEGORY`
FOREIGN KEY (`APPLICATION_CATEGORY_ID`)
REFERENCES `APPM_APPLICATION_CATEGORY` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_APPLICATION_APPM_LIFECYCLE_STATE1`
FOREIGN KEY (`LIFECYCLE_STATE_ID`)
REFERENCES `APPM_LIFECYCLE_STATE` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_APPLICATION_APPM_PLATFORM1`
FOREIGN KEY (`PLATFORM_ID`)
REFERENCES `APPM_PLATFORM` (`ID`)
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `AP_APP_RELEASE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AP_APP_RELEASE` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`VERSION` VARCHAR(10) NOT NULL,
`TENANT_ID` VARCHAR(45) NOT NULL,
`UUID` VARCHAR(200) NOT NULL,
`RELEASE_TYPE` VARCHAR(45) NOT NULL,
`APP_PRICE` DECIMAL(6,2) NULL DEFAULT NULL,
`STORED_LOCATION` VARCHAR(45) NOT NULL,
`BANNER_LOCATION` VARCHAR(45) NOT NULL,
`SC_1_LOCATION` VARCHAR(45) NOT NULL,
`SC_2_LOCATION` VARCHAR(45) NULL DEFAULT NULL,
`SC_3_LOCATION` VARCHAR(45) NULL DEFAULT NULL,
`APP_HASH_VALUE` VARCHAR(1000) NOT NULL,
`SHARED_WITH_ALL_TENANTS` INT(11) NULL DEFAULT NULL,
`APP_META_INFO` VARCHAR(20000) NULL DEFAULT NULL,
`RATING` DOUBLE NULL DEFAULT NULL,
`RATED_USERS` INT(11) NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`, `AP_APP_ID`),
CONSTRAINT `fk_AP_APP_RELEASE_AP_APP1`
FOREIGN KEY (`AP_APP_ID`)
REFERENCES `AP_APP` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the applications';
DEFAULT CHARACTER SET = utf8
COMMENT = ' ';
CREATE INDEX `fk_AP_APP_RELEASE_AP_APP1_idx` ON `AP_APP_RELEASE` (`AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_APPLICATION_PROPERTY`
-- Table `AP_APP_REVIEW`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_PROPERTY` (
`PROP_KEY` VARCHAR(255) NOT NULL,
`PROP_VAL` TEXT NULL,
`APPLICATION_ID` INT NOT NULL,
PRIMARY KEY (`PROP_KEY`, `APPLICATION_ID`),
INDEX `FK_APPLICATION_PROPERTY_APPLICATION` (`APPLICATION_ID` ASC),
CONSTRAINT `FK_APPLICATION_PROPERTY_APPLICATION`
FOREIGN KEY (`APPLICATION_ID`)
REFERENCES `APPM_APPLICATION` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_APP_REVIEW` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`COMMENT` VARCHAR(250) NOT NULL,
`REPLY_COMMENT` VARCHAR(250) NULL,
`CREATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`MODEFIED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`RATING` INT(11) NULL,
`USERNAME` VARCHAR(45) NOT NULL,
`AP_APP_RELEASE_ID` INT(11) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `fk_AP_APP_COMMENT_AP_APP_RELEASE1`
FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`)
REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the properties that related to the application';
DEFAULT CHARACTER SET = utf8;
CREATE INDEX `fk_AP_APP_COMMENT_AP_APP_RELEASE1_idx` ON `AP_APP_REVIEW` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_APPLICATION_RELEASE`
-- Table `AP_APP_LIFECYCLE_STATE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_RELEASE` (
`ID` INT NOT NULL AUTO_INCREMENT UNIQUE ,
`VERSION_NAME` VARCHAR(100) NOT NULL,
`RELEASE_RESOURCE` TEXT NULL,
`RELEASE_CHANNEL` VARCHAR(50) DEFAULT 'ALPHA',
`RELEASE_DETAILS` TEXT NULL,
`CREATED_AT` DATETIME NOT NULL,
`APPM_APPLICATION_ID` INT NOT NULL,
`IS_DEFAULT` TINYINT(1) NULL,
PRIMARY KEY (`APPM_APPLICATION_ID`, `VERSION_NAME`),
INDEX `FK_APPLICATION_VERSION_APPLICATION` (`APPM_APPLICATION_ID` ASC),
CONSTRAINT `FK_APPLICATION_VERSION_APPLICATION`
FOREIGN KEY (`APPM_APPLICATION_ID`)
REFERENCES `APPM_APPLICATION` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_APP_LIFECYCLE_STATE` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`CURRENT_STATE` VARCHAR(45) NOT NULL,
`PREVIOUSE_STATE` VARCHAR(45) NOT NULL,
`TENANT_ID` VARCHAR(45) NOT NULL,
`UPDATED_BY` VARCHAR(100) NOT NULL,
`UPDATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`AP_APP_RELEASE_ID` INT(11) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`, `AP_APP_RELEASE_ID`, `AP_APP_ID`),
CONSTRAINT `fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1`
FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`)
REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the application releases';
DEFAULT CHARACTER SET = utf8;
CREATE INDEX `fk_AP_APP_LIFECYCLE_STATE_AP_APP_RELEASE1_idx` ON `AP_APP_LIFECYCLE_STATE` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_RELEASE_PROPERTY`
-- Table `AP_APP_TAG`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_RELEASE_PROPERTY` (
`PROP_KEY` VARCHAR(255) NOT NULL,
`PROP_VALUE` TEXT NULL,
`APPLICATION_RELEASE_ID` INT NOT NULL,
PRIMARY KEY (`PROP_KEY`, `APPLICATION_RELEASE_ID`),
INDEX `FK_RELEASE_PROPERTY_APPLICATION_RELEASE` (`APPLICATION_RELEASE_ID` ASC),
CONSTRAINT `FK_RELEASE_PROPERTY_APPLICATION_RELEASE`
FOREIGN KEY (`APPLICATION_RELEASE_ID`)
REFERENCES `APPM_APPLICATION_RELEASE` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_APP_TAG` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`TAG` VARCHAR(45) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `fk_AP_APP_TAGS_AP_APP1`
FOREIGN KEY (`AP_APP_ID`)
REFERENCES `AP_APP` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the properties that related to the application release';
-- -----------------------------------------------------
-- Table `APPM_RESOURCE_TYPE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_RESOURCE_TYPE` (
`ID` INT NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(45) NULL,
`DESCRIPTION` TEXT NULL,
PRIMARY KEY (`ID`))
ENGINE = InnoDB;
DEFAULT CHARACTER SET = utf8;
INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('PUBLIC', 'OPEN VISIBILITY, CAN BE VIEWED BY ALL LOGGED IN USERS');
INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('ROLES', 'ROLE BASED RESTRICTION, CAN BE VIEWED BY ONLY GIVEN
SET OF USER WHO HAVE THE SPECIFIED ROLE');
INSERT INTO APPM_RESOURCE_TYPE (NAME , DESCRIPTION) VALUES ('DEVICE_GROUPS', 'DEVICE GROUP LEVEL RESTRICTION,
CAN BE VIEWED BY THE DEVICES/ROLES BELONG TO THE GROUP');
CREATE INDEX `fk_AP_APP_TAGS_AP_APP1_idx` ON `AP_APP_TAG` (`AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_SUBSCRIPTION`
-- Table `AP_DEVICE_SUBSCRIPTION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_SUBSCRIPTION` (
`ID` INT NOT NULL AUTO_INCREMENT,
`VALUE` VARCHAR(255) NOT NULL,
`CREATED_AT` DATETIME NOT NULL,
`RESOURCE_TYPE_ID` INT NOT NULL,
`APPLICATION_ID` INT NOT NULL,
`APPLICATION_RELEASE_ID` INT NULL,
PRIMARY KEY (`ID`, `APPLICATION_ID`, `RESOURCE_TYPE_ID`),
INDEX `FK_APPLICATION_SUBSCRIPTION_RESOURCE_TYPE` (`RESOURCE_TYPE_ID` ASC),
INDEX `FK_APPLICATION_SUBSCRIPTION_APPLICATION` (`APPLICATION_ID` ASC),
INDEX `FK_APPLICATION_SUBSCRIPTION_APPLICATION_RELEASE` (`APPLICATION_RELEASE_ID` ASC),
CONSTRAINT `fk_APPM_APPLICATION_SUBSCRIPTION_APPM_RESOURCE_TYPE1`
FOREIGN KEY (`RESOURCE_TYPE_ID`)
REFERENCES `APPM_RESOURCE_TYPE` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION1`
FOREIGN KEY (`APPLICATION_ID`)
REFERENCES `APPM_APPLICATION` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_APPLICATION_SUBSCRIPTION_APPM_APPLICATION_RELEASE1`
FOREIGN KEY (`APPLICATION_RELEASE_ID`)
REFERENCES `APPM_APPLICATION_RELEASE` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_DEVICE_SUBSCRIPTION` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`SUBSCRIBED_BY` VARCHAR(100) NOT NULL,
`SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`UNSUBSCRIBED` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL,
`DM_ENROLMENT_ID` INT(11) NOT NULL,
`AP_APP_RELEASE_ID` INT(11) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1`
FOREIGN KEY (`AP_APP_ID` , `AP_APP_RELEASE_ID`)
REFERENCES `AP_APP_RELEASE` (`AP_APP_ID` , `ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the application subscriptions';
DEFAULT CHARACTER SET = utf8;
CREATE INDEX `fk_AP_DEVICE_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_DEVICE_SUBSCRIPTION` (`AP_APP_ID` ASC, `AP_APP_RELEASE_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_COMMENT`
-- Table `AP_GROUP_SUBSCRIPTION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_COMMENT` (
`ID` INT NOT NULL AUTO_INCREMENT,
`APPLICATION_RELEASE_ID` INT NOT NULL,
`COMMENT_SUBJECT` VARCHAR(255) NULL,
`COMMENT_BODY` TEXT NULL,
`RATING` INT NULL,
`PARENT_ID` INT NULL,
`CREATED_AT` DATETIME NOT NULL,
`CREATED_BY` VARCHAR(45) NULL,
`MODIFIED_AT` DATETIME NULL,
`PUBLISHED` TINYINT(1) NULL,
`APPROVED` TINYINT(1) NULL,
PRIMARY KEY (`ID`, `APPLICATION_RELEASE_ID`),
INDEX `FK_APPLICATION_COMMENTS_APPLICATION_RELEASE` (`APPLICATION_RELEASE_ID` ASC),
CONSTRAINT `FK_APPLICATION_COMMENTS_APPLICATION_RELEASE`
FOREIGN KEY (`APPLICATION_RELEASE_ID`)
REFERENCES `APPM_APPLICATION_RELEASE` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_GROUP_SUBSCRIPTION` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`SUBSCRIBED_BY` VARCHAR(100) NOT NULL,
`SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`UNSUBSCRIBED` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL,
`DM_GROUP_ID` INT(11) NOT NULL,
`AP_APP_RELEASE_ID` INT(11) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1`
FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`)
REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the application comments';
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `APPM_PLATFORM_TAG`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_PLATFORM_TAG` (
`name` VARCHAR(100) NOT NULL,
`PLATFORM_ID` INT NOT NULL,
PRIMARY KEY (`PLATFORM_ID`, `name`),
INDEX `FK_PLATFORM_TAGS_PLATFORM` (`PLATFORM_ID` ASC),
CONSTRAINT `fk_APPM_SUPPORTED_PLATFORM_TAGS_APPM_SUPPORTED_PLATFORM1`
FOREIGN KEY (`PLATFORM_ID`)
REFERENCES `APPM_PLATFORM` (`ID`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the app platform tag';
CREATE INDEX `fk_AP_GROUP_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_GROUP_SUBSCRIPTION` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_APPLICATION_TAG`
-- Table `AP_ROLE_SUBSCRIPTION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_TAG` (
`NAME` VARCHAR(45) NOT NULL,
`APPLICATION_ID` INT NOT NULL,
PRIMARY KEY (`APPLICATION_ID`, `NAME`),
INDEX `FK_APPLICATION_TAG_APPLICATION` (`APPLICATION_ID` ASC),
CONSTRAINT `fk_APPM_APPLICATION_TAG_APPM_APPLICATION1`
FOREIGN KEY (`APPLICATION_ID`)
REFERENCES `APPM_APPLICATION` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_ROLE_SUBSCRIPTION` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`ROLE_NAME` VARCHAR(100) NOT NULL,
`SUBSCRIBED_BY` VARCHAR(100) NOT NULL,
`SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`UNSUBSCRIBED` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL,
`AP_APP_RELEASE_ID` INT(11) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1`
FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`)
REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
COMMENT = 'This table contains the data related to the application tags';
DEFAULT CHARACTER SET = utf8;
CREATE INDEX `fk_AP_ROLE_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_ROLE_SUBSCRIPTION` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_VISIBILITY`
-- Table `AP_UNRESTRICTED_ROLE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_VISIBILITY` (
`ID` INT NOT NULL AUTO_INCREMENT,
`VALUE` VARCHAR(255),
`RESOURCE_TYPE_ID` INT NOT NULL,
`APPLICATION_ID` INT NULL,
CREATE TABLE IF NOT EXISTS `AP_UNRESTRICTED_ROLE` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`ROLE` VARCHAR(45) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
INDEX `FK_APPM_VISIBILITY_RESOURCE_TYPE` (`RESOURCE_TYPE_ID` ASC),
INDEX `FK_VISIBILITY_APPLICATION` (`APPLICATION_ID` ASC),
CONSTRAINT `fk_APPM_VISIBILITY_APPM_RESOURCE_TYPE1`
FOREIGN KEY (`RESOURCE_TYPE_ID`)
REFERENCES `APPM_RESOURCE_TYPE` (`ID`)
CONSTRAINT `fk_AP_APP_VISIBILITY_AP_APP1`
FOREIGN KEY (`AP_APP_ID`)
REFERENCES `AP_APP` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_APPM_VISIBILITY_APPM_APPLICATION1`
FOREIGN KEY (`APPLICATION_ID`)
REFERENCES `APPM_APPLICATION` (`ID`)
ON DELETE CASCADE
ON UPDATE CASCADE )
ENGINE = InnoDB;
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE INDEX `fk_AP_APP_VISIBILITY_AP_APP1_idx` ON `AP_UNRESTRICTED_ROLE` (`AP_APP_ID` ASC);
-- -----------------------------------------------------
-- Table `APPM_SUBSCRIPTION_PROPERTIES`
-- Table `AP_USER_SUBSCRIPTION`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_SUBSCRIPTION_PROPERTIES` (
`PROP_KEY` VARCHAR(255) NOT NULL,
`PROP_VALUE` TEXT NULL,
`APPM_SUBSCRIPTION_ID` INT NOT NULL,
PRIMARY KEY (`PROP_KEY`, `APPM_SUBSCRIPTION_ID`),
INDEX `FK_SUBSCRIPTION_PROPERTIES_SUBSCRIPTION` (`APPM_SUBSCRIPTION_ID` ASC),
CONSTRAINT `fk_APPM_SUBSCRIPTION_PROPERTIES_APPM_SUBSCRIPTION1`
FOREIGN KEY (`APPM_SUBSCRIPTION_ID`)
REFERENCES `APPM_SUBSCRIPTION` (`ID`)
CREATE TABLE IF NOT EXISTS `AP_USER_SUBSCRIPTION` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL,
`USER_NAME` VARCHAR(100) NOT NULL,
`SUBSCRIBED_BY` VARCHAR(100) NOT NULL,
`SUBSCRIBED_TIMESTAMP` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`UNSUBSCRIBED` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_BY` INT(11) NULL DEFAULT NULL,
`UNSUBSCRIBED_TIMESTAMP` TIMESTAMP NULL DEFAULT NULL,
`AP_APP_RELEASE_ID` INT(11) NOT NULL,
`AP_APP_ID` INT(11) NOT NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1`
FOREIGN KEY (`AP_APP_RELEASE_ID` , `AP_APP_ID`)
REFERENCES `AP_APP_RELEASE` (`ID` , `AP_APP_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `APPM_DEVICE_APPLICATION_MAPPING`
-- -----------------------------------------------------
-- CREATE TABLE IF NOT EXISTS `APPM_DEVICE_APPLICATION_MAPPING` (
-- `ID` INT AUTO_INCREMENT NOT NULL,
-- `DEVICE_IDENTIFIER` VARCHAR(255) NOT NULL,
-- `APPLICATION_UUID` VARCHAR(100) NOT NULL,
-- `INSTALLED` BOOLEAN NOT NULL,
-- `SENT_AT` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- PRIMARY KEY (ID),
-- CONSTRAINT `fk_appm_application` FOREIGN KEY (`APPLICATION_UUID`) REFERENCES
-- APPM_APPLICATION (`UUID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
-- UNIQUE KEY `device_app_mapping` (`DEVICE_IDENTIFIER`, `APPLICATION_UUID`)
-- ) ENGINE = InnoDB;
CREATE INDEX `fk_AP_USER_SUBSCRIPTION_AP_APP_RELEASE1_idx` ON `AP_USER_SUBSCRIPTION` (`AP_APP_RELEASE_ID` ASC, `AP_APP_ID` ASC);
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;

@ -1840,7 +1840,7 @@
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.3.5</version>
<version>2.5.3</version>
<extensions>true</extensions>
<configuration>
<obrRepository>NONE</obrRepository>

Loading…
Cancel
Save