From cf1e808cbd4afa8f9e6cdbb6e79caff1ea335ab3 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 31 May 2016 13:57:38 +0530 Subject: [PATCH 01/29] refactored after testing UserAdminManangmentService --- ...pper.java => OldPasswordResetWrapper.java} | 24 +------ .../mgt/jaxrs/beans/PasswordResetWrapper.java | 41 +++++++++++ .../service/api/UserManagementService.java | 5 +- .../api/admin/UserManagementAdminService.java | 4 +- .../impl/UserManagementServiceImpl.java | 6 +- .../admin/UserManagementAdminServiceImpl.java | 6 +- .../CredentialManagementResponseBuilder.java | 71 ++++++++++++++----- .../mgt/jaxrs/util/DeviceMgtAPIUtils.java | 12 ++++ 8 files changed, 119 insertions(+), 50 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/{UserCredentialWrapper.java => OldPasswordResetWrapper.java} (62%) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PasswordResetWrapper.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/OldPasswordResetWrapper.java similarity index 62% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/OldPasswordResetWrapper.java index e5674b9de7..bef53c06b7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/OldPasswordResetWrapper.java @@ -21,34 +21,14 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -@ApiModel(value = "UserCredentialWrapper", description = "User credentials are included in this class.") -public class UserCredentialWrapper { +@ApiModel(value = "OldPasswordResetWrapper", description = "User credentials are included in this class.") +public class OldPasswordResetWrapper extends PasswordResetWrapper{ - @ApiModelProperty(name = "username", value = "Username of the user.", required = true ) - private String username; /* Base64 encoded password */ @ApiModelProperty(name = "oldPassword", value = "Old password of the user.", required = true ) private String oldPassword; - @ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true ) - private String newPassword; - - public String getNewPassword() { - return newPassword; - } - - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } public String getOldPassword() { return oldPassword; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PasswordResetWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PasswordResetWrapper.java new file mode 100644 index 0000000000..7bd67c2028 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PasswordResetWrapper.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "PasswordResetWrapper", description = "User credential is included in this class.") +public class PasswordResetWrapper { + + /* + Base64 encoded password + */ + @ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true ) + private String newPassword; + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index 1631eeaa28..a2c3362575 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -21,13 +21,12 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.Date; @API(name = "User Management API", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"}) @@ -438,6 +437,6 @@ public interface UserManagementService { @ApiParam( name = "credentials", value = "Credential.", - required = true) UserCredentialWrapper credentials); + required = true) OldPasswordResetWrapper credentials); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java index 7dd351734b..baec3eff63 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -71,6 +71,6 @@ public interface UserManagementAdminService { @ApiParam( name = "credentials", value = "Credential.", - required = true) UserCredentialWrapper credentials); + required = true) PasswordResetWrapper credentials); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 260b4df291..1a2bb05f2d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -26,7 +26,7 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; -import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; @@ -390,8 +390,8 @@ public class UserManagementServiceImpl implements UserManagementService { @PUT @Path("/{username}/credentials") @Override - public Response resetPassword(@PathParam("username") String username, UserCredentialWrapper credentials) { - return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials); + public Response resetPassword(@PathParam("username") String username, OldPasswordResetWrapper credentials) { + return CredentialManagementResponseBuilder.buildChangePasswordResponse(username, credentials); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index fc30afea17..1613c49b87 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -18,7 +18,7 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; -import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.UserManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; @@ -34,8 +34,8 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic @POST @Path("/{username}/credentials") @Override - public Response resetPassword(@PathParam("username") String user, UserCredentialWrapper credentials) { - return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); + public Response resetPassword(@PathParam("username") String user, PasswordResetWrapper credentials) { + return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java index dfdc187e16..2edbb20ebb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java @@ -18,15 +18,16 @@ package org.wso2.carbon.device.mgt.jaxrs.util; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; +import java.util.regex.Pattern; /** * This class builds Credential modification related Responses @@ -34,26 +35,38 @@ import java.io.UnsupportedEncodingException; public class CredentialManagementResponseBuilder { private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class); + private static String PASSWORD_VALIDATION_REGEX_TAG = "PasswordJavaRegEx"; /** * Builds the response to change the password of a user + * @param username - Username of the user. * @param credentials - User credentials * @return Response Object */ - public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) { + public static Response buildChangePasswordResponse(String username, OldPasswordResetWrapper credentials) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); - byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword()); - userStoreManager.updateCredential(credentials.getUsername(), new String( - decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8")); + if (!userStoreManager.isExistingUser(username)) { + return Response.status(Response.Status.BAD_REQUEST).entity("No user found with the username " + + username).build(); + } + if (credentials == null || credentials.getNewPassword() == null || credentials.getOldPassword() == null) { + return Response.status(Response.Status.BAD_REQUEST).entity("Password cannot be empty.") + .build(); + } + if (!validateCredential(credentials.getNewPassword())) { + return Response.status(Response.Status.BAD_REQUEST).entity("Password does not match with required format.") + .build(); + } + userStoreManager.updateCredential(username, credentials.getNewPassword(), + credentials.getOldPassword()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + - credentials.getUsername() + " was successfully changed.").build(); + username + " was successfully changed.").build(); } catch (UserStoreException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST).entity("Old password does not match.").build(); } catch (UnsupportedEncodingException e) { - String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + + String errorMsg = "Could not change the password of the user: " + username + ". The Character Encoding is not supported."; log.error(errorMsg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build(); @@ -62,27 +75,51 @@ public class CredentialManagementResponseBuilder { /** * Builds the response to reset the password of a user + * @param username - Username of the user. * @param credentials - User credentials * @return Response Object */ - public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) { + public static Response buildResetPasswordResponse(String username, PasswordResetWrapper credentials) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); - userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( - decodedNewPassword, "UTF-8")); - return Response.status(Response.Status.CREATED).entity("UserImpl password by username: " + - credentials.getUsername() + " was successfully changed.").build(); + if (!userStoreManager.isExistingUser(username)) { + return Response.status(Response.Status.BAD_REQUEST).entity("No user found with the username " + + username).build(); + } + if (credentials == null || credentials.getNewPassword() == null) { + return Response.status(Response.Status.BAD_REQUEST).entity("Password cannot be empty.") + .build(); + } + if (!validateCredential(credentials.getNewPassword())) { + return Response.status(Response.Status.BAD_REQUEST).entity("Password does not match with required format.") + .build(); + } + userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); + return Response.status(Response.Status.OK).entity("UserImpl password by username: " + + username + " was successfully changed.").build(); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while updating the credentials of user '" + credentials.getUsername() + "'"; + String msg = "ErrorResponse occurred while updating the credentials of user '" + username + "'"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (UnsupportedEncodingException e) { - String msg = "Could not change the password of the user: " + credentials.getUsername() + + String msg = "Could not change the password of the user: " + username + ". The Character Encoding is not supported."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } + private static boolean validateCredential(String password) + throws UserStoreException, UnsupportedEncodingException { + String passwordValidationRegex = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() + .getUserStoreProperty(PASSWORD_VALIDATION_REGEX_TAG); + if (passwordValidationRegex != null) { + Pattern pattern = Pattern.compile(passwordValidationRegex); + if (pattern.matcher(password).matches()) { + return true; + } + } + return false; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index 53ec73b841..f70a157b9f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -131,6 +131,18 @@ public class DeviceMgtAPIUtils { return userStoreManager; } + public static RealmService getRealmService() throws UserStoreException { + RealmService realmService; + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); + if (realmService == null) { + String msg = "Realm service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return realmService; + } + /** * Getting the current tenant's user realm */ From 1d4d0b7ae2850da6645ed0ab9d5f875403995f62 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 16:13:45 +0530 Subject: [PATCH 02/29] Improving certificate management webapp implementation --- .../mgt/jaxrs/api/CertificateMgtService.java | 47 +++- .../api/impl/CertificateMgtServiceImpl.java | 19 +- .../mgt/jaxrs/beans/ErrorListItem.java | 79 ++++++ .../mgt/jaxrs/beans/ErrorResponse.java | 193 +++++++++++++ .../UnexpectedServerErrorException.java | 34 +++ .../pom.xml | 4 - .../mgt/cert/jaxrs/api/Certificate.java | 123 --------- .../CertificateManagementAdminService.java | 255 ++++++++++++++++++ .../jaxrs/api/InputValidationException.java | 35 +++ .../api/UnexpectedServerErrorException.java | 34 +++ .../jaxrs/api/beans/BasePaginatedResult.java | 72 +++++ .../cert/jaxrs/api/beans/CertificateList.java | 55 ++++ .../cert/jaxrs/api/beans/ErrorListItem.java | 79 ++++++ .../cert/jaxrs/api/beans/ErrorResponse.java | 193 +++++++++++++ .../cert/jaxrs/api/impl/CertificateImpl.java | 181 ------------- ...CertificateManagementAdminServiceImpl.java | 134 +++++++++ .../jaxrs/api/util/DeviceMgtAPIUtils.java | 2 +- .../jaxrs/api/util/RequestValidationUtil.java | 48 ++++ .../src/main/webapp/META-INF/permissions.xml | 4 +- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 1 + 21 files changed, 1271 insertions(+), 323 deletions(-) create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorListItem.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorResponse.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/exception/UnexpectedServerErrorException.java delete mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/InputValidationException.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/UnexpectedServerErrorException.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/BasePaginatedResult.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/CertificateList.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorListItem.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorResponse.java delete mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/RequestValidationUtil.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java index 6c9abc27b6..a2f298ba91 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java @@ -1,9 +1,18 @@ package org.wso2.carbon.certificate.mgt.jaxrs.api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; + import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@Path("/scep") public interface CertificateMgtService { /** @@ -13,8 +22,38 @@ public interface CertificateMgtService { * @return X509Certificate type sign certificate. */ @POST - @Path("signcsr") - @Produces({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN}) - @Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN}) - Response getSignedCertFromCSR(String binarySecurityToken); + @Path("/sign-csr") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.TEXT_PLAIN) + @ApiOperation( + consumes = MediaType.TEXT_PLAIN, + produces = MediaType.TEXT_PLAIN, + httpMethod = "POST", + value = "Process a given CSR and return signed certificates.", + notes = "This will return a signed certificate upon a given CSR.", + tags = "Device Management") + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the device location.", + response = String.class), + @ApiResponse( + code = 304, + message = "Not Modified. \n " + + "Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while retrieving signed certificate.", + response = ErrorResponse.class) + }) + @Permission(scope = "sign-csr", permissions = {"/permission/admin/device-mgt/scep/sign-csr"}) + Response getSignedCertFromCSR( + @ApiParam( + name = "If-Modified-Since", + value = "Validates if the requested variant has not been modified since the time specified", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince, + String binarySecurityToken); + } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java index e0ca24de02..71c03b6e1c 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/impl/CertificateMgtServiceImpl.java @@ -5,6 +5,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.certificate.mgt.jaxrs.exception.UnexpectedServerErrorException; import org.wso2.carbon.certificate.mgt.jaxrs.api.CertificateMgtService; import org.wso2.carbon.certificate.mgt.jaxrs.exception.Message; @@ -14,15 +16,16 @@ import javax.ws.rs.core.Response; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; - +@Path("/scep") public class CertificateMgtServiceImpl implements CertificateMgtService { private static Log log = LogFactory.getLog(CertificateMgtServiceImpl.class); @POST - @Path("signcsr") - @Produces({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN}) - @Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN}) - public Response getSignedCertFromCSR(String binarySecurityToken) { + @Path("/sign-csr") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.TEXT_PLAIN) + public Response getSignedCertFromCSR( + @HeaderParam("If-Modified-Since") String ifModifiedSince, String binarySecurityToken) { Message message = new Message(); X509Certificate signedCert; String singedCertificate; @@ -41,11 +44,13 @@ public class CertificateMgtServiceImpl implements CertificateMgtService { } catch (KeystoreException e) { String msg = "Error occurred while fetching certificate."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode( + 500l).setMessage(msg).build()); } catch (CertificateEncodingException e) { String msg = "Error occurred while encoding the certificate."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode( + 500l).setMessage(msg).build()); } } } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorListItem.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorListItem.java new file mode 100644 index 0000000000..b9b6e6c67c --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorListItem.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.constraints.NotNull; + +@ApiModel(description = "Error List Item") +public class ErrorListItem { + + @NotNull + private String code = null; + @NotNull + private String message = null; + + @ApiModelProperty(required = true, value = "") + @JsonProperty("code") + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public ErrorListItem() { + } + + public ErrorListItem(String code, String msg) { + this.code = code; + this.message = msg; + } + + + /** + * Description about individual errors occurred + */ + @ApiModelProperty(required = true, value = "Description about individual errors occurred") + @JsonProperty("message") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("errorItem {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorResponse.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorResponse.java new file mode 100644 index 0000000000..81b49c5da5 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/beans/ErrorResponse.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.ArrayList; +import java.util.List; + +@ApiModel(description = "Error Response") +public class ErrorResponse { + + private Long code = null; + private String message = null; + private String description = null; + private String moreInfo = null; + private List errorItems = new ArrayList<>(); + + private ErrorResponse() { + } + + @JsonProperty(value = "code") + @ApiModelProperty(required = true, value = "") + public Long getCode() { + return code; + } + + public void setCode(Long code) { + this.code = code; + } + + @JsonProperty(value = "message") + @ApiModelProperty(required = true, value = "ErrorResponse message.") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @JsonProperty(value = "description") + @ApiModelProperty(value = "A detail description about the error message.") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @JsonProperty(value = "moreInfo") + @ApiModelProperty(value = "Preferably an url with more details about the error.") + public String getMoreInfo() { + return moreInfo; + } + + public void setMoreInfo(String moreInfo) { + this.moreInfo = moreInfo; + } + + public void addErrorListItem(ErrorListItem item) { + this.errorItems.add(item); + } + + /** + * If there are more than one error list them out. \nFor example, list out validation errors by each field. + */ + @JsonProperty(value = "errorItems") + @ApiModelProperty(value = "If there are more than one error list them out. \n" + + "For example, list out validation errors by each field.") + public List getErrorItems() { + return errorItems; + } + + public void setErrorItems(List error) { + this.errorItems = error; + } + + @Override + public String toString() { +// StringBuilder sb = new StringBuilder(); +// sb.append("{"); +// boolean cont = false; +// if (code != null) { +// cont = true; +// sb.append(" \"code\": ").append(code); +// } +// if (message != null) { +// if (cont) { +// sb.append(","); +// } +// cont = true; +// sb.append(" \"message\": \"").append(message).append("\""); +// } +// if (description != null) { +// if (cont) { +// sb.append(","); +// } +// cont = true; +// sb.append(" \"description\": ").append(description).append("\""); +// } +// if (moreInfo != null) { +// if (cont) { +// sb.append(","); +// } +// cont = true; +// sb.append(" \"moreInfo\": \"").append(moreInfo).append("\""); +// } +// if (error != null && error.size() > 0) { +// if (cont) { +// sb.append(","); +// } +// sb.append(" \"errorItems\": ").append(error); +// } +// sb.append("}"); +// return sb.toString(); + return null; + } + + public static class ErrorResponseBuilder { + + private Long code = null; + private String message = null; + private String description = null; + private String moreInfo = null; + private List error; + + + public ErrorResponseBuilder() { + this.error = new ArrayList<>(); + } + + public ErrorResponseBuilder setCode(long code) { + this.code = code; + return this; + } + + public ErrorResponseBuilder setMessage(String message) { + this.message = message; + return this; + } + + public ErrorResponseBuilder setDescription(String description) { + this.description = description; + return this; + } + + public ErrorResponseBuilder setMoreInfo(String moreInfo) { + this.moreInfo = moreInfo; + return this; + } + + public ErrorResponseBuilder addErrorItem(String code, String msg) { + ErrorListItem item = new ErrorListItem(); + item.setCode(code); + item.setMessage(msg); + this.error.add(item); + return this; + } + + public ErrorResponse build() { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setCode(code); + errorResponse.setMessage(message); + errorResponse.setErrorItems(error); + errorResponse.setDescription(description); + errorResponse.setMoreInfo(moreInfo); + return errorResponse; + } + } + +} + + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/exception/UnexpectedServerErrorException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/exception/UnexpectedServerErrorException.java new file mode 100644 index 0000000000..9b6e2d4ef2 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/exception/UnexpectedServerErrorException.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.jaxrs.exception; + +import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class UnexpectedServerErrorException extends WebApplicationException { + + private static final long serialVersionUID = 147943679458906890L; + + public UnexpectedServerErrorException(ErrorResponse error) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build()); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index 3b5c4a9a95..95ea9ce63a 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -51,10 +51,6 @@ admin-certificate - - org.apache.felix - maven-scr-plugin - diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java deleted file mode 100644 index 1192cdfa13..0000000000 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/Certificate.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.wso2.carbon.certificate.mgt.cert.jaxrs.api; - -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.MDMAPIException; -import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; -import org.wso2.carbon.device.mgt.common.PaginationResult; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -public interface Certificate { - - /** - * Save a list of certificates and relevant information in the database. - * - * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as - * a pem and a serial number. - * @return Status of the data persist operation. - */ - @POST - @ApiOperation( - consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - httpMethod = "POST", - value = "Adding an SSL Certificate", - notes = "Add a new SSL certificate to the client end database") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Added successfully"), - @ApiResponse(code = 500, message = "Error occurred while saving the certificate") - }) - @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"}) - Response saveCertificate(@HeaderParam("Accept") String acceptHeader, - @ApiParam(name = "enrollmentCertificates", value = "certificate with serial, " - + "pem and tenant id", required = true) EnrollmentCertificate[] - enrollmentCertificates); - - /** - * Get a certificate when the serial number is given. - * - * @param serialNumber serial of the certificate needed. - * @return certificate response. - */ - @GET - @Path("{serialNumber}") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - httpMethod = "GET", - value = "Getting Details of an SSL Certificate", - notes = "Get the client side SSL certificate details", - response = CertificateResponse.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK", response = CertificateResponse.class), - @ApiResponse(code = 400, message = "Notification status updated successfully"), - @ApiResponse(code = 500, message = "Error occurred while converting PEM file to X509Certificate") - }) - @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) - Response getCertificate(@HeaderParam("Accept") String acceptHeader, - @ApiParam(name = "serialNumber", value = "Provide the serial number of the " - + "certificate that you wish to get the details of", required = true) - @PathParam("serialNumber") String serialNumber); - - /** - * Get all certificates in a paginated manner. - * - * @param startIndex index of the first record to be fetched - * @param length number of records to be fetched starting from the start index. - * @return paginated result of certificate. - * @throws MDMAPIException - */ - @GET - @Path("paginate") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - httpMethod = "GET", - value = "Getting the Certificate Details in a Paginated Manner", - notes = "You will have many certificates used for mutual SSL. In a situation where you wish to " - + "view all the certificate details, it is not feasible to show all the details on one " - + "page therefore the details are paginated", - response = PaginationResult.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK", response = PaginationResult.class), - @ApiResponse(code = 400, message = "Invalid start index"), - @ApiResponse(code = 400, message = "Invalid length value"), - @ApiResponse(code = 500, message = "Error occurred while fetching all certificates") - }) - @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) - Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, - @ApiParam(name = "start", - value = "Provide the starting pagination index as the value", required = true) - @QueryParam("start") int startIndex, - @ApiParam(name = "length", value = "Provide how many certificate details you" - + " require from the starting pagination index as the value", - required = true) @QueryParam("length") int length) throws MDMAPIException; - - @DELETE - @Path("{serialNumber}") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, - httpMethod = "DELETE", - value = "Deleting an SSL Certificate", - notes = "Delete an SSL certificate that's on the client end", - response = boolean.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK"), - @ApiResponse(code = 400, message = "Invalid start index"), - @ApiResponse(code = 500, message = "Error when deleting the certificate" - ) }) - @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"}) - Response removeCertificate(@HeaderParam("Accept") String acceptHeader, - @ApiParam(name = "serialNumber", value = "Provide the serial number of the " - + "certificate that you wish to delete", required = true) - @PathParam("serialNumber") String serialNumber) throws MDMAPIException; - -} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java new file mode 100644 index 0000000000..3f9cf9c475 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java @@ -0,0 +1,255 @@ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api; + +import io.swagger.annotations.*; +import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Api(value = "Certificate Management", description = "This API carries all certificate management related operations " + + "such as get all the available devices, etc.") +@Path("/certificates") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface CertificateManagementAdminService { + + /** + * Save a list of certificates and relevant information in the database. + * + * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as + * a pem and a serial number. + * @return Status of the data persist operation. + */ + @POST + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Add a SSL certificate", + notes = "Add a new SSL certificate", + tags = "Certificate Management") + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "Created. \n Certificates have successfully been added", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The URL of the added certificates."), + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.")}), + @ApiResponse( + code = 303, + message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The entity of the request was in a not supported format."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding certificates.", + response = ErrorResponse.class) + }) + @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"}) + Response addCertificate( + @ApiParam( + name = "enrollmentCertificates", + value = "certificate with serial, " + + "pem and tenant id", + required = true) EnrollmentCertificate[] enrollmentCertificates); + + /** + * Get a certificate when the serial number is given. + * + * @param serialNumber serial of the certificate needed. + * @return certificate response. + */ + @GET + @Path("/{serialNumber}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of an SSL CertificateManagementAdminService", + notes = "Get the client side SSL certificate details", + tags = "Certificate Management") + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched information of the device.", + response = CertificateResponse.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n " + + "Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n No device is found under the provided type and id."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving information requested certificate.", + response = ErrorResponse.class) + }) + @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) + Response getCertificate( + @ApiParam(name = "serialNumber", + value = "Provide the serial number of the certificate that you wish to get the details of", + required = true) + @PathParam("serialNumber") String serialNumber, + @ApiParam( + name = "If-Modified-Since", + value = "Validates if the requested variant has not been modified since the time specified", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince + ); + + /** + * Get all certificates in a paginated manner. + * + * @return paginated result of certificate. + */ + @GET + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get certificates", + notes = "You will have many certificates used for mutual SSL. In a situation where you wish to " + + "view all the certificate details, it is not feasible to show all the details on one " + + "page therefore the details are paginated", + tags = "Certificate Management" + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n List of certificates enrolled in the system", + response = CertificateList.class, + responseContainer = "List", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.")}), + @ApiResponse( + code = 303, + message = "See Other. \n " + + "Source can be retrieved from the URL specified at the Location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 304, + message = "Not Modified. \n " + + "Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable. \n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving all certificates enrolled in the system.", + response = ErrorResponse.class) + }) + @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) + Response getAllCertificates( + @ApiParam( + name = "offset", + value = "Starting point within the complete list of items qualified.", + required = false) + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Maximum size of resource array to return.", + required = false) + @QueryParam("limit") int limit, + @ApiParam( + name = "If-Modified-Since", + value = "Validates if the requested variant has not been modified since the time specified", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince); + + @DELETE + @Path("/{serialNumber}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Delete an SSL certificate", + notes = "Delete an SSL certificate that's on the client end") + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Certificate has successfully been removed"), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n Resource to be deleted does not exist."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while removing the certificate.", + response = ErrorResponse.class)}) + @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"}) + Response removeCertificate( + @ApiParam( + name = "serialNumber", + value = "Provide the serial number of the " + + "certificate that you wish to delete", + required = true) + @PathParam("serialNumber") String serialNumber); + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/InputValidationException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/InputValidationException.java new file mode 100644 index 0000000000..0804806967 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/InputValidationException.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api; + +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import java.io.Serializable; + +public class InputValidationException extends WebApplicationException implements Serializable { + + private static final long serialVersionUID = 147843589458906890L; + + public InputValidationException(ErrorResponse error) { + super(Response.status(Response.Status.BAD_REQUEST).entity(error).build()); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/UnexpectedServerErrorException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/UnexpectedServerErrorException.java new file mode 100644 index 0000000000..28eaed09bc --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/UnexpectedServerErrorException.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api; + +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class UnexpectedServerErrorException extends WebApplicationException { + + private static final long serialVersionUID = 147943679458906890L; + + public UnexpectedServerErrorException(ErrorResponse error) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build()); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/BasePaginatedResult.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/BasePaginatedResult.java new file mode 100644 index 0000000000..b1fe40a9ec --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/BasePaginatedResult.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +public class BasePaginatedResult { + + private int count; + private String next; + private String previous; + + /** + * Number of Devices returned. + */ + @ApiModelProperty(value = "Number of resources returned.") + @JsonProperty("count") + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + + /** + * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. + */ + @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + + "Empty if no more resources are to be returned.") + @JsonProperty("next") + public String getNext() { + return next; + } + + public void setNext(String next) { + this.next = next; + } + + /** + * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. + */ + @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + + "Empty if current subset is the first subset returned.") + @JsonProperty("previous") + public String getPrevious() { + return previous; + } + + public void setPrevious(String previous) { + this.previous = previous; + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/CertificateList.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/CertificateList.java new file mode 100644 index 0000000000..2c61a4b23a --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/CertificateList.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; + +import java.util.ArrayList; +import java.util.List; + +public class CertificateList extends BasePaginatedResult { + + private List certificates = new ArrayList<>(); + + @ApiModelProperty(value = "List of certificates returned") + @JsonProperty("certificates") + public List getList() { + return certificates; + } + + public void setList(List certificates) { + this.certificates = certificates; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); + sb.append(" certificates: [").append(certificates).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorListItem.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorListItem.java new file mode 100644 index 0000000000..dc3a94efb1 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorListItem.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.constraints.NotNull; + +@ApiModel(description = "Error List Item") +public class ErrorListItem { + + @NotNull + private String code = null; + @NotNull + private String message = null; + + @ApiModelProperty(required = true, value = "") + @JsonProperty("code") + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public ErrorListItem() { + } + + public ErrorListItem(String code, String msg) { + this.code = code; + this.message = msg; + } + + + /** + * Description about individual errors occurred + */ + @ApiModelProperty(required = true, value = "Description about individual errors occurred") + @JsonProperty("message") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("errorItem {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorResponse.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorResponse.java new file mode 100644 index 0000000000..f8101d796f --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/beans/ErrorResponse.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.ArrayList; +import java.util.List; + +@ApiModel(description = "Error Response") +public class ErrorResponse { + + private Long code = null; + private String message = null; + private String description = null; + private String moreInfo = null; + private List errorItems = new ArrayList<>(); + + private ErrorResponse() { + } + + @JsonProperty(value = "code") + @ApiModelProperty(required = true, value = "") + public Long getCode() { + return code; + } + + public void setCode(Long code) { + this.code = code; + } + + @JsonProperty(value = "message") + @ApiModelProperty(required = true, value = "ErrorResponse message.") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @JsonProperty(value = "description") + @ApiModelProperty(value = "A detail description about the error message.") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @JsonProperty(value = "moreInfo") + @ApiModelProperty(value = "Preferably an url with more details about the error.") + public String getMoreInfo() { + return moreInfo; + } + + public void setMoreInfo(String moreInfo) { + this.moreInfo = moreInfo; + } + + public void addErrorListItem(ErrorListItem item) { + this.errorItems.add(item); + } + + /** + * If there are more than one error list them out. \nFor example, list out validation errors by each field. + */ + @JsonProperty(value = "errorItems") + @ApiModelProperty(value = "If there are more than one error list them out. \n" + + "For example, list out validation errors by each field.") + public List getErrorItems() { + return errorItems; + } + + public void setErrorItems(List error) { + this.errorItems = error; + } + + @Override + public String toString() { +// StringBuilder sb = new StringBuilder(); +// sb.append("{"); +// boolean cont = false; +// if (code != null) { +// cont = true; +// sb.append(" \"code\": ").append(code); +// } +// if (message != null) { +// if (cont) { +// sb.append(","); +// } +// cont = true; +// sb.append(" \"message\": \"").append(message).append("\""); +// } +// if (description != null) { +// if (cont) { +// sb.append(","); +// } +// cont = true; +// sb.append(" \"description\": ").append(description).append("\""); +// } +// if (moreInfo != null) { +// if (cont) { +// sb.append(","); +// } +// cont = true; +// sb.append(" \"moreInfo\": \"").append(moreInfo).append("\""); +// } +// if (error != null && error.size() > 0) { +// if (cont) { +// sb.append(","); +// } +// sb.append(" \"errorItems\": ").append(error); +// } +// sb.append("}"); +// return sb.toString(); + return null; + } + + public static class ErrorResponseBuilder { + + private Long code = null; + private String message = null; + private String description = null; + private String moreInfo = null; + private List error; + + + public ErrorResponseBuilder() { + this.error = new ArrayList<>(); + } + + public ErrorResponseBuilder setCode(long code) { + this.code = code; + return this; + } + + public ErrorResponseBuilder setMessage(String message) { + this.message = message; + return this; + } + + public ErrorResponseBuilder setDescription(String description) { + this.description = description; + return this; + } + + public ErrorResponseBuilder setMoreInfo(String moreInfo) { + this.moreInfo = moreInfo; + return this; + } + + public ErrorResponseBuilder addErrorItem(String code, String msg) { + ErrorListItem item = new ErrorListItem(); + item.setCode(code); + item.setMessage(msg); + this.error.add(item); + return this; + } + + public ErrorResponse build() { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setCode(code); + errorResponse.setMessage(message); + errorResponse.setErrorItems(error); + errorResponse.setDescription(description); + errorResponse.setMoreInfo(moreInfo); + return errorResponse; + } + } + +} + + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java deleted file mode 100644 index d97d5ab4b1..0000000000 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateImpl.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.Certificate; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.common.MDMAPIException; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.exception.Message; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; -import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; -import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; - -public class CertificateImpl implements Certificate { - - private static Log log = LogFactory.getLog(CertificateImpl.class); - - /** - * Save a list of certificates and relevant information in the database. - * - * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as - * a pem and a serial number. - * @return Status of the data persist operation. - */ - @POST - public Response saveCertificate(@HeaderParam("Accept") String acceptHeader, - EnrollmentCertificate[] enrollmentCertificates) { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - CertificateManagementService certificateService; - List certificates = new ArrayList<>(); - org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; - certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - try { - for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { - certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); - certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); - certificate.setSerial(enrollmentCertificate.getSerial()); - certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); - certificates.add(certificate); - } - certificateService.saveCertificate(certificates); - return Response.status(Response.Status.CREATED).entity("Added successfully."). - type(responseMediaType).build(); - } catch (KeystoreException e) { - String msg = "Error occurred while converting PEM file to X509Certificate."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } - - /** - * Get a certificate when the serial number is given. - * - * @param serialNumber serial of the certificate needed. - * @return certificate response. - */ - @GET - @Path("{serialNumber}") - public Response getCertificate(@HeaderParam("Accept") String acceptHeader, - @PathParam("serialNumber") String serialNumber) { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - Message message = new Message(); - - if (serialNumber == null || serialNumber.isEmpty()) { - message.setErrorMessage("Invalid serial number"); - message.setDiscription("Serial number is missing or invalid."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - List certificateResponse; - try { - certificateResponse = certificateService.searchCertificates(serialNumber); - return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build(); - } catch (CertificateManagementDAOException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } - - /** - * Get all certificates in a paginated manner. - * - * @param startIndex index of the first record to be fetched - * @param length number of records to be fetched starting from the start index. - * @return paginated result of certificate. - * @throws MDMAPIException - */ - @GET - @Path("paginate") - public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, - @QueryParam("start") int startIndex, - @QueryParam("length") int length) - throws MDMAPIException { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - Message message = new Message(); - - if (startIndex < 0) { - message.setErrorMessage("Invalid start index."); - message.setDiscription("Start index cannot be less that 0."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } else if (length <= 0) { - message.setErrorMessage("Invalid length value."); - message.setDiscription("Length should be a positive integer."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - PaginationRequest paginationRequest = new PaginationRequest(startIndex, length); - try { - PaginationResult certificates = certificateService.getAllCertificates(paginationRequest); - return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build(); - } catch (CertificateManagementDAOException e) { - String msg = "Error occurred while fetching all certificates."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } - - /** - * Get all certificates - * - * @return certificate details in an array. - * @throws MDMAPIException - */ - @GET - public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader) - throws MDMAPIException { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - try { - List certificates = certificateService.getCertificates(); - return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build(); - } catch (CertificateManagementDAOException e) { - String msg = "Error occurred while fetching all certificates."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } - - @DELETE - @Path("{serialNumber}") - public Response removeCertificate(@HeaderParam("Accept") String acceptHeader, - @PathParam("serialNumber") String serialNumber) throws MDMAPIException { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - Message message = new Message(); - - if (serialNumber == null || serialNumber.isEmpty()) { - message.setErrorMessage("Invalid serial number"); - message.setDiscription("Serial number is missing or invalid."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - boolean deleted; - try { - deleted = certificateService.removeCertificate(serialNumber); - if(deleted){ - return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build(); - } else { - return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build(); - } - } catch (CertificateManagementDAOException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } -} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java new file mode 100644 index 0000000000..ad3b1e8108 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java @@ -0,0 +1,134 @@ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.CertificateManagementAdminService; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.UnexpectedServerErrorException; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +@Path("/certificates") +public class CertificateManagementAdminServiceImpl implements CertificateManagementAdminService { + + private static Log log = LogFactory.getLog(CertificateManagementAdminServiceImpl.class); + + /** + * Save a list of certificates and relevant information in the database. + * + * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as + * a pem and a serial number. + * @return Status of the data persist operation. + */ + @POST + public Response addCertificate(EnrollmentCertificate[] enrollmentCertificates) { + CertificateManagementService certificateService; + List certificates = new ArrayList<>(); + org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; + certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + try { + for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { + certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); + certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + certificate.setSerial(enrollmentCertificate.getSerial()); + certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); + certificates.add(certificate); + } + certificateService.saveCertificate(certificates); + return Response.status(Response.Status.CREATED).entity("Added successfully.").build(); + } catch (KeystoreException e) { + String msg = "Error occurred while converting PEM file to X509Certificate."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + /** + * Get a certificate when the serial number is given. + * + * @param serialNumber serial of the certificate needed. + * @return certificate response. + */ + @GET + @Path("/{serialNumber}") + public Response getCertificate( + @PathParam("serialNumber") String serialNumber, + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + RequestValidationUtil.validateSerialNumber(serialNumber); + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + List certificateResponse; + try { + certificateResponse = certificateService.searchCertificates(serialNumber); + return Response.status(Response.Status.OK).entity(certificateResponse).build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + /** + * Get all certificates in a paginated manner. + * + * @param offset index of the first record to be fetched + * @param limit number of records to be fetched starting from the start index. + * @return paginated result of certificate. + */ + @GET + public Response getAllCertificates( + @QueryParam("offset") int offset, + @QueryParam("limit") int limit, + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + RequestValidationUtil.validatePaginationInfo(offset, limit); + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + PaginationRequest paginationRequest = new PaginationRequest(offset, limit); + try { + PaginationResult result = certificateService.getAllCertificates(paginationRequest); + CertificateList certificates = new CertificateList(); + certificates.setCount(result.getRecordsTotal()); + certificates.setList((List) result.getData()); + return Response.status(Response.Status.OK).entity(certificates).build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while fetching all certificates."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + @DELETE + @Path("/{serialNumber}") + public Response removeCertificate(@PathParam("serialNumber") String serialNumber) { + RequestValidationUtil.validateSerialNumber(serialNumber); + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + try { + certificateService.removeCertificate(serialNumber); + return Response.status(Response.Status.OK).entity("Certificate that carries the serial number '" + + serialNumber + " has been removed").build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java index 40026011f1..4419bcf79a 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java @@ -41,7 +41,7 @@ public class DeviceMgtAPIUtils { ctx.getOSGiService(CertificateManagementService.class, null); if (certificateManagementService == null) { - String msg = "CertificateImpl Management service not initialized."; + String msg = "CertificateManagementAdminServiceImpl Management service not initialized."; log.error(msg); throw new IllegalStateException(msg); } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/RequestValidationUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/RequestValidationUtil.java new file mode 100644 index 0000000000..233112c342 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/RequestValidationUtil.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util; + +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.InputValidationException; + +public class RequestValidationUtil { + + public static void validateSerialNumber(String serialNumber) { + if (serialNumber == null || serialNumber.isEmpty()) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + "Serial number cannot be null or empty").build()); + } + } + + public static void validatePaginationInfo(int offset, int limit) { + if (offset < 0) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + "Offset number cannot be negative").build()); + } + if (limit < 0) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + "Limit number cannot be negative").build()); + } + } + + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml index 955b726ad4..774a21e13a 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml @@ -38,7 +38,7 @@ emm_admin - + Save certificate in the database /device-mgt/admin/certificate/save @@ -63,5 +63,5 @@ /certificates/* DELETE - + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml index fc3c9ef240..a955e2a17d 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -59,7 +59,7 @@ - + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 7bb3dd412e..42eb1188dd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -55,6 +55,7 @@ + From f5aa2c5eb149d50ec2e5169f90cc126c07976399 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 16:17:05 +0530 Subject: [PATCH 03/29] Improving swagger annotations added to certificate management service --- .../mgt/cert/jaxrs/api/CertificateManagementAdminService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java index 3f9cf9c475..1b8498638e 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java @@ -62,7 +62,8 @@ public interface CertificateManagementAdminService { description = "The Source URL of the document.")}), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 415, message = "Unsupported media type. \n The entity of the request was in a not supported format."), From d65174d02606bc34f338f27ff6922dc66cc791e1 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 16:27:35 +0530 Subject: [PATCH 04/29] making the certificate management war adhere the REST API guidelines --- .../pom.xml | 4 +- .../CertificateManagementAdminService.java | 2 +- .../cert/jaxrs/api/util/ApiOriginFilter.java | 44 +++++++++++++++++++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 15 ++----- .../src/main/webapp/WEB-INF/web.xml | 15 +++++++ .../pom.xml | 2 +- .../src/main/resources/p2.inf | 2 +- 7 files changed, 68 insertions(+), 16 deletions(-) create mode 100644 components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ApiOriginFilter.java diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index 95ea9ce63a..bef88ced39 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -48,7 +48,7 @@ maven-war-plugin WEB-INF/lib/*cxf*.jar - admin-certificate + api#certificate-mgt#v1.0 @@ -75,7 +75,7 @@ - + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java index 1b8498638e..c7cbc13b52 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java @@ -13,7 +13,7 @@ import javax.ws.rs.core.Response; @Api(value = "Certificate Management", description = "This API carries all certificate management related operations " + "such as get all the available devices, etc.") -@Path("/certificates") +@Path("/admin/certificates") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public interface CertificateManagementAdminService { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ApiOriginFilter.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ApiOriginFilter.java new file mode 100644 index 0000000000..3a192bdf36 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/ApiOriginFilter.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class ApiOriginFilter implements Filter { + + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() { + //do nothing + } + + public void init(FilterConfig filterConfig) throws ServletException { + //do nothing + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml index a955e2a17d..a22b8681cd 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -26,6 +26,7 @@ + @@ -34,15 +35,6 @@ - - - - - - - - - @@ -51,8 +43,9 @@ - - + + + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/web.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/web.xml index 0b5d5b28bf..0efd4bc25a 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/web.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/web.xml @@ -25,6 +25,11 @@ org.apache.cxf.transport.servlet.CXFServlet + + swagger.security.filter + ApiAuthorizationFilterImpl + + 1 CXFServlet @@ -63,4 +68,14 @@ + + ApiOriginFilter + org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.ApiOriginFilter + + + ApiOriginFilter + /* + + + diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index 99c4ebe609..4726e13d2d 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -59,7 +59,7 @@ ${project.build.directory}/maven-shared-archive-resources/webapps - admin-certificate.war + api#certificate-mgt#v1.0.war diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf index f88e763ba3..b9e7e512bc 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf @@ -1,2 +1,2 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/admin-certificate.war,target:${installFolder}/../../deployment/server/webapps/admin-certificate.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/api#certificate-mgt#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#certificate-mgt#v1.0.war,overwrite:true);\ \ No newline at end of file From 9c7525220990767b7014ef96f3537669f3eea5e4 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 16:46:43 +0530 Subject: [PATCH 05/29] Updating permission.xml of certificate management admin service webapp with updated resource paths --- .../src/main/webapp/META-INF/permissions.xml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml index 774a21e13a..480483adb4 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml @@ -33,33 +33,33 @@ get certificate in the database /device-mgt/emm-admin/certificate/GetSignCSR - /certificates/signcsr + /certificates/sign-csr POST emm_admin - Save certificate in the database - /device-mgt/admin/certificate/save + Save certificate + /device-mgt/admin/certificate/Save /certificates POST - get certificate in the database + Get certificate /device-mgt/admin/certificate/Get /certificates/* GET - get certificate in the database + Get all certificates /device-mgt/admin/certificate/GetAll /certificates GET - get certificate in the database - /device-mgt/admin/certificate/Get + Remove certificate + /device-mgt/admin/certificate/Remove /certificates/* DELETE From d63e5e876b1bf8896336dfa80312c35156275766 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 31 May 2016 17:09:34 +0530 Subject: [PATCH 06/29] added password validation error msg --- .../util/CredentialManagementResponseBuilder.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java index 2edbb20ebb..d52bdec3d9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java @@ -36,6 +36,7 @@ public class CredentialManagementResponseBuilder { private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class); private static String PASSWORD_VALIDATION_REGEX_TAG = "PasswordJavaRegEx"; + private static String PASSWORD_VALIDATION_ERROR_MSG_TAG = "PasswordJavaRegExViolationErrorMsg"; /** * Builds the response to change the password of a user @@ -55,8 +56,9 @@ public class CredentialManagementResponseBuilder { .build(); } if (!validateCredential(credentials.getNewPassword())) { - return Response.status(Response.Status.BAD_REQUEST).entity("Password does not match with required format.") - .build(); + String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() + .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); + return Response.status(Response.Status.BAD_REQUEST).entity(errorMsg).build(); } userStoreManager.updateCredential(username, credentials.getNewPassword(), credentials.getOldPassword()); @@ -91,8 +93,9 @@ public class CredentialManagementResponseBuilder { .build(); } if (!validateCredential(credentials.getNewPassword())) { - return Response.status(Response.Status.BAD_REQUEST).entity("Password does not match with required format.") - .build(); + String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() + .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); + return Response.status(Response.Status.BAD_REQUEST).entity(errorMsg).build(); } userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + From bfe215deacea43925b6f131f017fdcba7308a416 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 31 May 2016 17:13:11 +0530 Subject: [PATCH 07/29] Adding changes and bug fixes to UserMgtService --- .../device/mgt/jaxrs/beans/UserList.java | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java new file mode 100644 index 0000000000..d98733ef89 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.ArrayList; +import java.util.List; + +@ApiModel(value = "List of users", description = "This contains a set of users that matches a given " + + "criteria as a collection") +public class UserList { + + private int count; + private String next; + private String previous; + + private List users = new ArrayList<>(); + + /** + * Number of Devices returned. + */ + @ApiModelProperty(value = "Number of users returned.") + @JsonProperty("count") + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + + /** + * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. + */ + @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + + "Empty if no more resources are to be returned.") + @JsonProperty("next") + public String getNext() { + return next; + } + + public void setNext(String next) { + this.next = next; + } + + /** + * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. + */ + @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + + "Empty if current subset is the first subset returned.") + @JsonProperty("previous") + public String getPrevious() { + return previous; + } + + public void setPrevious(String previous) { + this.previous = previous; + } + + /** + **/ + @ApiModelProperty(value = "List of devices returned") + @JsonProperty("users") + public List getList() { + return users; + } + + public void setList(List users) { + this.users = users; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(count).append(",\n"); + sb.append(" next: ").append(next).append(",\n"); + sb.append(" previous: ").append(previous).append(",\n"); + sb.append(" users: [").append(users).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + + +} From ddfd678b2a00624db6a2cc03b1b8ae4c1381836f Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 31 May 2016 17:26:20 +0530 Subject: [PATCH 08/29] Adding user management API bug fixes and improvements --- .../service/api/UserManagementService.java | 7 ++-- .../impl/UserManagementServiceImpl.java | 34 ++++++++++++++----- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index a2c3362575..524e3cac01 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -22,6 +22,7 @@ import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserList; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import javax.ws.rs.*; @@ -279,14 +280,14 @@ public interface UserManagementService { value = "Get user list", notes = "If you wish to get the details of all the users registered with EMM, you can do so " + "using the REST API", - response = UserWrapper.class, + response = UserList.class, responseContainer = "List", tags = "User Management") @ApiResponses(value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the requested role.", - response = UserWrapper.class, + response = UserList.class, responseContainer = "List", responseHeaders = { @ResponseHeader( @@ -303,7 +304,7 @@ public interface UserManagementService { }), @ApiResponse( code = 304, - message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), + message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."), @ApiResponse( code = 406, message = "Not Acceptable.\n The requested media type is not supported"), diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 1a2bb05f2d..9975fbb29b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserList; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; @@ -142,10 +143,10 @@ public class UserManagementServiceImpl implements UserManagementService { Properties props = new Properties(); props.setProperty("username", usernameBits[1]); props.setProperty("domain-name", tenantDomain); - props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + props.setProperty("first-name", getClaimValue(usernameBits[1], Constants.USER_CLAIM_FIRST_NAME)); props.setProperty("password", password); - String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); + String recipient = getClaimValue(usernameBits[1], Constants.USER_CLAIM_EMAIL_ADDRESS); EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); @@ -329,10 +330,15 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("Getting the list of users with all user-related information"); } - List userList; + List userList, offsetList; + String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter); + int appliedLimit = (limit <= 0) ? -1 : (limit + offset); + try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - String[] users = userStoreManager.listUsers("*", -1); + + //As the listUsers function accepts limit only to accommodate offset we are passing offset + limit + String[] users = userStoreManager.listUsers(appliedFilter, appliedLimit); userList = new ArrayList<>(users.length); UserWrapper user; for (String username : users) { @@ -343,12 +349,24 @@ public class UserManagementServiceImpl implements UserManagementService { user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); userList.add(user); } - if (userList.size() <= 0) { - return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build(); + + if (offset <= userList.size()) { + offsetList = userList.subList(offset, userList.size()); + } else { + offsetList = new ArrayList<>(); } - return Response.status(Response.Status.OK).entity(userList).build(); + + if (offsetList.size() <= 0) { + return Response.status(Response.Status.NOT_FOUND).entity("No users available for retrieval").build(); + } + + UserList result = new UserList(); + result.setList(offsetList); + result.setCount(offsetList.size()); + + return Response.status(Response.Status.OK).entity(result).build(); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while retrieving the list of users"; + String msg = "ErrorResponse occurred while retrieving the list of users."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } From 3e21c6d50dd8b1ec74b059e131485cfec81c28cf Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 17:49:26 +0530 Subject: [PATCH 09/29] Improving ceritificate management webapp impl --- .../CertificateManagementAdminService.java | 3 +- ...CertificateManagementAdminServiceImpl.java | 2 +- .../admin/GroupManagementAdminService.java | 130 +++++++++--------- .../GroupManagementAdminServiceImpl.java | 52 +++---- 4 files changed, 94 insertions(+), 93 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java index c7cbc13b52..6988f31712 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java @@ -227,7 +227,8 @@ public interface CertificateManagementAdminService { produces = MediaType.APPLICATION_JSON, httpMethod = "DELETE", value = "Delete an SSL certificate", - notes = "Delete an SSL certificate that's on the client end") + notes = "Delete an SSL certificate that's on the client end", + tags = "Certificate Management") @ApiResponses(value = { @ApiResponse( code = 200, diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java index ad3b1e8108..ebe9953f8b 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java @@ -22,7 +22,7 @@ import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; -@Path("/certificates") +@Path("/admin/certificates") public class CertificateManagementAdminServiceImpl implements CertificateManagementAdminService { private static Log log = LogFactory.getLog(CertificateManagementAdminServiceImpl.class); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java index 1143447c39..4d5915684b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -27,73 +27,73 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Date; -@Path("/admin/groups") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " + - "'internal' components to log in as an admin user and do a selected number of operations. " + - "Further, this is strictly restricted to admin users only ") +//@Path("/admin/groups") +//@Produces(MediaType.APPLICATION_JSON) +//@Consumes(MediaType.APPLICATION_JSON) +//@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " + +// "'internal' components to log in as an admin user and do a selected number of operations. " + +// "Further, this is strictly restricted to admin users only ") public interface GroupManagementAdminService { - @GET - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Get groups by the name.", - notes = "Get devices the name of device and tenant.", - response = DeviceGroupWrapper.class, - responseContainer = "List", - tags = "Group Management Administrative Service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", - response = DeviceGroupWrapper.class, - responseContainer = "List", - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource has been modified the last time.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 304, - message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported"), - @ApiResponse( - code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.") - }) - @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"}) - Response getGroupsOfUser( - @ApiParam( - name = "username", - value = "Username of the user.", - required = true) - @QueryParam("username") String username, - @ApiParam( - name = "If-Modified-Since", - value = "Timestamp of the last modified date", - required = false) - @HeaderParam("If-Modified-Since") String timestamp, - @ApiParam( - name = "offset", - value = "Starting point within the complete list of items qualified.", - required = false) - @QueryParam("offset") int offset, - @ApiParam( - name = "limit", - value = "Maximum size of resource array to return.", - required = false) - @QueryParam("limit") int limit); - +// @GET +// @ApiOperation( +// produces = MediaType.APPLICATION_JSON, +// httpMethod = "GET", +// value = "Get groups by the name.", +// notes = "Get devices the name of device and tenant.", +// response = DeviceGroupWrapper.class, +// responseContainer = "List", +// tags = "Group Management Administrative Service") +// @ApiResponses(value = { +// @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", +// response = DeviceGroupWrapper.class, +// responseContainer = "List", +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "ETag", +// description = "Entity Tag of the response resource.\n" + +// "Used by caches, or in conditional requests."), +// @ResponseHeader( +// name = "Last-Modified", +// description = "Date and time the resource has been modified the last time.\n" + +// "Used by caches, or in conditional requests."), +// }), +// @ApiResponse( +// code = 304, +// message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), +// @ApiResponse( +// code = 406, +// message = "Not Acceptable.\n The requested media type is not supported"), +// @ApiResponse( +// code = 500, +// message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.") +// }) +// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"}) +// Response getGroupsOfUser( +// @ApiParam( +// name = "username", +// value = "Username of the user.", +// required = true) +// @QueryParam("username") String username, +// @ApiParam( +// name = "If-Modified-Since", +// value = "Timestamp of the last modified date", +// required = false) +// @HeaderParam("If-Modified-Since") String timestamp, +// @ApiParam( +// name = "offset", +// value = "Starting point within the complete list of items qualified.", +// required = false) +// @QueryParam("offset") int offset, +// @ApiParam( +// name = "limit", +// value = "Maximum size of resource array to return.", +// required = false) +// @QueryParam("limit") int limit); +// } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 7fe91394f4..7573df0f5e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -31,32 +31,32 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Date; -@Path("/admin/groups") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) +//@Path("/admin/groups") +//@Produces(MediaType.APPLICATION_JSON) +//@Consumes(MediaType.APPLICATION_JSON) public class GroupManagementAdminServiceImpl implements GroupManagementAdminService { - - private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); - - @Override - public Response getGroupsOfUser( - @QueryParam("username") String username, - @HeaderParam("If-Modified-Since") String timestamp, - @QueryParam("offset") int offset, - @QueryParam("limit") int limit) { - try { - PaginationResult result = - DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); - if (result != null && result.getRecordsTotal() > 0) { - return Response.status(Response.Status.OK).entity(result).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } +// +// private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); +// +// @Override +// public Response getGroupsOfUser( +// @QueryParam("username") String username, +// @HeaderParam("If-Modified-Since") String timestamp, +// @QueryParam("offset") int offset, +// @QueryParam("limit") int limit) { +// try { +// PaginationResult result = +// DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); +// if (result != null && result.getRecordsTotal() > 0) { +// return Response.status(Response.Status.OK).entity(result).build(); +// } else { +// return Response.status(Response.Status.NOT_FOUND).build(); +// } +// } catch (GroupManagementException e) { +// String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'"; +// log.error(msg, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); +// } +// } } From 374d50988172157dc71d73e0bc20cb631688fe8e Mon Sep 17 00:00:00 2001 From: dilanua Date: Tue, 31 May 2016 18:34:00 +0530 Subject: [PATCH 10/29] Updating DeviceManagementAdminServiceImpl --- .../DeviceManagementAdminServiceImpl.java | 4 +- .../mgt/jaxrs/util/DeviceMgtAPIUtils.java | 18 +++++++-- .../carbon/device/mgt/core/dao/DeviceDAO.java | 2 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 38 +++++++++++++++---- .../DeviceManagementProviderService.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 32 +++++++++------- 6 files changed, 69 insertions(+), 27 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 7c6d779591..54140ccada 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -59,8 +59,10 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe } PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain)); - List devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name); + List devices = DeviceMgtAPIUtils.getDeviceManagementService(). + getDevicesByNameAndType(name, type, offset, limit); if (devices == null) { return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" + name + "', is currently enrolled in the system").build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index dfb8bc19df..ccafdd0e90 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -20,14 +20,13 @@ package org.wso2.carbon.device.mgt.jaxrs.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; @@ -237,4 +236,17 @@ public class DeviceMgtAPIUtils { return gadgetDataService; } + public static int getTenantId(String tenantDomain) throws DeviceManagementException { + RealmService realmService = + (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null); + if (realmService == null) { + throw new IllegalStateException(""); + } + try { + return realmService.getTenantManager().getTenantId(tenantDomain); + } catch (UserStoreException e) { + throw new DeviceManagementException(""); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 462f403693..a65f40db65 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -259,7 +259,7 @@ public interface DeviceDAO { * @return returns list of devices. * @throws DeviceManagementDAOException */ - List getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; + List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) throws DeviceManagementDAOException; /** * This method is used to retrieve devices of a given device name as a paginated result. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 868d070d24..0bc4d83f64 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -628,7 +628,18 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { * @throws DeviceManagementDAOException */ @Override - public List getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException { + public List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) + throws DeviceManagementDAOException { + + String filteringString = ""; + if (deviceName != null && !deviceName.isEmpty()) { + filteringString = filteringString + " AND d.NAME LIKE ?"; + } + + if (type != null && !type.isEmpty()) { + filteringString = filteringString + " AND t.NAME = ?"; + } + Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); @@ -638,13 +649,26 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID LIMIT ?, ?"; + stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceName + "%"); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); + stmt.setInt(1, tenantId); + + int i = 1; + + if (deviceName != null && !deviceName.isEmpty()) { + stmt.setString(++i, deviceName + "%"); + } + + if (type != null && !type.isEmpty()) { + stmt.setString(++i, type); + } + + stmt.setInt(++i, offset); + stmt.setInt(++i, limit); + rs = stmt.executeQuery(); while (rs.next()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index b07e1ebf51..8396e694ff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -139,7 +139,7 @@ public interface DeviceManagementProviderService { * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * device list */ - List getDevicesByName(String deviceName) throws DeviceManagementException; + List getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException; /** * This method is used to retrieve list of devices that matches with the given device name with paging information. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 5f3cad82f2..75c3cf9971 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -31,11 +31,7 @@ import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; -import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; -import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; +import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; @@ -50,13 +46,7 @@ import org.wso2.carbon.email.sender.core.TypedValue; import org.wso2.carbon.user.api.UserStoreException; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -1062,12 +1052,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List getDevicesByName(String deviceName) throws DeviceManagementException { + public List getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException { List devices = new ArrayList<>(); List allDevices; try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevicesByName(deviceName, this.getTenantId()); + allDevices = deviceDAO.getDevicesByNameAndType(deviceName, type, this.getTenantId(), offset, limit); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '" + deviceName + "'", e); @@ -1240,7 +1230,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return CarbonContext.getThreadLocalCarbonContext().getTenantId(); } +// private int getTenantId(String tenantDomain) throws DeviceManagementException { +// RealmService realmService = +// (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null); +// if (realmService == null) { +// throw new IllegalStateException(""); +// } +// try { +// return realmService.getTenantManager().getTenantId(tenantDomain); +// } catch (UserStoreException e) { +// throw new DeviceManagementException(""); +// } +// } + private DeviceManager getDeviceManager(String deviceType) { + DeviceManagementService deviceManagementService = pluginRepository.getDeviceManagementService(deviceType, this.getTenantId()); if (deviceManagementService == null) { From 00a16ea2bc1afdf39cbcdce272d9c81e11f0f852 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 18:36:00 +0530 Subject: [PATCH 11/29] Improving Role management API implementation --- .../device/mgt/jaxrs/beans/RoleList.java | 56 +++++++++++++++++ .../service/api/RoleManagementService.java | 37 ++++++----- .../api/admin/UserManagementAdminService.java | 2 +- .../impl/RoleManagementServiceImpl.java | 63 ++++++++++++------- .../admin/UserManagementAdminServiceImpl.java | 2 +- 5 files changed, 122 insertions(+), 38 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java new file mode 100644 index 0000000000..4cb08fa36c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "Role List") +public class RoleList extends BasePaginatedResult { + + private List roles; + + @ApiModelProperty(value = "List of roles returned") + @JsonProperty("roles") + public List getList() { + return roles; + } + + public void setList(List roles) { + this.roles = roles; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); + sb.append(" roles: [").append(roles).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java index 2db6620784..1785d92b82 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java @@ -22,6 +22,8 @@ import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; import org.wso2.carbon.user.mgt.common.UIPermissionNode; @@ -43,18 +45,15 @@ public interface RoleManagementService { produces = MediaType.APPLICATION_JSON, httpMethod = "GET", value = "Get the list of roles.", - responseContainer = "List", notes = "If you wish to get the details of all the roles in EMM, you can do so using this REST API. All " + "internal roles, roles created for Service-providers and application related roles are omitted.", - response = String.class, tags = "Role Management") @ApiResponses( value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the requested list of roles.", - response = String.class, - responseContainer = "List", + response = RoleList.class, responseHeaders = { @ResponseHeader( name = "Content-Type", @@ -76,7 +75,8 @@ public interface RoleManagementService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.") + message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.", + response = ErrorResponse.class) }) @Permission(scope = "roles-view", permissions = { "/permission/admin/device-mgt/admin/roles/list", @@ -155,7 +155,8 @@ public interface RoleManagementService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.") + message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.", + response = ErrorResponse.class) }) @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) Response getPermissionsOfRole( @@ -209,7 +210,8 @@ public interface RoleManagementService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the requested role.") + message = "Internal Server ErrorResponse. \n Server error occurred while fetching the requested role.", + response = ErrorResponse.class) }) @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) Response getRole( @@ -260,14 +262,16 @@ public interface RoleManagementService { description = "The Source URL of the document.")}), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 415, message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while adding a new role.") + "Server error occurred while adding a new role.", + response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"}) Response addRole( @@ -307,7 +311,8 @@ public interface RoleManagementService { "Used by caches, or in conditional requests.")}), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Resource to be deleted does not exist."), @@ -317,7 +322,8 @@ public interface RoleManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while updating the role.") + "Server error occurred while updating the role.", + response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) Response updateRole( @@ -349,7 +355,8 @@ public interface RoleManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while removing the role.") + "Server error occurred while removing the role.", + response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"}) Response deleteRole( @@ -395,7 +402,8 @@ public interface RoleManagementService { "Used by caches, or in conditional requests.")}), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Resource to be deleted does not exist."), @@ -405,7 +413,8 @@ public interface RoleManagementService { @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + - "Server error occurred while updating the user list of the role.") + "Server error occurred while updating the user list of the role.", + response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) Response updateUsersOfRole( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java index baec3eff63..d44bd57f77 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java @@ -62,7 +62,7 @@ public interface UserManagementAdminService { "Server error occurred while updating credentials of the user.") }) @Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) - Response resetPassword( + Response resetUserPassword( @ApiParam( name = "username", value = "Username of the user.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index 2007821939..8979f59641 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -22,7 +22,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; @@ -54,17 +57,22 @@ public class RoleManagementServiceImpl implements RoleManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { List filteredRoles; + RoleList targetRoles; try { filteredRoles = getRolesFromUserStore(); - if (filteredRoles == null || filteredRoles.size() == 0) { + if (filteredRoles == null) { return Response.status(Response.Status.NOT_FOUND).entity("No roles found.").build(); } + targetRoles = new RoleList(); + targetRoles.setCount(filteredRoles.size()); + targetRoles.setList(filteredRoles); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while retrieving roles from the underlying user stores"; + String msg = "Error occurred while retrieving roles from the underlying user stores"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - return Response.status(Response.Status.OK).entity(filteredRoles).build(); + return Response.status(Response.Status.OK).entity(targetRoles).build(); } @GET @@ -88,14 +96,16 @@ public class RoleManagementServiceImpl implements RoleManagementService { } return Response.status(Response.Status.OK).entity(rolePermissions).build(); } catch (UserAdminException e) { - String msg = "ErrorResponse occurred while retrieving the permissions of role '" + roleName + "'"; + String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while retrieving the underlying user realm attached to the " + + String msg = "Error occurred while retrieving the underlying user realm attached to the " + "current logged in user"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -150,9 +160,10 @@ public class RoleManagementServiceImpl implements RoleManagementService { roleWrapper.setPermissions(permList.toArray(permListAr)); } } catch (UserStoreException | UserAdminException e) { - String msg = "ErrorResponse occurred while retrieving the user role '" + roleName + "'"; + String msg = "Error occurred while retrieving the user role '" + roleName + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } return Response.status(Response.Status.OK).entity(roleWrapper).build(); } @@ -186,11 +197,13 @@ public class RoleManagementServiceImpl implements RoleManagementService { } userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while adding role '" + roleWrapper.getRoleName() + "'"; + String msg = "Error occurred while adding role '" + roleWrapper.getRoleName() + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - return Response.status(Response.Status.OK).build(); + return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " + + "successfully been added").build(); } @PUT @@ -228,11 +241,13 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while updating role '" + roleName + "'"; + String msg = "Error occurred while updating role '" + roleName + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - return Response.status(Response.Status.OK).build(); + return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " + + "successfully been updated").build(); } @DELETE @@ -249,11 +264,13 @@ public class RoleManagementServiceImpl implements RoleManagementService { // Delete all authorizations for the current role before deleting authorizationManager.clearRoleAuthorization(roleName); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while deleting the role '" + roleName + "'"; + String msg = "Error occurred while deleting the role '" + roleName + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - return Response.status(Response.Status.OK).build(); + return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " + + "successfully been deleted").build(); } @POST @@ -275,11 +292,13 @@ public class RoleManagementServiceImpl implements RoleManagementService { userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while updating the users of the role '" + roleName + "'"; + String msg = "Error occurred while updating the users of the role '" + roleName + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - return Response.status(Response.Status.OK).build(); + return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " + + "successfully been updated with the user list").build(); } private List getRolesFromUserStore() throws UserStoreException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index 1613c49b87..8067c74498 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -34,7 +34,7 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic @POST @Path("/{username}/credentials") @Override - public Response resetPassword(@PathParam("username") String user, PasswordResetWrapper credentials) { + public Response resetUserPassword(@PathParam("username") String user, PasswordResetWrapper credentials) { return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials); } From c9a2dc43999879796ec9ae8a311127f5911fce25 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Tue, 31 May 2016 19:05:37 +0530 Subject: [PATCH 12/29] Improving user management API implementation --- .../device/mgt/jaxrs/beans/UserList.java | 56 ++----------------- .../service/api/UserManagementService.java | 2 +- .../impl/UserManagementServiceImpl.java | 40 ++++++++----- .../impl/util/RequestValidationUtil.java | 10 ++++ .../CredentialManagementResponseBuilder.java | 47 ++++++++++------ 5 files changed, 69 insertions(+), 86 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java index d98733ef89..a205f0a3ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserList.java @@ -27,58 +27,10 @@ import java.util.List; @ApiModel(value = "List of users", description = "This contains a set of users that matches a given " + "criteria as a collection") -public class UserList { - - private int count; - private String next; - private String previous; +public class UserList extends BasePaginatedResult { private List users = new ArrayList<>(); - /** - * Number of Devices returned. - */ - @ApiModelProperty(value = "Number of users returned.") - @JsonProperty("count") - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } - - - /** - * Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned. - */ - @ApiModelProperty(value = "Link to the next subset of resources qualified. \n " + - "Empty if no more resources are to be returned.") - @JsonProperty("next") - public String getNext() { - return next; - } - - public void setNext(String next) { - this.next = next; - } - - /** - * Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned. - */ - @ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" + - "Empty if current subset is the first subset returned.") - @JsonProperty("previous") - public String getPrevious() { - return previous; - } - - public void setPrevious(String previous) { - this.previous = previous; - } - - /** - **/ @ApiModelProperty(value = "List of devices returned") @JsonProperty("users") public List getList() { @@ -94,9 +46,9 @@ public class UserList { StringBuilder sb = new StringBuilder(); sb.append("{\n"); - sb.append(" count: ").append(count).append(",\n"); - sb.append(" next: ").append(next).append(",\n"); - sb.append(" previous: ").append(previous).append(",\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); sb.append(" users: [").append(users).append("\n"); sb.append("]}\n"); return sb.toString(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index 524e3cac01..f3778efcbc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -317,7 +317,7 @@ public interface UserManagementService { @ApiParam( name = "filter", value = "Username of the user details to be fetched.", - required = true) + required = false) @QueryParam("filter") String filter, @ApiParam( name = "If-Modified-Since", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 9975fbb29b..79d51374b3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -26,10 +26,12 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.UserList; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; @@ -86,11 +88,13 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Exception in trying to add user '" + userWrapper.getUsername() + "' to the user store"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } catch (DeviceManagementException e) { String msg = "ErrorResponse occurred while inviting user to enroll the device"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -188,7 +192,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "ErrorResponse occurred while retrieving information of the user '" + username + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -246,7 +251,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException | UnsupportedEncodingException e) { String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -294,7 +300,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -318,7 +325,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Exception in trying to retrieve roles for user by username: " + username; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -356,9 +364,9 @@ public class UserManagementServiceImpl implements UserManagementService { offsetList = new ArrayList<>(); } - if (offsetList.size() <= 0) { - return Response.status(Response.Status.NOT_FOUND).entity("No users available for retrieval").build(); - } +// if (offsetList.size() <= 0) { +// return Response.status(Response.Status.NOT_FOUND).entity("No users available for retrieval").build(); +// } UserList result = new UserList(); result.setList(offsetList); @@ -368,7 +376,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "ErrorResponse occurred while retrieving the list of users."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -394,14 +403,15 @@ public class UserManagementServiceImpl implements UserManagementService { user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); userList.add(user); } - if (userList.size() <= 0) { - return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build(); - } +// if (userList.size() <= 0) { +// return Response.status(Response.Status.NOT_FOUND).entity("No user is available to be retrieved").build(); +// } return Response.status(Response.Status.OK).entity(userList).build(); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while retrieving the list of users using the filter : " + filter; + String msg = "Error occurred while retrieving the list of users using the filter : " + filter; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index 2d437f411c..b2dbecb194 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -21,7 +21,9 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; +import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; @@ -245,4 +247,12 @@ public class RequestValidationUtil { } } + public static void validateCredentials(OldPasswordResetWrapper credentials) { + if (credentials == null || credentials.getNewPassword() == null || credentials.getOldPassword() == null) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Old or New password " + + "fields cannot be empty").build()); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java index d52bdec3d9..6fe5706243 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java @@ -20,8 +20,12 @@ package org.wso2.carbon.device.mgt.jaxrs.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; @@ -48,17 +52,17 @@ public class CredentialManagementResponseBuilder { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { - return Response.status(Response.Status.BAD_REQUEST).entity("No user found with the username " - + username).build(); - } - if (credentials == null || credentials.getNewPassword() == null || credentials.getOldPassword() == null) { - return Response.status(Response.Status.BAD_REQUEST).entity("Password cannot be empty.") - .build(); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username " + + username).build()); } + RequestValidationUtil.validateCredentials(credentials); + if (!validateCredential(credentials.getNewPassword())) { String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); - return Response.status(Response.Status.BAD_REQUEST).entity(errorMsg).build(); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build()); } userStoreManager.updateCredential(username, credentials.getNewPassword(), credentials.getOldPassword()); @@ -66,12 +70,14 @@ public class CredentialManagementResponseBuilder { username + " was successfully changed.").build(); } catch (UserStoreException e) { log.error(e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity("Old password does not match.").build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(e.getMessage()).build()); } catch (UnsupportedEncodingException e) { - String errorMsg = "Could not change the password of the user: " + username + + String msg = "Could not change the password of the user: " + username + ". The Character Encoding is not supported."; - log.error(errorMsg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build(); + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } @@ -85,17 +91,20 @@ public class CredentialManagementResponseBuilder { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { - return Response.status(Response.Status.BAD_REQUEST).entity("No user found with the username " - + username).build(); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username " + + username).build()); } if (credentials == null || credentials.getNewPassword() == null) { - return Response.status(Response.Status.BAD_REQUEST).entity("Password cannot be empty.") - .build(); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Password cannot be empty." + + username).build()); } if (!validateCredential(credentials.getNewPassword())) { String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); - return Response.status(Response.Status.BAD_REQUEST).entity(errorMsg).build(); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build()); } userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + @@ -103,12 +112,14 @@ public class CredentialManagementResponseBuilder { } catch (UserStoreException e) { String msg = "ErrorResponse occurred while updating the credentials of user '" + username + "'"; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } catch (UnsupportedEncodingException e) { String msg = "Could not change the password of the user: " + username + ". The Character Encoding is not supported."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } } From 5b8b15f69b9e8c561a7cfea6e2ecc8b05dba1199 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 31 May 2016 19:12:58 +0530 Subject: [PATCH 13/29] fixed api issues in policy --- .../device/mgt/jaxrs/beans/PolicyWrapper.java | 63 +++------- .../service/api/PolicyManagementService.java | 1 + .../impl/PolicyManagementServiceImpl.java | 117 ++++++++++++------ .../impl/util/PolicyFilteringUtil.java | 41 ++++++ .../src/main/webapp/META-INF/permissions.xml | 2 +- 5 files changed, 145 insertions(+), 79 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java index b8558856fe..31420dae88 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java @@ -21,21 +21,20 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + import java.util.List; @ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy " + "Wrappers") public class PolicyWrapper { - @ApiModelProperty(name = "id", value = "The policy ID", required = true) - private int id; - @ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the" - + " policy", required = true) - private Profile profile; @ApiModelProperty(name = "policyName", value = "The name of the policy", required = true) private String policyName; + @ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true) private String description; + @ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the" + " following non-compliance rules:\n" + "Enforce - Forcefully enforce the policies on the devices\n" @@ -44,8 +43,7 @@ public class PolicyWrapper { + "violation unknown to the user and the administrator can take the necessary actions with regard" + " to the reported", required = true) private String compliance; - @ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true) - private List roles; + @ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the " + "following values:\n" + "ANY - The policy will be applied on the BYOD and COPE device types\n" @@ -53,26 +51,21 @@ public class PolicyWrapper { + "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE " + "device type", required = true) private String ownershipType; - @ApiModelProperty(name = "devices", value = "Lists out the devices the policy is enforced on", + + @ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the" + + " policy", required = true) + private Profile profile; + + @ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true) + private List roles; + + @ApiModelProperty(name = "deviceIdentifiers", value = "Lists out the devices the policy is enforced on", required = true) - private List devices; + private List deviceIdentifiers; + @ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced", required = true) private List users; - @ApiModelProperty(name = "tenantId", value = "The ID of the tenant that created the policy", - required = true) - private int tenantId; - @ApiModelProperty(name = "profileId", value = "The ID of each profile that is in the selected policy", - required = true) - private int profileId; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } public Profile getProfile() { return profile; @@ -122,12 +115,12 @@ public class PolicyWrapper { this.ownershipType = ownershipType; } - public List getDevices() { - return devices; + public List getDeviceIdentifiers() { + return deviceIdentifiers; } - public void setDevices(List devices) { - this.devices = devices; + public void setDeviceIdentifier(List deviceIdentifier) { + this.deviceIdentifiers = deviceIdentifiers; } public List getUsers() { @@ -138,20 +131,4 @@ public class PolicyWrapper { this.users = users; } - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public int getProfileId() { - return profileId; - } - - public void setProfileId(int profileId) { - this.profileId = profileId; - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java index 53ec37550c..b4daa172bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java @@ -258,6 +258,7 @@ public interface PolicyManagementService { required = true) PolicyWrapper policy); @POST + @Path("/remove-policy") @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index faf2b02b1e..32760e1189 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -23,11 +23,13 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.PolicyFilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; import org.wso2.carbon.policy.mgt.common.Policy; @@ -51,49 +53,62 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @Override public Response addPolicy(PolicyWrapper policyWrapper) { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - Policy policy = this.getPolicyFromWrapper(policyWrapper); + try { + Policy policy = this.getPolicyFromWrapper(policyWrapper); - List devices = policy.getDevices(); - if (devices != null && devices.size() == 1) { - DeviceAccessAuthorizationService deviceAccessAuthorizationService = - DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(devices.get(0).getDeviceIdentifier(), - devices.get(0).getType()); - PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - String username = threadLocalCarbonContext.getUsername(); - try { - if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) { - return Response.status(Response.Status.UNAUTHORIZED).entity("Current logged in user is " + - "not authorized to add policies").build(); + List devices = policy.getDevices(); + if (devices != null && devices.size() == 1) { + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(devices.get(0).getDeviceIdentifier(), + devices.get(0).getType()); + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + try { + if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) { + return Response.status(Response.Status.UNAUTHORIZED).entity("Current logged in user is " + + "not authorized to add policies").build(); + } + } catch (DeviceAccessAuthorizationException e) { + String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy"; + log.error(msg, e); + return javax.ws.rs.core.Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - } catch (DeviceAccessAuthorizationException e) { - String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy"; - log.error(msg, e); - return javax.ws.rs.core.Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - } - try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); pap.addPolicy(policy); - return Response.status(Response.Status.OK).entity("Policy has been added successfully").build(); + return Response.status(Response.Status.CREATED).entity("Policy has been added successfully").build(); } catch (PolicyManagementException e) { String msg = "ErrorResponse occurred while adding policy"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (DeviceManagementException e) { + String msg = "ErrorResponse occurred while retrieving device list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) { - Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); + private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) throws DeviceManagementException { + Policy policy = new Policy(); policy.setPolicyName(policyWrapper.getPolicyName()); - policy.setProfileId(policyWrapper.getProfileId()); policy.setDescription(policyWrapper.getDescription()); policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); policy.setOwnershipType(policyWrapper.getOwnershipType()); policy.setRoles(policyWrapper.getRoles()); policy.setUsers(policyWrapper.getUsers()); - policy.setTenantId(policyWrapper.getTenantId()); policy.setCompliance(policyWrapper.getCompliance()); + //TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here. + List devices = null; + List deviceIdentifiers = policyWrapper.getDeviceIdentifiers(); + if (deviceIdentifiers != null) { + for (DeviceIdentifier id : deviceIdentifiers) { + devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id)); + } + } + policy.setDevices(devices); + policy.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); return policy; } @@ -116,7 +131,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(Response.Status.OK).entity(policies).build(); + return Response.status(Response.Status.OK).entity(PolicyFilteringUtil.getPolicies(policies, offset, limit)) + .build(); } @GET @@ -144,19 +160,29 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @Override public Response updatePolicy(@PathParam("id") int id, PolicyWrapper policyWrapper) { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - Policy policy = this.getPolicyFromWrapper(policyWrapper); try { + Policy policy = this.getPolicyFromWrapper(policyWrapper); + policy.setId(id); PolicyAdministratorPoint pap = policyManagementService.getPAP(); + Policy exisitingPolicy = pap.getPolicy(id); + if (exisitingPolicy == null) { + return Response.status(Response.Status.NOT_FOUND).entity("Policy not found.").build(); + } pap.updatePolicy(policy); return Response.status(Response.Status.OK).entity("Policy has successfully been updated").build(); } catch (PolicyManagementException e) { String msg = "ErrorResponse occurred while updating the policy"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (DeviceManagementException e) { + String msg = "ErrorResponse occurred while retrieving the device list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @POST + @Path("/remove-policy") @Override public Response removePolicies(List policyIds) { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); @@ -164,8 +190,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); for (int i : policyIds) { - org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i); - if (!pap.deletePolicy(policy)) { + Policy policy = pap.getPolicy(i); + if (policy == null || !pap.deletePolicy(policy)) { policyDeleted = false; } } @@ -182,41 +208,62 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } } - @POST + @PUT @Path("/activate-policy") @Override public Response activatePolicies(List policyIds) { + boolean isPolicyActivated = false; try { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyAdministratorPoint pap = policyManagementService.getPAP(); for (int i : policyIds) { - pap.activatePolicy(i); + Policy policy = pap.getPolicy(i); + if (policy != null) { + pap.activatePolicy(i); + isPolicyActivated = true; + } } } catch (PolicyManagementException e) { String msg = "ErrorResponse occurred while activating policies"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated").build(); + if (isPolicyActivated) { + return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated") + .build(); + } else { + return Response.status(Response.Status.NOT_FOUND).entity("Selected policies have not been activated") + .build(); + } } - @POST + @PUT @Path("/deactivate-policy") @Override public Response deactivatePolicies(List policyIds) { + boolean isPolicyDeActivated = false; try { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyAdministratorPoint pap = policyManagementService.getPAP(); for (int i : policyIds) { - pap.inactivatePolicy(i); + Policy policy = pap.getPolicy(i); + if (policy != null) { + pap.inactivatePolicy(i); + isPolicyDeActivated = true; + } } } catch (PolicyManagementException e) { String msg = "Exception in inactivating policies."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(Response.Status.OK).entity("Selected policies have been successfully " + - "deactivated").build(); + if (isPolicyDeActivated) { + return Response.status(Response.Status.OK).entity("Selected policies have been successfully " + + "deactivated").build(); + } else { + return Response.status(Response.Status.NOT_FOUND).entity("Selected policies have not been deactivated") + .build(); + } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java new file mode 100644 index 0000000000..d57266145b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; + +import org.wso2.carbon.policy.mgt.common.Policy; + +import java.util.Collections; +import java.util.List; + +/** + * This is used instead of filtering from cache. + * Todo : need to implement proper pagination support on retrieving policies. + */ +public class PolicyFilteringUtil { + + /** + * This is used to filter from the cached policies. + */ + public static List getPolicies(List sourceList, int offset, int limit) { + if(sourceList == null || sourceList.size() < offset){ + return Collections.emptyList(); + } + return sourceList.subList(offset, Math.min(offset + limit, sourceList.size())); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index a886c71925..0c9d193aef 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -736,7 +736,7 @@ Remove policy /device-mgt/admin/policies/remove - /policies/bulk-remove + /policies/remove-policy POST From d9c15b62e7757490ddce5442a486aaad9580f593 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 31 May 2016 23:26:51 +0530 Subject: [PATCH 14/29] few changes after testing user management api --- .../mgt/jaxrs/service/api/UserManagementService.java | 2 +- .../mgt/jaxrs/service/impl/UserManagementServiceImpl.java | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index f3778efcbc..5eb8d54d42 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -406,7 +406,7 @@ public interface UserManagementService { @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, - httpMethod = "POST", + httpMethod = "PUT", value = "Changing the user password.", notes = "A user is able to change the password to secure their EMM profile via this REST API.", tags = "User Management") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 79d51374b3..af2b599109 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -209,9 +209,8 @@ public class UserManagementServiceImpl implements UserManagementService { userWrapper.getEmailAddress()); if (StringUtils.isNotEmpty(userWrapper.getPassword())) { // Decoding Base64 encoded password - byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword()); userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(), - new String(decodedBytes, "UTF-8")); + userWrapper.getPassword()); log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed"); } List currentRoles = this.getFilteredRoles(userStoreManager, userWrapper.getUsername()); @@ -248,7 +247,7 @@ public class UserManagementServiceImpl implements UserManagementService { userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was " + "refused.").build(); } - } catch (UserStoreException | UnsupportedEncodingException e) { + } catch (UserStoreException e) { String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); log.error(msg, e); throw new UnexpectedServerErrorException( @@ -305,7 +304,7 @@ public class UserManagementServiceImpl implements UserManagementService { } } - @POST + @GET @Path("/{username}/roles") @Override public Response getRolesOfUser(@PathParam("username") String username) { From ce557266ecca90ed3b27e9e6b4ae5f6d092f1db8 Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 1 Jun 2016 00:10:30 +0530 Subject: [PATCH 15/29] Fixed issues in RoleManagementService --- .../service/impl/RoleManagementServiceImpl.java | 14 +++++++++++++- .../src/main/webapp/META-INF/permissions.xml | 16 ++++------------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index 2007821939..94df0875c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -170,6 +170,10 @@ public class RoleManagementServiceImpl implements RoleManagementService { @POST @Override public Response addRole(RoleWrapper roleWrapper) { + if (roleWrapper == null) { + log.error("Request body is incorrect or empty"); + return Response.status(Response.Status.BAD_REQUEST).build(); + } try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { @@ -197,6 +201,10 @@ public class RoleManagementServiceImpl implements RoleManagementService { @Path("/{roleName}") @Override public Response updateRole(@PathParam("roleName") String roleName, RoleWrapper roleWrapper) { + if (roleWrapper == null) { + log.error("Request body is incorrect or empty"); + return Response.status(Response.Status.BAD_REQUEST).build(); + } String newRoleName = roleWrapper.getRoleName(); try { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); @@ -256,10 +264,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { return Response.status(Response.Status.OK).build(); } - @POST + @PUT @Path("/{roleName}/users") @Override public Response updateUsersOfRole(@PathParam("roleName") String roleName, List users) { + if (users == null || users.size() == 0) { + log.error("No users are found"); + return Response.status(Response.Status.BAD_REQUEST).build(); + } try { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index a886c71925..dbf4de5cc4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -460,7 +460,7 @@ List roles /device-mgt/admin/roles/list - /roles/permissions + /roles/*/permissions GET @@ -481,22 +481,14 @@ Update role /device-mgt/admin/roles/update - /roles + /roles/* PUT - - - - - - - - Update role /device-mgt/admin/roles/update - /roles/users + /roles/*/users PUT @@ -510,7 +502,7 @@ Remove role /device-mgt/admin/roles/remove - /roles + /roles/* DELETE From 7aa37ff4d5a118e3f9ade737405002828b0697ad Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 1 Jun 2016 00:31:48 +0530 Subject: [PATCH 16/29] Fixed issues in RoleManagementService --- .../jaxrs/service/impl/PolicyManagementServiceImpl.java | 4 ++-- .../mgt/jaxrs/service/impl/RoleManagementServiceImpl.java | 4 ++++ .../util/{PolicyFilteringUtil.java => FilteringUtil.java} | 7 +++---- 3 files changed, 9 insertions(+), 6 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/{PolicyFilteringUtil.java => FilteringUtil.java} (81%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index 32760e1189..f543b7b295 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -29,7 +29,7 @@ import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorization import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.PolicyFilteringUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; import org.wso2.carbon.policy.mgt.common.Policy; @@ -131,7 +131,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(Response.Status.OK).entity(PolicyFilteringUtil.getPolicies(policies, offset, limit)) + return Response.status(Response.Status.OK).entity(FilteringUtil.getFilteredList(policies, offset, limit)) .build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index c0c90e38b5..58e08c1d8f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -25,6 +25,7 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; @@ -60,6 +61,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { RoleList targetRoles; try { filteredRoles = getRolesFromUserStore(); + if (offset != -1 && limit != -1) { + filteredRoles = FilteringUtil.getFilteredList(filteredRoles, offset, limit); + } if (filteredRoles == null) { return Response.status(Response.Status.NOT_FOUND).entity("No roles found.").build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/FilteringUtil.java similarity index 81% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/FilteringUtil.java index d57266145b..3cc650029c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/PolicyFilteringUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/FilteringUtil.java @@ -18,21 +18,20 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; -import org.wso2.carbon.policy.mgt.common.Policy; + import java.util.Collections; import java.util.List; /** * This is used instead of filtering from cache. - * Todo : need to implement proper pagination support on retrieving policies. */ -public class PolicyFilteringUtil { +public class FilteringUtil { /** * This is used to filter from the cached policies. */ - public static List getPolicies(List sourceList, int offset, int limit) { + public static List getFilteredList(List sourceList, int offset, int limit) { if(sourceList == null || sourceList.size() < offset){ return Collections.emptyList(); } From 9f1de717c5213112c12de07c5c050cdc508e1a31 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Wed, 1 Jun 2016 01:23:13 +0530 Subject: [PATCH 17/29] updated permissions in the permission.xml --- .../service/api/UserManagementService.java | 2 +- .../impl/UserManagementServiceImpl.java | 2 +- .../src/main/webapp/META-INF/permissions.xml | 324 +++--------------- 3 files changed, 46 insertions(+), 282 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index 5eb8d54d42..a9285d47ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -336,7 +336,7 @@ public interface UserManagementService { @QueryParam("limit") int limit); @GET - @Path("/usernames") + @Path("/search/usernames") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index af2b599109..91d627e1ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -381,7 +381,7 @@ public class UserManagementServiceImpl implements UserManagementService { } @GET - @Path("/usernames") + @Path("/search/usernames") @Override public Response getUserNames(@QueryParam("filter") String filter, @HeaderParam("If-Modified-Since") String timestamp, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 0c9d193aef..f3a81be3e1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -37,6 +37,12 @@ /activities/* GET + + Fetch Activity related details + /device-mgt/admin/activities/view + /activities + GET + @@ -529,334 +535,100 @@ /users GET - - - Add user - /device-mgt/admin/users/add - /users - POST - - - View user - /device-mgt/admin/users/view - /users/view + List users + /device-mgt/admin/users/list + /users/search/usernames GET - - Update user - /device-mgt/admin/users/update + Add user + /device-mgt/admin/users/add /users - PUT - - - - Change user password - /login - /users/change-password - POST - - - - Reset password - /device-mgt/admin/users/password-reset - /users/reset-password POST - Remove user /device-mgt/admin/users/remove - /users + /users/* DELETE - View user /device-mgt/admin/users/view - /users/roles + /users/* GET - - - - - - - - - - Add user - /device-mgt/admin/users/add - /roles - POST - - - List user devices - /device-mgt/user/devices/list - /users/devices - GET - - - - View user - /device-mgt/admin/users/view - /users/*/* - GET - - - - List users - /device-mgt/admin/users/list - /users/count - GET + Update user + /device-mgt/admin/users/update + /users/* + PUT - - List users - /device-mgt/admin/users/list - /users/view-users - GET + Update user credential + /device-mgt/admin/users/update + /users/*/credentials + PUT - - Add role + Get role /device-mgt/admin/roles/add - /users/view-users - GET - - - - Update role - /device-mgt/admin/roles/update - /users/view-users - GET - - - - Add policy - /device-mgt/admin/policies/add - /users/view-users - GET - - - - Update policy - /device-mgt/admin/policies/update - /users/view-users - GET - - - - List users - /device-mgt/admin/users/list - /users/users-by-username + /users/*/roles GET - - - List users - /device-mgt/admin/users/list - /users/users-by-username/* - GET - - - Invite user - /device-mgt/admin/users/invite - /users/email-invitation + Update user credential + /device-mgt/admin/users/update + /admin/users/*/credentials POST - - Authorize user - /login - /users/authorize - POST - + - - Add Policy - /device-mgt/admin/policies/add - /policies/inactive-policy - POST - - - Add Policy - /device-mgt/user/policies/add - /policies/inactive-policy - POST - - List policies /device-mgt/admin/policies/list - /policies/*/* - POST - - - - List policies - /device-mgt/admin/policies/list - /policies/*/*/* - GET - - - - View device - /device-mgt/admin/devices/view - /policies/*/*/* + /policies GET - - View device - /device-mgt/user/devices/view - /policies/*/*/* - GET + Add Policy + /device-mgt/admin/policies/add + /policies + POST - - Add policy + Activate policy /device-mgt/admin/policies/add - /policies/active-policy - POST + /policies/activate-policy + PUT - Add Policy + Deactivate Policy /device-mgt/user/policies/add - /policies/inactive-policy - POST + /policies/deactivate-policy + PUT - - Remove policy - /device-mgt/admin/policies/remove + Remove Policy + /device-mgt/user/policies/remove /policies/remove-policy POST - - - List policies - /device-mgt/admin/policies/list - /policies - GET - - - List policies - /device-mgt/admin/policies/list - /policies/* - GET - - - - List user policies - /device-mgt/user/policies/list - /policies - GET - - - - List user policies - /device-mgt/user/policies/list + View Policy + /device-mgt/admin/policies/view /policies/* GET - - Update policy + Update Policy /device-mgt/admin/policies/update /policies/* - PUT - - - - Remove policy - /device-mgt/admin/policies/remove - /policies - DELETE - - - - List policies - /device-mgt/admin/policies/list - /policies/count - GET - - - - Edit policy - /device-mgt/admin/policies/update - /policies/priorities - PUT - - - - Edit policy - /device-mgt/admin/policies/update - /policies/activate - PUT - - - - Add policy - /device-mgt/admin/policies/add - /policies/activate - PUT - - - - Edit policy - /device-mgt/admin/policies/update - /policies/inactivate - PUT - - - - Add policy - /device-mgt/admin/policies/add - /policies/inactivate - PUT - - - - Edit policy - /device-mgt/admin/policies/update - /policies/apply-changes - PUT - - - - Add policy - /device-mgt/admin/policies/add - /policies/start-task/* - GET - - - - Add policy - /device-mgt/admin/policies/add - /policies/update-task/* - GET - - - - Add policy - /device-mgt/admin/policies/add - /policies/stop-task - GET - - - - List policies - /device-mgt/admin/policies/list - /policies/*/* - GET + Put @@ -939,14 +711,6 @@ /configuration GET - - - Add configuration - /device-mgt/admin/platform-configs/add - /configuration - POST - - Update configuration /device-mgt/admin/platform-configs/modify From 61beca5048860e6369351f33ead2fecd285311f3 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 1 Jun 2016 01:30:02 +0530 Subject: [PATCH 18/29] Fixing getDevice method to support status, ownership, etc as query param filters --- .../mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java | 4 ++++ .../mgt/jaxrs/service/impl/UserManagementServiceImpl.java | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 75e886cb92..4464f06e5c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -77,14 +77,18 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { PaginationResult result; if (type != null) { + request.setDeviceType(type); result = dms.getDevicesByType(request); } else if (user != null) { + request.setOwner(user); result = dms.getDevicesOfUser(request); } else if (ownership != null) { RequestValidationUtil.validateOwnershipType(ownership); + request.setOwnership(ownership); result = dms.getDevicesByOwnership(request); } else if (status != null) { RequestValidationUtil.validateStatus(status); + request.setStatus(status); result = dms.getDevicesByStatus(request); } else { result = dms.getAllDevices(request); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index af2b599109..74b1769c38 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -79,7 +79,7 @@ public class UserManagementServiceImpl implements UserManagementService { this.inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword); // Outputting debug message upon successful addition of user if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + " was successfully added."); + log.debug("User '" + userWrapper.getUsername() + "' has successfully been added."); } // returning response with success state return Response.status(Response.Status.OK).entity("User by username: " + userWrapper.getUsername() + From 81aa298740c5c401e524fbfce06ff9887684e337 Mon Sep 17 00:00:00 2001 From: mharindu Date: Wed, 1 Jun 2016 02:18:15 +0530 Subject: [PATCH 19/29] Fixed RoleManagementService API issues --- .../device/mgt/jaxrs/beans/PolicyList.java | 55 +++++++++++++++++++ .../device/mgt/jaxrs/beans/RoleList.java | 1 - .../impl/PolicyManagementServiceImpl.java | 13 ++++- .../impl/RoleManagementServiceImpl.java | 18 +++--- 4 files changed, 74 insertions(+), 13 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyList.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyList.java new file mode 100644 index 0000000000..21b4f12cbc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyList.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.policy.mgt.common.Policy; + +import java.util.List; + +@ApiModel(value = "Policy List") +public class PolicyList extends BasePaginatedResult { + + private List policies; + + @ApiModelProperty(value = "List of policies returned") + @JsonProperty("policies") + public List getList() { + return policies; + } + + public void setList(List policies) { + this.policies = policies; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); + sb.append(" roles: [").append(policies).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java index 4cb08fa36c..11cfaa3ddc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleList.java @@ -43,7 +43,6 @@ public class RoleList extends BasePaginatedResult { public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{\n"); - sb.append(" count: ").append(getCount()).append(",\n"); sb.append(" next: ").append(getNext()).append(",\n"); sb.append(" previous: ").append(getPrevious()).append(",\n"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index f543b7b295..aeacd9046e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyList; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; @@ -120,19 +121,27 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @QueryParam("limit") int limit) { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); List policies; + List filteredPolicies; + PolicyList targetPolicies = new PolicyList(); try { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); policies = policyAdministratorPoint.getPolicies(); if (policies == null || policies.size() == 0) { return Response.status(Response.Status.NOT_FOUND).entity("No policies found.").build(); } + targetPolicies.setCount(policies.size()); + filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit); + if (filteredPolicies.size() == 0) { + return Response.status(Response.Status.NOT_FOUND).entity("No policies found.").build(); + } + targetPolicies.setList(filteredPolicies); } catch (PolicyManagementException e) { String msg = "ErrorResponse occurred while retrieving all available policies"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(Response.Status.OK).entity(FilteringUtil.getFilteredList(policies, offset, limit)) - .build(); + + return Response.status(Response.Status.OK).entity(targetPolicies).build(); } @GET diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index 58e08c1d8f..46d4888ef2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -58,17 +58,17 @@ public class RoleManagementServiceImpl implements RoleManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { List filteredRoles; - RoleList targetRoles; + RoleList targetRoles = new RoleList(); try { filteredRoles = getRolesFromUserStore(); - if (offset != -1 && limit != -1) { - filteredRoles = FilteringUtil.getFilteredList(filteredRoles, offset, limit); - } - if (filteredRoles == null) { + if (filteredRoles == null || filteredRoles.size() == 0) { return Response.status(Response.Status.NOT_FOUND).entity("No roles found.").build(); } - targetRoles = new RoleList(); targetRoles.setCount(filteredRoles.size()); + filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(), offset, limit); + if (filteredRoles.size() == 0) { + return Response.status(Response.Status.NOT_FOUND).entity("No roles found.").build(); + } targetRoles.setList(filteredRoles); } catch (UserStoreException e) { String msg = "Error occurred while retrieving roles from the underlying user stores"; @@ -219,8 +219,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { @Override public Response updateRole(@PathParam("roleName") String roleName, RoleWrapper roleWrapper) { if (roleWrapper == null) { - log.error("Request body is incorrect or empty"); - return Response.status(Response.Status.BAD_REQUEST).build(); + return Response.status(Response.Status.BAD_REQUEST).entity("Request body is incorrect or empty").build(); } String newRoleName = roleWrapper.getRoleName(); try { @@ -290,8 +289,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { @Override public Response updateUsersOfRole(@PathParam("roleName") String roleName, List users) { if (users == null || users.size() == 0) { - log.error("No users are found"); - return Response.status(Response.Status.BAD_REQUEST).build(); + return Response.status(Response.Status.BAD_REQUEST).entity("No users are found in the request").build(); } try { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); From 25e45dc9f1053c9d0ab2f350898ee33dc1200f58 Mon Sep 17 00:00:00 2001 From: dilanua Date: Wed, 1 Jun 2016 10:44:08 +0530 Subject: [PATCH 20/29] Fixing issues in GET /operations and /admin/devices APIs --- .../service/impl/DeviceManagementServiceImpl.java | 4 ++-- .../admin/DeviceManagementAdminServiceImpl.java | 14 +++++++++++--- .../src/main/webapp/META-INF/permissions.xml | 14 ++++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 75e886cb92..b9e181745a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -326,8 +326,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { dms = DeviceMgtAPIUtils.getDeviceManagementService(); operations = dms.getOperations(new DeviceIdentifier(id, type)); if (operations == null) { - Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is found upon " + - "the provided type and id"); + return Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is found upon " + + "the provided type and id").build(); } } catch (OperationManagementException e) { String msg = "Error occurred while fetching the operations for the '" + type + "' device, which " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 54140ccada..6400e59821 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -25,9 +25,11 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnauthorizedAccessException; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -67,11 +69,17 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" + name + "', is currently enrolled in the system").build(); } - return Response.status(Response.Status.OK).entity(devices).build(); + + DeviceList deviceList = new DeviceList(); + deviceList.setCount(devices.size()); + deviceList.setList(devices); + + return Response.status(Response.Status.OK).entity(deviceList).build(); } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the devices that carry the name '" + name + "'"; + String msg = "Error occurred at server side while fetching device list."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 45293bc4a1..5a9c3f5347 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -394,6 +394,20 @@ GET + + View device + /device-mgt/admin/devices/view + /devices/*/*/operations + GET + + + + View device + /device-mgt/user/devices/view + /devices/*/*/operations + GET + + From 07a4a65c7c7df7d9999f0b2eadc03080a8631fe3 Mon Sep 17 00:00:00 2001 From: dilanua Date: Wed, 1 Jun 2016 11:14:17 +0530 Subject: [PATCH 21/29] Fixing permission issues with GET /devices/*/*/features API --- .../src/main/webapp/META-INF/permissions.xml | 37 ++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 5a9c3f5347..8797ebc6cb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -418,34 +418,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + List policies /device-mgt/admin/policies/list - /features/* + /devices/*/*/features GET View device /device-mgt/admin/devices/view - /features/* + /devices/*/*/features GET View device /device-mgt/user/devices/view - /features/* + /devices/*/*/features GET View device /device-mgt/user/devices/view - /features + /devices/*/*/features GET - + From d926bdaa3464ab45f999f7ac84ac4e8985c637ce Mon Sep 17 00:00:00 2001 From: ayyoob Date: Wed, 1 Jun 2016 12:20:18 +0530 Subject: [PATCH 22/29] removed unused permission from permission.xml --- .../src/main/webapp/META-INF/permissions.xml | 193 ++++++------------ 1 file changed, 67 insertions(+), 126 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 8797ebc6cb..5034e47d1d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -30,104 +30,7 @@ - - - Fetch Activity related details - /device-mgt/admin/activities/view - /activities/* - GET - - - Fetch Activity related details - /device-mgt/admin/activities/view - /activities - GET - - - - - List devices - /device-mgt/admin/devices/list - /devices - GET - - - - List device types - /device-mgt/admin/devices/list - /devices/types - GET - - - - List device types - /device-mgt/user/devices/list - /devices/types - GET - - - - Add policy - /device-mgt/admin/policies/add - /devices/types - GET - - - - Add User policy - /device-mgt/user/policies/add - /devices/types - GET - - - - Edit policy - /device-mgt/admin/policies/update - /devices/types - GET - - - - Edit User policy - /device-mgt/user/policies/update - /devices/types - GET - - - - View device - /device-mgt/admin/devices/view - /devices/view - GET - - - - View user device - /device-mgt/user/devices/view - /devices/view - GET - - - - Modify user device - /device-mgt/user/devices/update - /devices/type/*/id/* - PUT - - - - Remove user device - /device-mgt/user/devices/remove - /devices/type/*/id/* - DELETE - - - - - - - - + Device Management /device-mgt @@ -239,51 +142,90 @@ / GET + - - - - - - - - - - + - View device - /device-mgt/admin/devices/view - /devices/user/*/* + Fetch Activity related details + /device-mgt/admin/activities/view + /activities/* GET - - Devices Count All + Fetch Activity related details + /device-mgt/admin/activities/view + /activities + GET + + + + + List devices /device-mgt/admin/devices/list - /devices/count + /devices GET - - Device Count - /device-mgt/user/devices/list - /devices/user/*/count + Retrieve device information + /device-mgt/admin/devices/list + /devices/*/*/info GET - - List devices + Get device /device-mgt/admin/devices/list - /devices/name/*/* + /devices/*/* GET - - List All Own Devices - /device-mgt/user/devices/list - /devices/user/* + Get device location + /device-mgt/admin/devices/list + /devices/*/*/location + GET + + + devices location + /device-mgt/admin/devices/list + /devices/locations + POST + + + Get devices feature + /device-mgt/admin/devices/list + /devices/*/*/features + GET + + + Search devices + /device-mgt/admin/devices/list + /devices/search-devices + POST + + + list device application + /device-mgt/admin/devices/list + /devices/*/*/applications GET + + list device operation + /device-mgt/admin/devices/list + /devices/*/*/operations + GET + + + list device effective-policy + /device-mgt/admin/devices/list + /devices/*/*/effective-policy + GET + + + list devices + /device-mgt/admin/devices/list + /devices/admin/devices + GET + + @@ -1033,5 +975,4 @@ GET - From aa6298b5e77d75cbcbbd850a4522d160163b9245 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Wed, 1 Jun 2016 12:28:10 +0530 Subject: [PATCH 23/29] updated device management admin api permission --- .../src/main/webapp/META-INF/permissions.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 5034e47d1d..4328808d68 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -222,7 +222,7 @@ list devices /device-mgt/admin/devices/list - /devices/admin/devices + /admin/devices GET From 52c59c8e53dcc0022369fbe48c0a2945aeb6d25a Mon Sep 17 00:00:00 2001 From: ayyoob Date: Wed, 1 Jun 2016 12:39:38 +0530 Subject: [PATCH 24/29] added permission updates on certificates --- .../src/main/webapp/META-INF/permissions.xml | 2 +- .../src/main/webapp/META-INF/permissions.xml | 16 ++++------------ 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml index 8718c827e0..b38133cc1f 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -33,7 +33,7 @@ get certificate in the database /device-mgt/emm-admin/certificate/GetSignCSR - /certificates/signcsr + /certificates/scep/signcsr POST emm_admin diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml index 480483adb4..dcd6b92155 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/permissions.xml @@ -29,38 +29,30 @@ --> - - - get certificate in the database - /device-mgt/emm-admin/certificate/GetSignCSR - /certificates/sign-csr - POST - emm_admin - Save certificate /device-mgt/admin/certificate/Save - /certificates + /admin/certificates POST Get certificate /device-mgt/admin/certificate/Get - /certificates/* + /admin/certificates/* GET Get all certificates /device-mgt/admin/certificate/GetAll - /certificates + /admin/certificates GET Remove certificate /device-mgt/admin/certificate/Remove - /certificates/* + /admin/certificates/* DELETE From 0bd2a46690d6beb4968e9ba6b04bbc3f4286289e Mon Sep 17 00:00:00 2001 From: dilanua Date: Wed, 1 Jun 2016 15:58:45 +0530 Subject: [PATCH 25/29] Adding H2/MSSQL/ORACLE/POSTGRESQL support for GET /admin/devices API --- .../impl/DeviceManagementServiceImpl.java | 5 +- .../DeviceManagementAdminServiceImpl.java | 15 +++-- .../mgt/jaxrs/util/DeviceMgtAPIUtils.java | 5 +- .../carbon/device/mgt/core/dao/DeviceDAO.java | 3 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 65 ------------------- .../dao/impl/device/GenericDeviceDAOImpl.java | 65 +++++++++++++++++++ .../dao/impl/device/OracleDeviceDAOImpl.java | 65 +++++++++++++++++++ .../impl/device/PostgreSQLDeviceDAOImpl.java | 65 +++++++++++++++++++ .../impl/device/SQLServerDeviceDAOImpl.java | 65 +++++++++++++++++++ 9 files changed, 276 insertions(+), 77 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index b9e181745a..d7065e0878 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -272,10 +272,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - if (devices == null) { + if (devices == null || devices.size() == 0) { return Response.status(Response.Status.NOT_FOUND).entity("It is likely that no device is found upon " + - "the provided type and id").build(); + "the provided search filters").build(); } + return Response.status(Response.Status.OK).entity(devices).build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 6400e59821..46f80d18bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -56,30 +56,31 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { throw new UnauthorizedAccessException( - new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage( - "Current logged in user is not authorized to perform this operation").build()); + new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage( + "Current logged in user is not authorized to perform this operation").build()); } PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain)); List devices = DeviceMgtAPIUtils.getDeviceManagementService(). - getDevicesByNameAndType(name, type, offset, limit); - if (devices == null) { + getDevicesByNameAndType(name, type, offset, limit); + if (devices == null || devices.size() == 0) { return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" + - name + "', is currently enrolled in the system").build(); + name + "', is currently enrolled in the system").build(); } + // setting up paginated result DeviceList deviceList = new DeviceList(); - deviceList.setCount(devices.size()); deviceList.setList(devices); + deviceList.setCount(devices.size()); return Response.status(Response.Status.OK).entity(deviceList).build(); } catch (DeviceManagementException e) { String msg = "Error occurred at server side while fetching device list."; log.error(msg, e); throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index 9f273b63b1..d9c998c622 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -252,12 +252,13 @@ public class DeviceMgtAPIUtils { RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null); if (realmService == null) { - throw new IllegalStateException(""); + throw new IllegalStateException("Realm service has not been initialized."); } try { return realmService.getTenantManager().getTenantId(tenantDomain); } catch (UserStoreException e) { - throw new DeviceManagementException(""); + throw new DeviceManagementException("Error occured while trying to " + + "obtain tenant id of currently logged in user"); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index a65f40db65..ae7fd00de2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -259,7 +259,8 @@ public interface DeviceDAO { * @return returns list of devices. * @throws DeviceManagementDAOException */ - List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) throws DeviceManagementDAOException; + List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) + throws DeviceManagementDAOException; /** * This method is used to retrieve devices of a given device name as a paginated result. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 0bc4d83f64..96dce585c2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -619,71 +619,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return deviceCount; } - /** - * Get the list of devices that matches with the given device name. - * - * @param deviceName Name of the device. - * @param tenantId Id of the current tenant - * @return device list - * @throws DeviceManagementDAOException - */ - @Override - public List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) - throws DeviceManagementDAOException { - - String filteringString = ""; - if (deviceName != null && !deviceName.isEmpty()) { - filteringString = filteringString + " AND d.NAME LIKE ?"; - } - - if (type != null && !type.isEmpty()) { - filteringString = filteringString + " AND t.NAME = ?"; - } - - Connection conn; - PreparedStatement stmt = null; - List devices = new ArrayList<>(); - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + - ") d1 WHERE d1.ID = e.DEVICE_ID LIMIT ?, ?"; - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - - int i = 1; - - if (deviceName != null && !deviceName.isEmpty()) { - stmt.setString(++i, deviceName + "%"); - } - - if (type != null && !type.isEmpty()) { - stmt.setString(++i, type); - } - - stmt.setInt(++i, offset); - stmt.setInt(++i, limit); - - rs = stmt.executeQuery(); - - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + deviceName + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - @Override public int addEnrollment(Device device, int tenantId) throws DeviceManagementDAOException { Connection conn; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index e009fd6343..d10b7e9d99 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -303,6 +303,71 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + /** + * Get the list of devices that matches with the given device name and (or) device type. + * + * @param deviceName Name of the device. + * @param tenantId Id of the current tenant + * @return device list + * @throws DeviceManagementDAOException + */ + @Override + public List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) + throws DeviceManagementDAOException { + + String filteringString = ""; + if (deviceName != null && !deviceName.isEmpty()) { + filteringString = filteringString + " AND d.NAME LIKE ?"; + } + + if (type != null && !type.isEmpty()) { + filteringString = filteringString + " AND t.NAME = ?"; + } + + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + ResultSet rs = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID LIMIT ?, ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int i = 1; + + if (deviceName != null && !deviceName.isEmpty()) { + stmt.setString(++i, deviceName + "%"); + } + + if (type != null && !type.isEmpty()) { + stmt.setString(++i, type); + } + + stmt.setInt(++i, offset); + stmt.setInt(++i, limit); + + rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" + + "to the mentioned filtering criteria", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index bc8756710c..7d2f874dd5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -310,6 +310,71 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + /** + * Get the list of devices that matches with the given device name and (or) device type. + * + * @param deviceName Name of the device. + * @param tenantId Id of the current tenant + * @return device list + * @throws DeviceManagementDAOException + */ + @Override + public List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) + throws DeviceManagementDAOException { + + String filteringString = ""; + if (deviceName != null && !deviceName.isEmpty()) { + filteringString = filteringString + " AND d.NAME LIKE ?"; + } + + if (type != null && !type.isEmpty()) { + filteringString = filteringString + " AND t.NAME = ?"; + } + + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + ResultSet rs = null; + try { + conn = this.getConnection(); + String sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, " + + "d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + + "(SELECT d.ID, d.NAME, d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID) rs) WHERE offset >= ? AND ROWNUM <= ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int i = 1; + + if (deviceName != null && !deviceName.isEmpty()) { + stmt.setString(++i, deviceName + "%"); + } + + if (type != null && !type.isEmpty()) { + stmt.setString(++i, type); + } + + stmt.setInt(++i, offset); + stmt.setInt(++i, limit); + + rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" + + "to the mentioned filtering criteria", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 00ed10661b..878e310742 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -303,6 +303,71 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + /** + * Get the list of devices that matches with the given device name and (or) device type. + * + * @param deviceName Name of the device. + * @param tenantId Id of the current tenant + * @return device list + * @throws DeviceManagementDAOException + */ + @Override + public List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) + throws DeviceManagementDAOException { + + String filteringString = ""; + if (deviceName != null && !deviceName.isEmpty()) { + filteringString = filteringString + " AND d.NAME LIKE ?"; + } + + if (type != null && !type.isEmpty()) { + filteringString = filteringString + " AND t.NAME = ?"; + } + + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + ResultSet rs = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? LIMIT ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int i = 1; + + if (deviceName != null && !deviceName.isEmpty()) { + stmt.setString(++i, deviceName + "%"); + } + + if (type != null && !type.isEmpty()) { + stmt.setString(++i, type); + } + + stmt.setInt(++i, offset); + stmt.setInt(++i, limit); + + rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" + + "to the mentioned filtering criteria", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index d39bc7f52d..476b703ad8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -305,6 +305,71 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } + /** + * Get the list of devices that matches with the given device name and (or) device type. + * + * @param deviceName Name of the device. + * @param tenantId Id of the current tenant + * @return device list + * @throws DeviceManagementDAOException + */ + @Override + public List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) + throws DeviceManagementDAOException { + + String filteringString = ""; + if (deviceName != null && !deviceName.isEmpty()) { + filteringString = filteringString + " AND d.NAME LIKE ?"; + } + + if (type != null && !type.isEmpty()) { + filteringString = filteringString + " AND t.NAME = ?"; + } + + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + ResultSet rs = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int i = 1; + + if (deviceName != null && !deviceName.isEmpty()) { + stmt.setString(++i, deviceName + "%"); + } + + if (type != null && !type.isEmpty()) { + stmt.setString(++i, type); + } + + stmt.setInt(++i, offset); + stmt.setInt(++i, limit); + + rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" + + "to the mentioned filtering criteria", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } From e002ffb54ab08e6c4b0ff9081e5288c41ffa6783 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 2 Jun 2016 00:20:14 +0530 Subject: [PATCH 26/29] Re-enabling retrieval of device info --- .../service/api/DeviceManagementService.java | 125 +++++++++--------- .../impl/DeviceManagementServiceImpl.java | 45 ++++--- 2 files changed, 85 insertions(+), 85 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 2fad649ab4..9c88e11cd8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -201,69 +201,68 @@ public interface DeviceManagementService { required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); -// @POST -// @ApiOperation( -// consumes = MediaType.APPLICATION_JSON, -// produces = MediaType.APPLICATION_JSON, -// httpMethod = "POST", -// value = "Retrieve devices information from the supplied device identifies.", -// notes = "This will return device information such as CPU usage, memory usage etc for supplied device " + -// "identifiers.", -// response = DeviceInfo.class, -// responseContainer = "List", -// tags = "Device Management") -// @ApiResponses( -// value = { -// @ApiResponse( -// code = 200, -// message = "OK. \n Information of the submitted list of devices is returned", -// response = DeviceInfo.class, -// responseContainer = "List", -// responseHeaders = { -// @ResponseHeader( -// name = "Content-Type", -// description = "The content type of the body"), -// @ResponseHeader( -// name = "ETag", -// description = "Entity Tag of the response resource.\n" + -// "Used by caches, or in conditional requests."), -// @ResponseHeader( -// name = "Last-Modified", -// description = "Date and time the resource has been modified the last time.\n" + -// "Used by caches, or in conditional requests.")}), -// @ApiResponse( -// code = 303, -// message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", -// responseHeaders = { -// @ResponseHeader( -// name = "Content-Location", -// description = "The Source URL of the document.")}), -// @ApiResponse( -// code = 304, -// message = "Not Modified. \n " + -// "Empty body because the client already has the latest version of the requested resource."), -// @ApiResponse( -// code = 400, -// message = "Bad Request. \n Invalid request or validation error."), -// @ApiResponse( -// code = 406, -// message = "Not Acceptable. \n The requested media type is not supported."), -// @ApiResponse( -// code = 500, -// message = "Internal Server ErrorResponse. \n " + -// "Server error occurred while retrieving information of the list of the devices submitted.") -// }) -// @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) -// Response getDevicesInfo( -// @ApiParam( -// name = "deviceIds", -// value = "List of device identifiers", -// required = true) List deviceIds, -// @ApiParam( -// name = "If-Modified-Since", -// value = "Timestamp of the last modified date", -// required = false) -// @HeaderParam("If-Modified-Since") String timestamp); + @POST + @Path("/get-info") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Retrieve devices information from the supplied device identifies.", + notes = "This will return device information such as CPU usage, memory usage etc for supplied device " + + "identifiers.", + tags = "Device Management") + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Information of the submitted list of devices is returned", + response = DeviceInfo.class, + responseContainer = "List", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.")}), + @ApiResponse( + code = 303, + message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 304, + message = "Not Modified. \n " + + "Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 406, + message = "Not Acceptable. \n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server ErrorResponse. \n " + + "Server error occurred while retrieving information of the list of the devices submitted.") + }) + @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) + Response getDevicesInfo( + @ApiParam( + name = "If-Modified-Since", + value = "Timestamp of the last modified date", + required = false) + @HeaderParam("If-Modified-Since") String timestamp, + @ApiParam( + name = "deviceIds", + value = "List of device identifiers", + required = true) List deviceIds); @GET diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index d7065e0878..04eb20326c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -131,28 +131,29 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).entity(deviceInfo).build(); } -// -// @POST -// @Override -// public Response getDevicesInfo( -// List deviceIds, -// @HeaderParam("If-Modified-Since") String timestamp) { -// DeviceInformationManager informationManager; -// List deviceInfo; -// try { -// informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); -// deviceInfo = informationManager.getDevicesInfo(deviceIds); -// if (deviceInfo == null) { -// return Response.status(Response.Status.NOT_FOUND).entity("No device information is available for the " + -// "device list submitted").build(); -// } -// } catch (DeviceDetailsMgtException e) { -// String msg = "Error occurred while getting the device information."; -// log.error(msg, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); -// } -// return Response.status(Response.Status.OK).entity(deviceInfo).build(); -// } + + @POST + @Path("/get-info") + @Override + public Response getDevicesInfo( + @HeaderParam("If-Modified-Since") String timestamp, + List deviceIds) { + DeviceInformationManager informationManager; + List deviceInfo; + try { + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); + deviceInfo = informationManager.getDevicesInfo(deviceIds); + if (deviceInfo == null) { + return Response.status(Response.Status.NOT_FOUND).entity("No device information is available for the " + + "device list submitted").build(); + } + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while getting the device information."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(deviceInfo).build(); + } @GET @Path("/{type}/{id}") From 9ebf7053237230ceada2de0e3bf5f69e25a07bcc Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 2 Jun 2016 00:22:46 +0530 Subject: [PATCH 27/29] Re-enabling retrieval of device info --- .../service/api/DeviceManagementService.java | 125 +++++++++--------- .../impl/DeviceManagementServiceImpl.java | 44 +++--- 2 files changed, 84 insertions(+), 85 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 2fad649ab4..f1c13574f5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -201,69 +201,68 @@ public interface DeviceManagementService { required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); -// @POST -// @ApiOperation( -// consumes = MediaType.APPLICATION_JSON, -// produces = MediaType.APPLICATION_JSON, -// httpMethod = "POST", -// value = "Retrieve devices information from the supplied device identifies.", -// notes = "This will return device information such as CPU usage, memory usage etc for supplied device " + -// "identifiers.", -// response = DeviceInfo.class, -// responseContainer = "List", -// tags = "Device Management") -// @ApiResponses( -// value = { -// @ApiResponse( -// code = 200, -// message = "OK. \n Information of the submitted list of devices is returned", -// response = DeviceInfo.class, -// responseContainer = "List", -// responseHeaders = { -// @ResponseHeader( -// name = "Content-Type", -// description = "The content type of the body"), -// @ResponseHeader( -// name = "ETag", -// description = "Entity Tag of the response resource.\n" + -// "Used by caches, or in conditional requests."), -// @ResponseHeader( -// name = "Last-Modified", -// description = "Date and time the resource has been modified the last time.\n" + -// "Used by caches, or in conditional requests.")}), -// @ApiResponse( -// code = 303, -// message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", -// responseHeaders = { -// @ResponseHeader( -// name = "Content-Location", -// description = "The Source URL of the document.")}), -// @ApiResponse( -// code = 304, -// message = "Not Modified. \n " + -// "Empty body because the client already has the latest version of the requested resource."), -// @ApiResponse( -// code = 400, -// message = "Bad Request. \n Invalid request or validation error."), -// @ApiResponse( -// code = 406, -// message = "Not Acceptable. \n The requested media type is not supported."), -// @ApiResponse( -// code = 500, -// message = "Internal Server ErrorResponse. \n " + -// "Server error occurred while retrieving information of the list of the devices submitted.") -// }) -// @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) -// Response getDevicesInfo( -// @ApiParam( -// name = "deviceIds", -// value = "List of device identifiers", -// required = true) List deviceIds, -// @ApiParam( -// name = "If-Modified-Since", -// value = "Timestamp of the last modified date", -// required = false) -// @HeaderParam("If-Modified-Since") String timestamp); + @POST + @Path("/get-info") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Retrieve devices information from the supplied device identifies.", + notes = "This will return device information such as CPU usage, memory usage etc for supplied device " + + "identifiers.", + tags = "Device Management") + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Information of the submitted list of devices is returned", + response = DeviceInfo.class, + responseContainer = "List", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.")}), + @ApiResponse( + code = 303, + message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 304, + message = "Not Modified. \n " + + "Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error."), + @ApiResponse( + code = 406, + message = "Not Acceptable. \n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server ErrorResponse. \n " + + "Server error occurred while retrieving information of the list of the devices submitted.") + }) + @Permission(scope = "device-info", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) + Response getDevicesInfo( + @ApiParam( + name = "deviceIds", + value = "List of device identifiers", + required = true) List deviceIds, + @ApiParam( + name = "If-Modified-Since", + value = "Timestamp of the last modified date", + required = false) + @HeaderParam("If-Modified-Since") String timestamp); @GET diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 4464f06e5c..6122071b40 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -135,28 +135,28 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).entity(deviceInfo).build(); } -// -// @POST -// @Override -// public Response getDevicesInfo( -// List deviceIds, -// @HeaderParam("If-Modified-Since") String timestamp) { -// DeviceInformationManager informationManager; -// List deviceInfo; -// try { -// informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); -// deviceInfo = informationManager.getDevicesInfo(deviceIds); -// if (deviceInfo == null) { -// return Response.status(Response.Status.NOT_FOUND).entity("No device information is available for the " + -// "device list submitted").build(); -// } -// } catch (DeviceDetailsMgtException e) { -// String msg = "Error occurred while getting the device information."; -// log.error(msg, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); -// } -// return Response.status(Response.Status.OK).entity(deviceInfo).build(); -// } + + @POST + @Override + public Response getDevicesInfo( + List deviceIds, + @HeaderParam("If-Modified-Since") String timestamp) { + DeviceInformationManager informationManager; + List deviceInfo; + try { + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); + deviceInfo = informationManager.getDevicesInfo(deviceIds); + if (deviceInfo == null) { + return Response.status(Response.Status.NOT_FOUND).entity("No device information is available for the " + + "device list submitted").build(); + } + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while getting the device information."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(deviceInfo).build(); + } @GET @Path("/{type}/{id}") From fe22bfc1254c605a17c0c5fba1cbf7ae9795edf0 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 2 Jun 2016 00:33:14 +0530 Subject: [PATCH 28/29] Renaming 'recieved' to 'received' --- .../common/operation/mgt/OperationResponse.java | 14 +++++++------- .../mgt/dao/impl/GenericOperationDAOImpl.java | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java index 5a154e35b7..5b3e99104f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java @@ -26,11 +26,11 @@ import io.swagger.annotations.ApiModelProperty; + " responses") public class OperationResponse { - @ApiModelProperty(name = "response", value = "Operation response return from the device", required = true) + @ApiModelProperty(name = "response", value = "Operation response returned from the device", required = true) private String response; - @ApiModelProperty(name = "recievedTimeStamp", value = "Time that the operation response received", + @ApiModelProperty(name = "receivedTimeStamp", value = "Time that the operation response received", required = true) - private String recievedTimeStamp; + private String receivedTimeStamp; public String getResponse() { return response; @@ -40,12 +40,12 @@ public class OperationResponse { this.response = response; } - public String getRecievedTimeStamp() { - return recievedTimeStamp; + public String getReceivedTimeStamp() { + return receivedTimeStamp; } - public void setRecievedTimeStamp(String recievedTimeStamp) { - this.recievedTimeStamp = recievedTimeStamp; + public void setReceivedTimeStamp(String receivedTimeStamp) { + this.receivedTimeStamp = receivedTimeStamp; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index e7fa8bdd62..dd3ea76b0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -207,7 +207,7 @@ public class GenericOperationDAOImpl implements OperationDAO { while (rs.next()) { OperationResponse response = new OperationResponse(); - response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); ByteArrayInputStream bais = null; ObjectInputStream ois = null; byte[] contentBytes; @@ -435,7 +435,7 @@ public class GenericOperationDAOImpl implements OperationDAO { ClassNotFoundException, IOException, SQLException { OperationResponse response = new OperationResponse(); if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); } ByteArrayInputStream bais = null; ObjectInputStream ois = null; From 92cf44380e447205f8e834e39f1e69f020d4dc2a Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 2 Jun 2016 00:48:44 +0530 Subject: [PATCH 29/29] Adding validations to certificate deletion operation --- .../api/impl/CertificateManagementAdminServiceImpl.java | 8 ++++++-- .../mgt/core/dao/impl/GenericCertificateDAOImpl.java | 5 +---- .../core/service/CertificateManagementServiceImpl.java | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java index ebe9953f8b..15b0a548c7 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java @@ -121,9 +121,13 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); try { - certificateService.removeCertificate(serialNumber); + boolean status = certificateService.removeCertificate(serialNumber); + if (!status) { + Response.status(Response.Status.NOT_FOUND).entity("No certificate is found with the given " + + "serial number '" + serialNumber + "'"); + } return Response.status(Response.Status.OK).entity("Certificate that carries the serial number '" + - serialNumber + " has been removed").build(); + serialNumber + "' has been removed").build(); } catch (CertificateManagementDAOException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; log.error(msg, e); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index 73f6ee7b79..5109f55e03 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -252,10 +252,7 @@ public class GenericCertificateDAOImpl implements CertificateDAO { stmt.setString(1, serialNumber); stmt.setInt(2, tenantId); - if(stmt.executeUpdate() > 0) { - return true; - } - return false; + return stmt.executeUpdate() > 0; } catch (SQLException e) { String errorMsg = "Unable to get the read the certificate with serial" + serialNumber; diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 89fd9b4827..83505cf04a 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -173,7 +173,7 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe try { CertificateManagementDAOFactory.beginTransaction(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - Boolean status = certificateDAO.removeCertificate(serialNumber); + boolean status = certificateDAO.removeCertificate(serialNumber); CertificateManagementDAOFactory.commitTransaction(); return status; } catch (TransactionManagementException e) {