add APIs for managing caregories

feature/appm-store/pbac
lasanthaDLPDS 6 years ago
parent b4643d84cd
commit be992c4b8d

@ -243,4 +243,11 @@ public interface ApplicationManager {
List<String> addTags(List<String> tags) throws ApplicationManagementException; List<String> addTags(List<String> tags) throws ApplicationManagementException;
List<String> addApplicationTags(int appId, List<String> tags) throws ApplicationManagementException; List<String> addApplicationTags(int appId, List<String> tags) throws ApplicationManagementException;
List<String> addCategories(List<String> categories) throws ApplicationManagementException;
void deleteCategory(String categoryName) throws ApplicationManagementException;
void updateCategory(String oldCategoryName, String newCategoryName) throws ApplicationManagementException;
} }

@ -79,10 +79,14 @@ public interface ApplicationDAO {
List<String> getAppCategories (int appId, int tenantId) throws ApplicationManagementDAOException; List<String> getAppCategories (int appId, int tenantId) throws ApplicationManagementDAOException;
boolean hasCategoryMapping(int categoryId, int tenantId) throws ApplicationManagementDAOException;
List<CategoryDTO> getAllCategories(int tenantId) throws ApplicationManagementDAOException; List<CategoryDTO> getAllCategories(int tenantId) throws ApplicationManagementDAOException;
List<Integer> getDistinctCategoryIdsInCategoryMapping() throws ApplicationManagementDAOException; List<Integer> getDistinctCategoryIdsInCategoryMapping() throws ApplicationManagementDAOException;
CategoryDTO getCategoryForCategoryName(String categoryName, int tenantId) throws ApplicationManagementDAOException;
void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException; void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException;
void addCategoryMapping(List<Integer> categoryIds, int applicationId, int tenantId) void addCategoryMapping(List<Integer> categoryIds, int applicationId, int tenantId)
@ -90,6 +94,12 @@ public interface ApplicationDAO {
void deleteCategoryMapping (int applicationId, int tenantId) throws ApplicationManagementDAOException; void deleteCategoryMapping (int applicationId, int tenantId) throws ApplicationManagementDAOException;
void deleteCategory(int categoryId, int tenantId) throws ApplicationManagementDAOException;
void updateCategory(CategoryDTO categoryDTO, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To check application existence. * To check application existence.
* *

@ -773,6 +773,39 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public CategoryDTO getCategoryForCategoryName(String categoryName, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get category for given category name.");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT AP_APP_CATEGORY.ID AS ID"
+ " FROM AP_APP_CATEGORY "
+ "WHERE AP_APP_CATEGORY.CATEGORY = ? AND "
+ "AP_APP_CATEGORY.TENANT_ID = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, categoryName);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
CategoryDTO categoryDTO = new CategoryDTO();
categoryDTO.setId(rs.getInt("ID"));
categoryDTO.setCategoryName(categoryName);
return categoryDTO;
}
}
}
return null;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when getting category Id for given category name",
e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"SQL Error occurred while getting category Id for category name.", e);
}
}
@Override @Override
public void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException { public void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException {
@ -866,6 +899,64 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public void deleteCategory(int categoryId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete category.");
}
Connection conn;
String sql = "DELETE FROM " +
"AP_APP_CATEGORY cat " +
"WHERE " +
"cat.ID = ? AND " +
"cat.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, categoryId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when deleting category which has ID: "
+ categoryId, e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred when deleting category which has ID: " + categoryId, e);
}
}
@Override
public void updateCategory(CategoryDTO categoryDTO, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to update a category.");
}
Connection conn;
String sql = "UPDATE " +
"AP_APP_CATEGORY cat " +
"SET cat.CATEGORY_NAME = ? " +
"WHERE " +
"cat.ID = ? AND " +
"cat.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, categoryDTO.getCategoryName());
stmt.setInt(1, categoryDTO.getId());
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when updating category which has ID: "
+ categoryDTO.getId(), e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred when updating category which has ID: " + categoryDTO.getId(), e);
}
}
@Override @Override
public List<Integer> getTagIdsForTagNames(List<String> tagNames, int tenantId) public List<Integer> getTagIdsForTagNames(List<String> tagNames, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
@ -1256,8 +1347,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override @Override
public List<String> getAppCategories(int appId, int tenantId) throws ApplicationManagementDAOException { public List<String> getAppCategories(int appId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -1290,6 +1379,36 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public boolean hasCategoryMapping (int categoryId, int tenantId) throws ApplicationManagementDAOException{
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to verify whether tag is associated with at least one application.");
}
Connection conn;
String sql = "SELECT cm.AP_APP_ID AS ID "
+ "FROM AP_APP_CATEGORY_MAPPING cm "
+ "WHERE "
+ "cm.AP_APP_CATEGORY_ID = ? AND "
+ "cm.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, categoryId);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when verifying the existence of a category mapping",
e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred when verifying the existence of a category mapping.", e);
}
}
@Override @Override
public void deleteTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException { public void deleteTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException {

@ -2010,23 +2010,22 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
@Override
public List<String> addTags(List<String> tags) throws ApplicationManagementException { public List<String> addTags(List<String> tags) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
if (tags != null && !tags.isEmpty()) { if (tags != null && !tags.isEmpty()) {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
List<TagDTO> registeredTags = applicationDAO.getAllTags(tenantId); List<TagDTO> registeredTags = applicationDAO.getAllTags(tenantId);
List<String> registeredTagNames = new ArrayList<>(); List<String> registeredTagNames = registeredTags.stream().map(TagDTO::getTagName)
.collect(Collectors.toList());
for (TagDTO tagDTO : registeredTags) {
registeredTagNames.add(tagDTO.getTagName());
}
List<String> newTags = getDifference(tags, registeredTagNames); List<String> newTags = getDifference(tags, registeredTagNames);
if (!newTags.isEmpty()) { if (!newTags.isEmpty()) {
this.applicationDAO.addTags(newTags, tenantId); this.applicationDAO.addTags(newTags, tenantId);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("New tags entries are added to the AP_APP_TAG table."); log.debug("New tags are added to the AP_APP_TAG table.");
} }
} }
return Stream.concat(registeredTagNames.stream(), newTags.stream()).collect(Collectors.toList()); return Stream.concat(registeredTagNames.stream(), newTags.stream()).collect(Collectors.toList());
@ -2053,11 +2052,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (tags != null && !tags.isEmpty()) { if (tags != null && !tags.isEmpty()) {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
List<TagDTO> registeredTags = applicationDAO.getAllTags(tenantId); List<TagDTO> registeredTags = applicationDAO.getAllTags(tenantId);
List<String> registeredTagNames = new ArrayList<>(); List<String> registeredTagNames = registeredTags.stream().map(TagDTO::getTagName)
.collect(Collectors.toList());
for (TagDTO tagDTO : registeredTags) {
registeredTagNames.add(tagDTO.getTagName());
}
List<String> newTags = getDifference(tags, registeredTagNames); List<String> newTags = getDifference(tags, registeredTagNames);
if (!newTags.isEmpty()) { if (!newTags.isEmpty()) {
this.applicationDAO.addTags(newTags, tenantId); this.applicationDAO.addTags(newTags, tenantId);
@ -2090,6 +2087,92 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
public List<String> addCategories(List<String> categories) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
if (categories != null && !categories.isEmpty()) {
ConnectionManagerUtil.beginDBTransaction();
List<CategoryDTO> registeredCategories = applicationDAO.getAllCategories(tenantId);
List<String> registeredCategoryNames = registeredCategories.stream().map(CategoryDTO::getCategoryName)
.collect(Collectors.toList());
List<String> newCategories = getDifference(categories, registeredCategoryNames);
if (!newCategories.isEmpty()) {
this.applicationDAO.addCategories(newCategories, tenantId);
ConnectionManagerUtil.commitDBTransaction();
if (log.isDebugEnabled()) {
log.debug("New categories are added to the AP_APP_TAG table.");
}
}
return Stream.concat(registeredCategoryNames.stream(), newCategories.stream())
.collect(Collectors.toList());
} else{
String msg = "Category list is either null of empty. In order to add new categories, category list "
+ "should be a list of Stings. Therefore please verify the payload.";
log.error(msg);
throw new BadRequestException(msg);
}
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred either getting registered categories or adding new categories.";
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void deleteCategory(String tagName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
ConnectionManagerUtil.beginDBTransaction();
CategoryDTO category = applicationDAO.getCategoryForCategoryName(tagName, tenantId);
if (category == null){
String msg = "Couldn't found a category for category name " + tagName + ".";
log.error(msg);
throw new NotFoundException(msg);
}
if (applicationDAO.hasCategoryMapping(category.getId(), tenantId)){
String msg = "Category " + category.getCategoryName()
+ " is used by some applications. Therefore it is not permitted to delete the application category.";
log.error(msg);
throw new ForbiddenException(msg);
}
applicationDAO.deleteCategory(category.getId(), tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred when getting category Id or deleting the category from the system.";
log.error(msg);
throw new ApplicationManagementException(msg);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void updateCategory(String oldCategoryName, String newCategoryName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
ConnectionManagerUtil.beginDBTransaction();
CategoryDTO category = applicationDAO.getCategoryForCategoryName(oldCategoryName, tenantId);
if (category == null){
String msg = "Couldn't found a category for tag name " + oldCategoryName + ".";
log.error(msg);
throw new NotFoundException(msg);
}
category.setCategoryName(newCategoryName);
applicationDAO.updateCategory(category, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred when getting tag Ids or deleting the category from the system.";
log.error(msg);
throw new ApplicationManagementException(msg);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
private void validateFilter(Filter filter) throws BadRequestException { private void validateFilter(Filter filter) throws BadRequestException {
if (filter == null) { if (filter == null) {
String msg = "Filter validation is failed, Filter shouldn't be null, hence please verify the request payload"; String msg = "Filter validation is failed, Filter shouldn't be null, hence please verify the request payload";

@ -35,11 +35,15 @@ import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List;
/** /**
* APIs to handle application management related tasks. * APIs to handle application management related tasks.
@ -186,4 +190,120 @@ public interface ApplicationManagementPublisherAdminAPI {
required = true) required = true)
@PathParam("tagName") String tagName @PathParam("tagName") String tagName
); );
@POST
@Path("/categories")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add new application categories.",
notes = "This will add new application categories",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:app:publisher:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully delete registered tag.",
response = ApplicationList.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n " +
"Category list is either empty or null"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting registered tag.",
response = ErrorResponse.class)
})
Response addCategories(
@ApiParam(
name = "tagName",
value = "Tag Name",
required = true) List<String> categorynames
);
@PUT
@Path("/tags/{tagName}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Update application category",
notes = "This will update application category.",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:app:publisher:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully delete registered category.",
response = ApplicationList.class),
@ApiResponse(
code = 404,
message = "Not Found. There doesn't have an category for given category name.."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting registered category.",
response = ErrorResponse.class)
})
Response renameCategory(
@ApiParam(
name = "oldCategoryName",
value = "Existing Category Name",
required = true)
@QueryParam("from") String oldCategoryName,
@ApiParam(
name = "newCategoryName",
value = "Modifying Category Name",
required = true)
@QueryParam("to") String newCategoryName
);
@DELETE
@Path("/categories/{categoryName}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Delete application category",
notes = "This will delete application category.",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:app:publisher:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully deleted registered category.",
response = ApplicationList.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting registered category.",
response = ErrorResponse.class)
})
Response deleteCategory(
@ApiParam(
name = "categoryName",
value = "Category Name",
required = true)
@PathParam("categoryName") String categoryName
);
} }

@ -16,7 +16,6 @@
*/ */
package org.wso2.carbon.device.application.mgt.publisher.api.services.impl; package org.wso2.carbon.device.application.mgt.publisher.api.services.impl;
import org.apache.axiom.attachments.utils.BAAInputStream;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;

@ -22,6 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
@ -29,10 +30,14 @@ import org.wso2.carbon.device.application.mgt.publisher.api.services.admin.Appli
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List;
/** /**
* Implementation of Application Management related APIs. * Implementation of Application Management related APIs.
@ -117,4 +122,70 @@ public class ApplicationManagementPublisherAdminAPIImpl implements ApplicationMa
} }
} }
@POST
@Override
@Consumes("application/json")
@Path("/categories")
public Response addCategories(
List<String> categoryNames) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
try {
applicationManager.addCategories(categoryNames);
String msg = "New application categories are added successfully.";
return Response.status(Response.Status.OK).entity(msg).build();
} catch (BadRequestException e) {
String msg = e.getMessage();
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error Occurred while adding new categories.";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
@Override
@Consumes("application/json")
@Path("/categories/rename")
public Response renameCategory(
@QueryParam("from") String oldCategoryName,
@QueryParam("to") String newCategoryName) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
try {
applicationManager.updateCategory(oldCategoryName, newCategoryName);
String msg = "Category is updated from " + oldCategoryName + " to " + newCategoryName;
return Response.status(Response.Status.OK).entity(msg).build();
} catch (NotFoundException e) {
String msg = e.getMessage();
log.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error Occurred while rename registered category.";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@DELETE
@Override
@Consumes("application/json")
@Path("/categories/{categoryName}")
public Response deleteCategory(
@PathParam("categoryName") String categoryName) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
try {
applicationManager.deleteCategory(categoryName);
String msg = "Category " + categoryName + " is deleted successfully.";
return Response.status(Response.Status.OK).entity(msg).build();
} catch (NotFoundException e) {
String msg = e.getMessage();
log.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error Occurred while deleting registered category.";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
} }

Loading…
Cancel
Save