From 516155dae514a8e3e2de800f1b68a0ad6cfa2fc9 Mon Sep 17 00:00:00 2001 From: charithag Date: Mon, 18 Apr 2016 16:39:35 +0530 Subject: [PATCH 01/10] Moved devicemgt_admin jax-rs to device-mgt from carbon-devicemgt-plugins --- .../org.wso2.carbon.device.mgt.api/pom.xml | 4 +- .../org/wso2/carbon/mdm/api/Certificate.java | 62 +-- .../wso2/carbon/mdm/api/Configuration.java | 98 ++-- .../api/{MobileDevice.java => Device.java} | 144 +++--- .../carbon/mdm/api/DeviceInformation.java | 23 +- .../carbon/mdm/api/DeviceNotification.java | 123 ++--- .../org/wso2/carbon/mdm/api/DeviceSearch.java | 13 +- .../java/org/wso2/carbon/mdm/api/Feature.java | 22 +- .../java/org/wso2/carbon/mdm/api/Group.java | 443 ++++++++++++++++++ .../java/org/wso2/carbon/mdm/api/License.java | 38 +- .../org/wso2/carbon/mdm/api/Operation.java | 164 +++---- .../java/org/wso2/carbon/mdm/api/Policy.java | 243 +++++----- .../java/org/wso2/carbon/mdm/api/Profile.java | 75 ++- .../java/org/wso2/carbon/mdm/api/Role.java | 328 +++++++------ .../java/org/wso2/carbon/mdm/api/User.java | 228 +++++---- .../CredentialManagementResponseBuilder.java | 31 +- ...DMAPIUtils.java => DeviceMgtAPIUtils.java} | 23 +- .../org/wso2/carbon/mdm/util/Constants.java | 10 +- .../src/main/webapp/META-INF/permissions.xml | 345 ++++++++++---- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 16 +- .../src/main/webapp/WEB-INF/web.xml | 10 +- .../pom.xml | 2 +- .../src/main/resources/p2.inf | 2 +- .../pom.xml | 18 +- features/device-mgt/pom.xml | 33 +- pom.xml | 6 + 26 files changed, 1553 insertions(+), 951 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/{MobileDevice.java => Device.java} (51%) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java rename components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/{MDMAPIUtils.java => DeviceMgtAPIUtils.java} (94%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index a187c98560..f6c0292529 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -50,7 +50,7 @@ 2.2 WEB-INF/lib/*cxf*.jar - mdm-admin + devicemgt_admin @@ -77,7 +77,7 @@ - + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java index e7ba2fd3e7..e1714c2c29 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java @@ -18,7 +18,6 @@ package org.wso2.carbon.mdm.api; -import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; @@ -29,14 +28,19 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.beans.EnrollmentCertificate; -import org.wso2.carbon.mdm.exception.*; -import org.wso2.carbon.mdm.exception.BadRequestException; -import org.wso2.carbon.mdm.util.MDMUtil; +import org.wso2.carbon.mdm.exception.Message; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; @@ -45,7 +49,8 @@ import java.util.List; /** * All the certificate related tasks such as saving certificates, can be done through this endpoint. */ -@Produces({ "application/json", "application/xml" }) +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) @Consumes({ "application/json", "application/xml" }) public class Certificate { @@ -57,18 +62,16 @@ public class Certificate { * @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. - * @throws MDMAPIException */ @POST @Path("saveCertificate") public Response saveCertificate(@HeaderParam("Accept") String acceptHeader, - EnrollmentCertificate[] enrollmentCertificates) throws MDMAPIException { - MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); + EnrollmentCertificate[] enrollmentCertificates) { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); CertificateManagementService certificateService; - List certificates = new ArrayList(); + List certificates = new ArrayList<>(); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; - certificateService = MDMAPIUtils.getCertificateManagementService(); + certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); try { for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); @@ -83,7 +86,7 @@ public class Certificate { } catch (KeystoreException e) { String msg = "Error occurred while converting PEM file to X509Certificate."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); } } @@ -92,22 +95,21 @@ public class Certificate { * * @param serialNumber serial of the certificate needed. * @return certificate response. - * @throws MDMAPIException */ @GET @Path("{serialNumber}") public Response getCertificate(@HeaderParam("Accept") String acceptHeader, - @PathParam("serialNumber") String serialNumber) throws MDMAPIException { - MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(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."); - throw new BadRequestException(message, responseMediaType); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); } - CertificateManagementService certificateService = MDMAPIUtils.getCertificateManagementService(); + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); CertificateResponse certificateResponse; try { certificateResponse = certificateService.getCertificateBySerial(serialNumber); @@ -118,7 +120,7 @@ public class Certificate { } catch (KeystoreException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; log.error(msg, e); - return Response.serverError().build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); } } @@ -136,20 +138,20 @@ public class Certificate { @QueryParam("start") int startIndex, @QueryParam("length") int length) throws MDMAPIException { - MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); + 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."); - throw new BadRequestException(message, responseMediaType); + 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."); - throw new BadRequestException(message, responseMediaType); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); } - CertificateManagementService certificateService = MDMAPIUtils.getCertificateManagementService(); + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); PaginationRequest paginationRequest = new PaginationRequest(startIndex, length); try { PaginationResult certificates = certificateService.getAllCertificates(paginationRequest); @@ -157,7 +159,7 @@ public class Certificate { } catch (CertificateManagementDAOException e) { String msg = "Error occurred while fetching all certificates."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); } } @@ -165,16 +167,16 @@ public class Certificate { @Path("{serialNumber}") public Response removeCertificate(@HeaderParam("Accept") String acceptHeader, @PathParam("serialNumber") String serialNumber) throws MDMAPIException { - MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); + 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."); - throw new BadRequestException(message, responseMediaType); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); } - CertificateManagementService certificateService = MDMAPIUtils.getCertificateManagementService(); + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); boolean deleted; try { deleted = certificateService.removeCertificate(serialNumber); @@ -186,7 +188,7 @@ public class Certificate { } catch (CertificateManagementDAOException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; log.error(msg, e); - return Response.serverError().build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java index eb8a5e1388..ac305b2008 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java @@ -24,14 +24,16 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.MDMAppConstants; import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; -import javax.jws.WebService; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; @@ -40,74 +42,72 @@ import java.util.List; * General Tenant Configuration REST-API implementation. * All end points support JSON, XMl with content negotiation. */ -@WebService -@Produces({ "application/json", "application/xml" }) + +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) @Consumes({ "application/json", "application/xml" }) public class Configuration { private static Log log = LogFactory.getLog(Configuration.class); @POST - public ResponsePayload saveTenantConfiguration(TenantConfiguration configuration) - throws MDMAPIException { - ResponsePayload responseMsg = new ResponsePayload(); - try { - MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, - MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + public Response saveTenantConfiguration(TenantConfiguration configuration) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, + MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); //Schedule the task service - MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration)); - Response.status(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Tenant configuration saved successfully."); + DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration)); + responseMsg.setMessageFromServer("Tenant configuration saved successfully."); responseMsg.setStatusCode(HttpStatus.SC_CREATED); - return responseMsg; - } catch (ConfigurationManagementException e) { + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ConfigurationManagementException e) { String msg = "Error occurred while saving the tenant configuration."; log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @GET - public TenantConfiguration getConfiguration() throws MDMAPIException { - String msg; - try { - TenantConfiguration tenantConfiguration = MDMAPIUtils.getTenantConfigurationManagementService(). - getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + public Response getConfiguration() { + String msg; + try { + TenantConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService(). + getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); ConfigurationEntry configurationEntry = new ConfigurationEntry(); configurationEntry.setContentType("text"); configurationEntry.setName("notifierFrequency"); configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency()); List configList = tenantConfiguration.getConfiguration(); if (configList == null) { - configList = new ArrayList(); - } - configList.add(configurationEntry); - tenantConfiguration.setConfiguration(configList); - return tenantConfiguration; - } catch (ConfigurationManagementException e) { - msg = "Error occurred while retrieving the tenant configuration."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + configList = new ArrayList<>(); + } + configList.add(configurationEntry); + tenantConfiguration.setConfiguration(configList); + return Response.status(Response.Status.OK).entity(tenantConfiguration).build(); + } catch (ConfigurationManagementException e) { + msg = "Error occurred while retrieving the tenant configuration."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @PUT - public ResponsePayload updateConfiguration(TenantConfiguration configuration) throws MDMAPIException { - ResponsePayload responseMsg = new ResponsePayload(); - try { - MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, - MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + public Response updateConfiguration(TenantConfiguration configuration) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, + MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); //Schedule the task service - MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration)); - Response.status(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Tenant configuration updated successfully."); + DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration)); + responseMsg.setMessageFromServer("Tenant configuration updated successfully."); responseMsg.setStatusCode(HttpStatus.SC_CREATED); - return responseMsg; - } catch (ConfigurationManagementException e) { + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ConfigurationManagementException e) { String msg = "Error occurred while updating the tenant configuration."; log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/MobileDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Device.java similarity index 51% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/MobileDevice.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Device.java index f377817473..487c93ada5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/MobileDevice.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Device.java @@ -21,14 +21,20 @@ package org.wso2.carbon.mdm.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; -import javax.ws.rs.*; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @@ -36,25 +42,24 @@ import java.util.List; /** * Device related operations */ -public class MobileDevice { - private static Log log = LogFactory.getLog(MobileDevice.class); +@SuppressWarnings("NonJaxWsWebServices") +public class Device { + private static Log log = LogFactory.getLog(Device.class); /** * Get all devices. We have to use accept all the necessary query parameters sent by datatable. * Hence had to put lot of query params here. * * @return Device List - * @throws MDMAPIException */ @GET - public Object getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user, - @QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status, - @QueryParam("start") int startIdx, @QueryParam("length") int length, - @QueryParam("device-name") String deviceName, - @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership - ) throws MDMAPIException { + public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user, + @QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status, + @QueryParam("start") int startIdx, @QueryParam("length") int length, + @QueryParam("device-name") String deviceName, + @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) { try { - DeviceManagementProviderService service = MDMAPIUtils.getDeviceManagementService(); + DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService(); //Length > 0 means this is a pagination request. if (length > 0) { PaginationRequest paginationRequest = new PaginationRequest(startIdx, length); @@ -67,10 +72,10 @@ public class MobileDevice { paginationRequest.setStatus(status.toString()); } paginationRequest.setDeviceType(type); - return service.getAllDevices(paginationRequest); + return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build(); } - List allDevices = null; + List allDevices; if ((type != null) && !type.isEmpty()) { allDevices = service.getAllDevices(type); } else if ((user != null) && !user.isEmpty()) { @@ -84,11 +89,11 @@ public class MobileDevice { } else { allDevices = service.getAllDevices(); } - return allDevices; + return Response.status(Response.Status.OK).entity(allDevices).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while fetching the device list."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -96,60 +101,75 @@ public class MobileDevice { * Fetch device details for a given device type and device Id. * * @return Device wrapped inside Response - * @throws MDMAPIException */ @GET @Path("view") @Produces({MediaType.APPLICATION_JSON}) public Response getDevice(@QueryParam("type") String type, - @QueryParam("id") String id) throws MDMAPIException { - DeviceIdentifier deviceIdentifier = MDMAPIUtils.instantiateDeviceIdentifier(type, id); - DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); - Device device; + @QueryParam("id") String id) { + DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); + org.wso2.carbon.device.mgt.common.Device device; try { device = deviceManagementProviderService.getDevice(deviceIdentifier); } catch (DeviceManagementException e) { - String error = "Error occurred while fetching the device information."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Error occurred while fetching the device information."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); if (device == null) { responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); responsePayload.setMessageFromServer("Requested device by type: " + type + " and id: " + id + " does not exist."); - return Response.status(HttpStatus.SC_NOT_FOUND).entity(responsePayload).build(); + return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build(); } else { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + "."); responsePayload.setResponseContent(device); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } } /** - * Fetch Android device details of a given user. + * Fetch device details of a given user. * * @param user User Name - * @param tenantDomain tenant domain * @return Device - * @throws MDMAPIException */ @GET - @Path("user/{user}/{tenantDomain}") - public List getDeviceByUser(@PathParam("user") String user, - @PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { - List devices; + @Path("user/{user}") + public Response getDevice(@PathParam("user") String user) { + List devices; try { - devices = MDMAPIUtils.getDeviceManagementService().getDevicesOfUser(user); + devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user); if (devices == null) { - Response.status(Response.Status.NOT_FOUND); + return Response.status(Response.Status.NOT_FOUND).build(); } - return devices; + return Response.status(Response.Status.OK).entity(devices).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the devices list of given user."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Fetch device count of a given user. + * + * @param user User Name + * @return Device + */ + @GET + @Path("user/{user}/count") + public Response getDeviceCount(@PathParam("user") String user) { + try { + Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user); + return Response.status(Response.Status.OK).entity(count).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while fetching the devices list of given user."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -157,17 +177,17 @@ public class MobileDevice { * Get current device count * * @return device count - * @throws MDMAPIException */ @GET @Path("count") - public int getDeviceCount() throws MDMAPIException { + public Response getDeviceCount() { try { - return MDMAPIUtils.getDeviceManagementService().getDeviceCount(); + Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(); + return Response.status(Response.Status.OK).entity(count).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while fetching the device count."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -177,42 +197,38 @@ public class MobileDevice { * @param deviceName Device name * @param tenantDomain Callee tenant domain * @return list of devices. - * @throws MDMAPIException If some unusual behaviour is observed while fetching the device list */ @GET @Path("name/{name}/{tenantDomain}") - public List getDevicesByName(@PathParam("name") String deviceName, - @PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { - - List devices; + public Response getDevicesByName(@PathParam("name") String deviceName, + @PathParam("tenantDomain") String tenantDomain) { + List devices; try { - devices = MDMAPIUtils.getDeviceManagementService().getDevicesByName(deviceName); + devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName); + return Response.status(Response.Status.OK).entity(devices).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while fetching the devices list of device name."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return devices; } /** * Get the list of available device types. * * @return list of device types. - * @throws MDMAPIException If some unusual behaviour is observed while fetching the device list */ @GET @Path("types") - public List getDeviceTypes() throws MDMAPIException { - - List deviceTypes; - try { - deviceTypes = MDMAPIUtils.getDeviceManagementService().getAvailableDeviceTypes(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the list of device types."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - return deviceTypes; - } + public Response getDeviceTypes() { + List deviceTypes; + try { + deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes(); + return Response.status(Response.Status.OK).entity(deviceTypes).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java index c8503d32f3..81fe19e73c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java @@ -19,7 +19,6 @@ package org.wso2.carbon.mdm.api; -import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -27,57 +26,55 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; +@SuppressWarnings("NonJaxWsWebServices") public class DeviceInformation { private static Log log = LogFactory.getLog(DeviceInformation.class); @GET @Path("{type}/{id}") - public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) throws MDMAPIException { + public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) { DeviceInformationManager informationManager; DeviceInfo deviceInfo; try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(id); deviceIdentifier.setType(type); - informationManager = MDMAPIUtils.getDeviceInformationManagerService(); + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); - } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device information."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).entity(deviceInfo).build(); + return Response.status(Response.Status.OK).entity(deviceInfo).build(); } @GET @Path("location/{type}/{id}") - public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) throws MDMAPIException { + public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) { DeviceInformationManager informationManager; DeviceLocation deviceLocation; try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(id); deviceIdentifier.setType(type); - informationManager = MDMAPIUtils.getDeviceInformationManagerService(); + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceLocation = informationManager.getDeviceLocation(deviceIdentifier); - } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device location."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).entity(deviceLocation).build(); + return Response.status(Response.Status.OK).entity(deviceLocation).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java index 9a8567572d..0f85351571 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @@ -21,14 +21,18 @@ package org.wso2.carbon.mdm.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; -import javax.jws.WebService; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import java.util.List; @@ -36,73 +40,70 @@ import java.util.List; * DeviceNotification management REST-API implementation. * All end points support JSON, XMl with content negotiation. */ -@WebService -@Produces({ "application/json", "application/xml" }) +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) @Consumes({ "application/json", "application/xml" }) public class DeviceNotification { private static Log log = LogFactory.getLog(Configuration.class); @GET - public List getNotifications() throws MDMAPIException { - String msg; - try { - return MDMAPIUtils.getNotificationManagementService().getAllNotifications(); - } catch (NotificationManagementException e) { - msg = "Error occurred while retrieving the notification list."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + public Response getNotifications() { + String msg; + try { + List notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications(); + return Response.status(Response.Status.OK).entity(notifications).build(); + } catch (NotificationManagementException e) { + msg = "Error occurred while retrieving the notification list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @GET @Path("{status}") - public List getNotificationsByStatus(@PathParam("status") Notification.Status status) - throws MDMAPIException { - String msg; - try { - return MDMAPIUtils.getNotificationManagementService().getNotificationsByStatus(status); - } catch (NotificationManagementException e) { - msg = "Error occurred while retrieving the notification list."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) { + String msg; + try { + List notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status); + return Response.status(Response.Status.OK).entity(notifications).build(); + } catch (NotificationManagementException e) { + msg = "Error occurred while retrieving the notification list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @PUT @Path("{id}/{status}") - public ResponsePayload updateNotificationStatus(@PathParam("id") int id, - @PathParam("status") Notification.Status status) - throws MDMAPIException{ - ResponsePayload responseMsg = new ResponsePayload(); - try { - MDMAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status); - Response.status(HttpStatus.SC_ACCEPTED); - responseMsg.setMessageFromServer("Notification status updated successfully."); + public Response updateNotificationStatus(@PathParam("id") int id, + @PathParam("status") Notification.Status status) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status); + responseMsg.setMessageFromServer("Notification status updated successfully."); responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED); - return responseMsg; - } catch (NotificationManagementException e) { - String msg = "Error occurred while updating notification status."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build(); + } catch (NotificationManagementException e) { + String msg = "Error occurred while updating notification status."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @POST - public ResponsePayload addNotification(Notification notification) - throws MDMAPIException{ - ResponsePayload responseMsg = new ResponsePayload(); - try { - MDMAPIUtils.getNotificationManagementService().addNotification(notification); - Response.status(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Notification has added successfully."); + public Response addNotification(Notification notification) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification); + responseMsg.setMessageFromServer("Notification has added successfully."); responseMsg.setStatusCode(HttpStatus.SC_CREATED); - return responseMsg; - } catch (NotificationManagementException e) { - String msg = "Error occurred while updating notification status."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (NotificationManagementException e) { + String msg = "Error occurred while updating notification status."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java index ab1bf51943..fc9a7bd3a6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java @@ -19,38 +19,37 @@ package org.wso2.carbon.mdm.api; -import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import javax.ws.rs.GET; import javax.ws.rs.core.Response; import java.util.List; +@SuppressWarnings("NonJaxWsWebServices") public class DeviceSearch { private static Log log = LogFactory.getLog(DeviceSearch.class); @GET - public Response getDeviceInfo(SearchContext searchContext) throws MDMAPIException { + public Response getDeviceInfo(SearchContext searchContext) { SearchManagerService searchManagerService; List devices; try { - searchManagerService = MDMAPIUtils.getSearchManagerService(); + searchManagerService = DeviceMgtAPIUtils.getSearchManagerService(); devices = searchManagerService.search(searchContext); } catch (SearchMgtException e) { String msg = "Error occurred while searching the device information."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).entity(devices).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/mdm/api/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Feature.java index b98baab481..9cd8c305e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Feature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Feature.java @@ -22,15 +22,20 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; import java.util.List; /** * Features */ +@SuppressWarnings("NonJaxWsWebServices") @Produces({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"}) public class Feature { @@ -40,24 +45,21 @@ public class Feature { * Get all features for Mobile Device Type * * @return Feature - * @throws MDMAPIException - * */ @GET @Path("/{type}") - public List getFeatures(@PathParam("type") String type) - throws MDMAPIException { + public Response getFeatures(@PathParam("type") String type) { List features; DeviceManagementProviderService dmService; try { - dmService = MDMAPIUtils.getDeviceManagementService(); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); features = dmService.getFeatureManager(type).getFeatures(); } catch (DeviceManagementException e) { String msg = "Error occurred while retrieving the list of features"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return features; + return Response.status(Response.Status.OK).entity(features).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java new file mode 100644 index 0000000000..8c86419aea --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java @@ -0,0 +1,443 @@ +/* + * 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.mdm.api; + +import org.apache.commons.logging.Log; +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.PaginationResult; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.Date; +import java.util.List; + +@SuppressWarnings("NonJaxWsWebServices") +public class Group { + + private static final String DEFAULT_ADMIN_ROLE = "admin"; + private static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations"; + private static final String DEFAULT_STATS_MONITOR_ROLE = "view-statistics"; + private static final String DEFAULT_VIEW_POLICIES = "view-policies"; + private static final String DEFAULT_MANAGE_POLICIES = "mange-policies"; + private static final String DEFAULT_VIEW_EVENTS = "view-events"; + private static final String[] DEFAULT_ADMIN_PERMISSIONS = {"/permission/device-mgt/admin/groups", + "/permission/device-mgt/user/groups"}; + private static final String[] DEFAULT_OPERATOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_operation"}; + private static final String[] DEFAULT_STATS_MONITOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_monitor"}; + private static final String[] DEFAULT_MANAGE_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/add"}; + private static final String[] DEFAULT_VIEW_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/view"}; + private static final String[] DEFAULT_VIEW_EVENTS_PERMISSIONS = {"/permission/device-mgt/user/groups/device_events"}; + + private static Log log = LogFactory.getLog(Group.class); + + @POST + @Consumes("application/json") + public Response createGroup(DeviceGroup group) { + String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + if (group == null) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + group.setOwner(owner); + group.setDateOfCreation(new Date().getTime()); + group.setDateOfLastUpdate(new Date().getTime()); + try { + GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); + groupManagementService.createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, + DEFAULT_OPERATOR_ROLE, + DEFAULT_OPERATOR_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_STATS_MONITOR_ROLE, + DEFAULT_STATS_MONITOR_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_POLICIES, + DEFAULT_VIEW_POLICIES_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_MANAGE_POLICIES, + DEFAULT_MANAGE_POLICIES_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_EVENTS, + DEFAULT_VIEW_EVENTS_PERMISSIONS); + return Response.status(Response.Status.CREATED).build(); + } catch (GroupAlreadyEixistException e) { + return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/{owner}/{groupName}") + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + DeviceGroup deviceGroup) { + try { + DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner); + return Response.status(Response.Status.OK).build(); + } catch (GroupManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/{owner}/{groupName}") + @DELETE + public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner); + return Response.status(Response.Status.OK).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @GET + @Produces("application/json") + public Response getGroups(@QueryParam("start") int startIndex, @PathParam("rowCount") int rowCount) { + try { + PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(startIndex, rowCount); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/user/{user}") + @GET + @Produces("application/json") + public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex, + @QueryParam("rowCount") int rowCount) { + try { + PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(userName, startIndex, rowCount); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/{owner}/{groupName}") + @GET + @Produces("application/json") + public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner); + if (deviceGroup != null) { + return Response.status(Response.Status.OK).entity(deviceGroup).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/search") + @GET + @Produces("application/json") + public Response findGroups(@QueryParam("groupName") String groupName, + @QueryParam("userName") String userName) { + try { + List groups = DeviceMgtAPIUtils.getGroupManagementProviderService() + .findInGroups(groupName, userName); + DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; + groups.toArray(deviceGroups); + return Response.status(Response.Status.OK).entity(deviceGroups).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/user/{user}/all") + @GET + @Produces("application/json") + public Response getGroups(@PathParam("user") String userName, + @QueryParam("permission") String permission) { + try { + GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); + List groups; + if (permission != null) { + groups = groupManagementService.getGroups(userName, permission); + } else { + groups = groupManagementService.getGroups(userName); + } + DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; + groups.toArray(deviceGroups); + return Response.status(Response.Status.OK).entity(deviceGroups).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/user/{user}/count") + @GET + @Produces("application/json") + public Response getGroupCount(@PathParam("user") String userName) { + try { + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/{owner}/{groupName}/share") + @PUT + @Produces("application/json") + public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @FormParam("shareUser") String shareUser, + @FormParam("roleName") String sharingRole) { + + try { + boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup( + shareUser, groupName, owner, sharingRole); + if (isShared) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/{owner}/{groupName}/unshare") + @PUT + @Produces("application/json") + public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @FormParam("unShareUser") String unShareUser, + @FormParam("roleName") String sharingRole) { + try { + boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup( + unShareUser, groupName, owner, sharingRole); + if (isUnShared) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Path("/{owner}/{groupName}/share/roles/{roleName}/permissions") + @PUT + @Produces("application/json") + public Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName, + @PathParam("owner") String owner, + @PathParam("roleName") String roleName, + @FormParam("permissions") String[] permissions) { + + try { + boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole( + shareUser, groupName, owner, roleName, permissions); + if (isAdded) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @DELETE + @Path("/{owner}/{groupName}/share/roles/{roleName}/permissions") + @Produces("application/json") + public Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName, + @PathParam("owner") String owner, + @PathParam("roleName") String roleName) { + try { + boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole( + groupName, owner, roleName); + if (isRemoved) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @GET + @Path("/{owner}/{groupName}/share/roles") + @Produces("application/json") + public Response getRoles(@PathParam("groupName") String groupName, + @PathParam("owner") String owner, @QueryParam("userName") String userName) { + try { + List roles; + if (userName != null && !userName.isEmpty()) { + roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner); + } else { + roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner); + } + String[] rolesArray = new String[roles.size()]; + roles.toArray(rolesArray); + return Response.status(Response.Status.OK).entity(rolesArray).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @GET + @Path("/{owner}/{groupName}/users") + @Produces("application/json") + public Response getUsers(@PathParam("groupName") String groupName, + @PathParam("owner") String owner) { + try { + List users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers( + groupName, owner); + GroupUser[] usersArray = new GroupUser[users.size()]; + users.toArray(usersArray); + return Response.status(Response.Status.OK).entity(usersArray).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @GET + @Path("/{owner}/{groupName}/devices/all") + @Produces("application/json") + public Response getDevices(@PathParam("groupName") String groupName, + @PathParam("owner") String owner) { + try { + List devices = DeviceMgtAPIUtils.getGroupManagementProviderService().getDevices( + groupName, owner); + Device[] deviceArray = new Device[devices.size()]; + devices.toArray(deviceArray); + return Response.status(Response.Status.OK).entity(deviceArray).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @GET + @Path("/{owner}/{groupName}/devices/count") + @Produces("application/json") + public Response getDeviceCount(@PathParam("groupName") String groupName, + @PathParam("owner") String owner) { + try { + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @PUT + @Path("/{owner}/{groupName}/devices/{deviceType}/{deviceId}") + @Produces("application/json") + public Response addDevice(@PathParam("groupName") String groupName, + @PathParam("owner") String owner, @PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType, + @FormParam("userName") String userName) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); + boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice( + deviceIdentifier, groupName, owner); + if (isAdded) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @DELETE + @Path("/{owner}/{groupName}/devices/{deviceType}/{deviceId}") + @Produces("application/json") + public Response removeDevice(@PathParam("groupName") String groupName, + @PathParam("owner") String owner, @PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); + boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice( + deviceIdentifier, groupName, owner); + if (isRemoved) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @GET + @Path("/{owner}/{groupName}/users/{userName}/permissions") + @Produces("application/json") + public Response getPermissions(@PathParam("userName") String userName, + @PathParam("groupName") String groupName, + @PathParam("owner") String owner) { + try { + String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getPermissions(userName, groupName, owner); + return Response.status(Response.Status.OK).entity(permissions).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java index 1b1e6c3d0f..fbf0badc9a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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 + * "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. */ @@ -22,17 +22,21 @@ import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; -import javax.ws.rs.*; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * This class represents license related operations. */ +@SuppressWarnings("NonJaxWsWebServices") public class License { private static Log log = LogFactory.getLog(License.class); @@ -43,18 +47,17 @@ public class License { * @param deviceType Device type, ex: android, ios * @param languageCode Language code, ex: en_US * @return Returns the license text - * @throws MDMAPIException If the device type or language code arguments are not available or invalid. */ @GET @Path ("{deviceType}/{languageCode}") @Produces ({MediaType.APPLICATION_JSON}) public Response getLicense(@PathParam ("deviceType") String deviceType, - @PathParam ("languageCode") String languageCode) throws MDMAPIException { + @PathParam("languageCode") String languageCode) { org.wso2.carbon.device.mgt.common.license.mgt.License license; - ResponsePayload responsePayload = new ResponsePayload(); + ResponsePayload responsePayload; try { - license = MDMAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode); + license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode); if (license == null) { return Response.status(HttpStatus.SC_NOT_FOUND).build(); } @@ -65,9 +68,9 @@ public class License { } catch (DeviceManagementException e) { String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** @@ -76,24 +79,23 @@ public class License { * @param deviceType Device type, ex: android, ios * @param license License object * @return Returns the acknowledgement for the action - * @throws MDMAPIException */ @POST @Path ("{deviceType}") public Response addLicense(@PathParam ("deviceType") String deviceType, - org.wso2.carbon.device.mgt.common.license.mgt.License license) throws MDMAPIException { + org.wso2.carbon.device.mgt.common.license.mgt.License license) { ResponsePayload responsePayload; try { - MDMAPIUtils.getDeviceManagementService().addLicense(deviceType, license); + DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license); responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK). messageFromServer("License added successfully for '" + deviceType + "' device type"). build(); } catch (DeviceManagementException e) { String msg = "Error occurred while adding license for '" + deviceType + "' device type"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java index 84e88c92a3..50b141aa30 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java @@ -33,50 +33,54 @@ import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderServ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.context.DeviceOperationContext; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.MDMAndroidOperationUtil; import org.wso2.carbon.mdm.api.util.MDMIOSOperationUtil; import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.beans.ApplicationWrapper; import org.wso2.carbon.mdm.beans.MobileApp; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; -import java.util.ArrayList; import java.util.List; /** * Operation related REST-API implementation. */ +@SuppressWarnings("NonJaxWsWebServices") @Produces({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"}) public class Operation { private static Log log = LogFactory.getLog(Operation.class); + /* @deprecated */ @GET - public List getAllOperations() - throws MDMAPIException { + public Response getAllOperations() { List operations; DeviceManagementProviderService dmService; try { - dmService = MDMAPIUtils.getDeviceManagementService(); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); operations = dmService.getOperations(null); } catch (OperationManagementException e) { String msg = "Error occurred while fetching the operations for the device."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return operations; + return Response.status(Response.Status.OK).entity(operations).build(); } @GET @Path("paginate/{type}/{id}") - public PaginationResult getDeviceOperations( - @PathParam("type") String type, @PathParam("id") String id, @QueryParam("start") int startIdx, - @QueryParam("length") int length, @QueryParam("search") String search) - throws MDMAPIException { + public Response getDeviceOperations( + @PathParam("type") String type, @PathParam("id") String id, @QueryParam("start") int startIdx, + @QueryParam("length") int length, @QueryParam("search") String search) { PaginationResult operations; DeviceManagementProviderService dmService; DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); @@ -84,147 +88,133 @@ public class Operation { try { deviceIdentifier.setType(type); deviceIdentifier.setId(id); - dmService = MDMAPIUtils.getDeviceManagementService(); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); operations = dmService.getOperations(deviceIdentifier, paginationRequest); } catch (OperationManagementException e) { String msg = "Error occurred while fetching the operations for the device."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return operations; + return Response.status(Response.Status.OK).entity(operations).build(); } - @GET - @Path("{type}/{id}") - public List getDeviceOperations( - @PathParam("type") String type, @PathParam("id") String id) - throws MDMAPIException { - List operations; - DeviceManagementProviderService dmService; - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - try { - deviceIdentifier.setType(type); - deviceIdentifier.setId(id); - dmService = MDMAPIUtils.getDeviceManagementService(); - operations = dmService.getOperations(deviceIdentifier); - } catch (OperationManagementException e) { - String msg = "Error occurred while fetching the operations for the device."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - return operations; - } + @GET + @Path("{type}/{id}") + public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) { + List operations; + DeviceManagementProviderService dmService; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + try { + deviceIdentifier.setType(type); + deviceIdentifier.setId(id); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + operations = dmService.getOperations(deviceIdentifier); + } catch (OperationManagementException e) { + String msg = "Error occurred while fetching the operations for the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(operations).build(); + } /* @deprecated */ @POST - public ResponsePayload addOperation(DeviceOperationContext operationContext) throws MDMAPIException { + public Response addOperation(DeviceOperationContext operationContext) { DeviceManagementProviderService dmService; ResponsePayload responseMsg = new ResponsePayload(); try { - dmService = MDMAPIUtils.getDeviceManagementService(); - int operationId = dmService.addOperation(operationContext.getOperation(), - operationContext.getDevices()); - if (operationId>0) { - Response.status(HttpStatus.SC_CREATED); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + int operationId = dmService.addOperation(operationContext.getOperation(), operationContext.getDevices()); + if (operationId > 0) { + responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Operation has added successfully."); } - return responseMsg; + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); } catch (OperationManagementException e) { String msg = "Error occurred while saving the operation"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - @GET - @Path("{type}/{id}/apps") - public List getInstalledApps( - @PathParam("type") String type, - @PathParam("id") String id) - throws MDMAPIException { - List applications; - ApplicationManagementProviderService appManagerConnector; - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - try { - deviceIdentifier.setType(type); - deviceIdentifier.setId(id); - appManagerConnector = MDMAPIUtils.getAppManagementService(); - applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while fetching the apps of the device."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - return applications; - } + @GET + @Path("{type}/{id}/apps") + public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) { + List applications; + ApplicationManagementProviderService appManagerConnector; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + try { + deviceIdentifier.setType(type); + deviceIdentifier.setId(id); + appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); + applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while fetching the apps of the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.CREATED).entity(applications).build(); + } @POST @Path("installApp/{tenantDomain}") - public ResponsePayload installApplication(ApplicationWrapper applicationWrapper, - @PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { + public Response installApplication(ApplicationWrapper applicationWrapper, + @PathParam("tenantDomain") String tenantDomain) { ResponsePayload responseMsg = new ResponsePayload(); ApplicationManager appManagerConnector; org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; - ArrayList deviceIdentifiers; try { - appManagerConnector = MDMAPIUtils.getAppManagementService(); + appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); MobileApp mobileApp = applicationWrapper.getApplication(); if (applicationWrapper.getDeviceIdentifiers() != null) { for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { - deviceIdentifiers = new ArrayList(); - if (deviceIdentifier.getType().equals(Platform.android.toString())) { operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp); } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp); } - deviceIdentifiers.add(deviceIdentifier); } appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } - Response.status(HttpStatus.SC_CREATED); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Application installation request has been sent to the device."); - return responseMsg; - } catch (ApplicationManagementException e) { + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ApplicationManagementException | MDMAPIException e) { String msg = "Error occurred while saving the operation"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @POST @Path("uninstallApp/{tenantDomain}") - public ResponsePayload uninstallApplication(ApplicationWrapper applicationWrapper, - @PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { + public Response uninstallApplication(ApplicationWrapper applicationWrapper, + @PathParam("tenantDomain") String tenantDomain) { ResponsePayload responseMsg = new ResponsePayload(); ApplicationManager appManagerConnector; org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; - ArrayList deviceIdentifiers; try { - appManagerConnector = MDMAPIUtils.getAppManagementService(); + appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); MobileApp mobileApp = applicationWrapper.getApplication(); if (applicationWrapper.getDeviceIdentifiers() != null) { for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { - deviceIdentifiers = new ArrayList(); - if (deviceIdentifier.getType().equals(Platform.android.toString())) { operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp); } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp); } - deviceIdentifiers.add(deviceIdentifier); } appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } - Response.status(HttpStatus.SC_CREATED); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Application removal request has been sent to the device."); - return responseMsg; - } catch (ApplicationManagementException e) { + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ApplicationManagementException | MDMAPIException e) { String msg = "Error occurred while saving the operation"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java index c0dd24d142..4878b32f9e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java @@ -23,7 +23,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.beans.PolicyWrapper; import org.wso2.carbon.mdm.beans.PriorityUpdatedPolicyWrapper; @@ -36,20 +36,27 @@ import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; +@SuppressWarnings("NonJaxWsWebServices") public class Policy { private static Log log = LogFactory.getLog(Policy.class); @POST @Path("inactive-policy") - public ResponsePayload addPolicy(PolicyWrapper policyWrapper) throws MDMAPIException { + public Response addPolicy(PolicyWrapper policyWrapper) { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); ResponsePayload responseMsg = new ResponsePayload(); org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); policy.setPolicyName(policyWrapper.getPolicyName()); @@ -62,25 +69,14 @@ public class Policy { policy.setTenantId(policyWrapper.getTenantId()); policy.setCompliance(policyWrapper.getCompliance()); - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - pap.addPolicy(policy); - Response.status(HttpStatus.SC_CREATED); - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Policy has been added successfully."); - return responseMsg; - } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); - } + return addPolicy(policyManagementService, responseMsg, policy); } @POST @Path("active-policy") - public ResponsePayload addActivePolicy(PolicyWrapper policyWrapper) throws MDMAPIException { + public Response addActivePolicy(PolicyWrapper policyWrapper) { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); ResponsePayload responseMsg = new ResponsePayload(); org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); policy.setPolicyName(policyWrapper.getPolicyName()); @@ -94,87 +90,91 @@ public class Policy { policy.setCompliance(policyWrapper.getCompliance()); policy.setActive(true); + return addPolicy(policyManagementService, responseMsg, policy); + } + + private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg, + org.wso2.carbon.policy.mgt.common.Policy policy) { try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); pap.addPolicy(policy); - Response.status(HttpStatus.SC_CREATED); responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Policy has been added successfully."); - return responseMsg; + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @GET @Produces({MediaType.APPLICATION_JSON}) - public Response getAllPolicies() throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + public Response getAllPolicies() { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); List policies; try { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); policies = policyAdministratorPoint.getPolicies(); } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Sending all retrieved device policies."); responsePayload.setResponseContent(policies); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @GET @Produces({MediaType.APPLICATION_JSON}) @Path("{id}") - public Response getPolicy(@PathParam("id") int policyId) throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + public Response getPolicy(@PathParam("id") int policyId) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); final org.wso2.carbon.policy.mgt.common.Policy policy; try { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); policy = policyAdministratorPoint.getPolicy(policyId); } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } if (policy == null){ ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); responsePayload.setMessageFromServer("Policy for ID " + policyId + " not found."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Sending all retrieved device policies."); responsePayload.setResponseContent(policy); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @GET @Path("count") - public int getPolicyCount() throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + public Response getPolicyCount() { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); try { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); - return policyAdministratorPoint.getPolicyCount(); + Integer count = policyAdministratorPoint.getPolicyCount(); + return Response.status(Response.Status.OK).entity(count).build(); } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @PUT @Path("{id}") - public ResponsePayload updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) - throws MDMAPIException { + public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); ResponsePayload responseMsg = new ResponsePayload(); org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); policy.setPolicyName(policyWrapper.getPolicyName()); @@ -191,14 +191,13 @@ public class Policy { try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); pap.updatePolicy(policy); - Response.status(HttpStatus.SC_OK); responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Policy has been updated successfully."); - return responseMsg; + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); } catch (PolicyManagementException e) { - String error = "Policy Management related exception in policy update."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception in policy update."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -206,11 +205,10 @@ public class Policy { @Path("priorities") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response updatePolicyPriorities(List priorityUpdatedPolicies) - throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + public Response updatePolicyPriorities(List priorityUpdatedPolicies) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); List policiesToUpdate = - new ArrayList(priorityUpdatedPolicies.size()); + new ArrayList<>(priorityUpdatedPolicies.size()); int i; for (i = 0; i < priorityUpdatedPolicies.size(); i++) { org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy(); @@ -223,19 +221,19 @@ public class Policy { PolicyAdministratorPoint pap = policyManagementService.getPAP(); policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate); } catch (PolicyManagementException e) { - String error = "Exception in updating policy priorities."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Exception in updating policy priorities."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); if (policiesUpdated) { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Policy Priorities successfully updated."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } else { responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer("Policy priorities did not update. Bad Request."); - return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } } @@ -243,8 +241,8 @@ public class Policy { @Path("bulk-remove") @Consumes("application/json") @Produces("application/json") - public Response bulkRemovePolicy(List policyIds) throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + public Response bulkRemovePolicy(List policyIds) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); boolean policyDeleted = true; try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); @@ -255,43 +253,42 @@ public class Policy { } } } catch (PolicyManagementException e) { - String error = "Exception in deleting policies."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Exception in deleting policies."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); if (policyDeleted) { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Policies have been successfully deleted."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } else { responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer("Policy does not exist."); - return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } } @PUT @Produces("application/json") @Path("activate") - public Response activatePolicy(List policyIds) throws MDMAPIException { + public Response activatePolicy(List policyIds) { try { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyAdministratorPoint pap = policyManagementService.getPAP(); for(int i : policyIds) { pap.activatePolicy(i); } } catch (PolicyManagementException e) { - String error = "Exception in activating policies."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Exception in activating policies."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Selected policies have been successfully activated."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); - + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @PUT @@ -300,132 +297,134 @@ public class Policy { public Response inactivatePolicy(List policyIds) throws MDMAPIException { try { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyAdministratorPoint pap = policyManagementService.getPAP(); for(int i : policyIds) { pap.inactivatePolicy(i); } } catch (PolicyManagementException e) { - String error = "Exception in inactivating policies."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Exception in inactivating policies."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Selected policies have been successfully inactivated."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @PUT @Produces("application/json") @Path("apply-changes") - public Response applyChanges() throws MDMAPIException { + public Response applyChanges() { try { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyAdministratorPoint pap = policyManagementService.getPAP(); pap.publishChanges(); } catch (PolicyManagementException e) { - String error = "Exception in applying changes."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Exception in applying changes."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Changes have been successfully updated."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @GET @Path("start-task/{milliseconds}") - public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) throws MDMAPIException { + public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); try { TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); taskScheduleService.startTask(monitoringFrequency); } catch (PolicyMonitoringTaskException e) { - String error = "Policy Management related exception."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Policy monitoring service started successfully."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @GET @Path("update-task/{milliseconds}") - public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) throws MDMAPIException { + public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); try { TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); taskScheduleService.updateTask(monitoringFrequency); } catch (PolicyMonitoringTaskException e) { - String error = "Policy Management related exception."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Policy monitoring service updated successfully."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @GET @Path("stop-task") - public Response stopTaskService() throws MDMAPIException { + public Response stopTaskService() { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); try { TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); taskScheduleService.stopTask(); } catch (PolicyMonitoringTaskException e) { - String error = "Policy Management related exception."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Policy Management related exception."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Policy monitoring service stopped successfully."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } @GET @Path("{type}/{id}") - public ComplianceData getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) throws - MDMAPIException { + public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) { try { - DeviceIdentifier deviceIdentifier = MDMAPIUtils.instantiateDeviceIdentifier(type, id); - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); - return policyManagementService.getDeviceCompliance(deviceIdentifier); + DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier); + return Response.status(Response.Status.OK).entity(complianceData).build(); } catch (PolicyComplianceException e) { - String error = "Error occurred while getting the compliance data."; - log.error(error, e); - throw new MDMAPIException(error, e); + String msg = "Error occurred while getting the compliance data."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @GET @Path("{type}/{id}/active-policy") - public org.wso2.carbon.policy.mgt.common.Policy getDeviceActivePolicy(@PathParam("type") String type, - @PathParam("id") String id) throws MDMAPIException { - try { - DeviceIdentifier deviceIdentifier = MDMAPIUtils.instantiateDeviceIdentifier(type, id); - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); - return policyManagementService.getAppliedPolicyToDevice(deviceIdentifier); - } catch (PolicyManagementException e) { - String error = "Error occurred while getting the current policy."; - log.error(error, e); - throw new MDMAPIException(error, e); - } - } + public Response getDeviceActivePolicy(@PathParam("type") String type, + @PathParam("id") String id) { + try { + DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService + .getAppliedPolicyToDevice(deviceIdentifier); + return Response.status(Response.Status.OK).entity(policy).build(); + } catch (PolicyManagementException e) { + String msg = "Error occurred while getting the current policy."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java index 4cf216ec6a..77569a649c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,17 +11,16 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.mdm.api; -import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; @@ -33,57 +32,55 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; +@SuppressWarnings("NonJaxWsWebServices") public class Profile { private static Log log = LogFactory.getLog(Profile.class); @POST - public org.wso2.carbon.policy.mgt.common.Profile addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); - try { + public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); profile = pap.addProfile(profile); - Response.status(HttpStatus.SC_CREATED); - return profile; - } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); - } - } + return Response.status(Response.Status.OK).entity(profile).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @POST @Path("{id}") - public ResponsePayload updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile, @PathParam("id") String profileId) - throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); + public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile, + @PathParam("id") String profileId) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); pap.updateProfile(profile); - Response.status(HttpStatus.SC_OK); responseMsg.setMessageFromServer("Profile has been updated successfully."); - return responseMsg; - } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); - } - } + return Response.status(Response.Status.OK).entity(responseMsg).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } @DELETE @Path("{id}") - public ResponsePayload deleteProfile(@PathParam("id") int profileId) throws MDMAPIException { - PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); + public Response deleteProfile(@PathParam("id") int profileId) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId); pap.deleteProfile(profile); - Response.status(HttpStatus.SC_OK); responseMsg.setMessageFromServer("Profile has been deleted successfully."); - return responseMsg; - } catch (PolicyManagementException e) { - String error = "Policy Management related exception"; - log.error(error, e); - throw new MDMAPIException(error, e); - } - } + return Response.status(Response.Status.OK).entity(responseMsg).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java index f0157ef4e9..d0e434c34f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java @@ -24,23 +24,35 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.beans.RoleWrapper; import org.wso2.carbon.mdm.util.SetReferenceTransformer; -import org.wso2.carbon.user.api.*; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.mgt.UserRealmProxy; import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UserAdminException; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +@SuppressWarnings("NonJaxWsWebServices") public class Role { private static Log log = LogFactory.getLog(Role.class); @@ -49,63 +61,49 @@ public class Role { * Get user roles (except all internal roles) from system. * * @return A list of users - * @throws MDMAPIException */ @GET - @Produces ({MediaType.APPLICATION_JSON}) - public Response getRoles() throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); - String[] roles; + @Produces({MediaType.APPLICATION_JSON}) + public Response getRoles() { + List filteredRoles; try { - if (log.isDebugEnabled()) { - log.debug("Getting the list of user roles"); - } - roles = userStoreManager.getRoleNames(); - - } catch (UserStoreException e) { - String msg = "Error occurred while retrieving the list of user roles."; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList(); - for (String role : roles) { - if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { - filteredRoles.add(role); - } + filteredRoles = getRolesFromUserStore(); + } catch (MDMAPIException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("All user roles were successfully retrieved."); responsePayload.setResponseContent(filteredRoles); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** * Get user roles by user store(except all internal roles) from system. * * @return A list of users - * @throws MDMAPIException */ @GET - @Path ("{userStore}") - @Produces ({MediaType.APPLICATION_JSON}) - public Response getRoles(@PathParam ("userStore") String userStore) throws MDMAPIException { - AbstractUserStoreManager abstractUserStoreManager = (AbstractUserStoreManager) MDMAPIUtils.getUserStoreManager(); + @Path("{userStore}") + @Produces({MediaType.APPLICATION_JSON}) + public Response getRoles(@PathParam("userStore") String userStore) { String[] roles; try { + AbstractUserStoreManager abstractUserStoreManager = + (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { log.debug("Getting the list of user roles"); } - roles = abstractUserStoreManager.getRoleNames(userStore+"/*", -1, false, true, true); + roles = abstractUserStoreManager.getRoleNames(userStore + "/*", -1, false, true, true); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of user roles."; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList(); + List filteredRoles = new ArrayList<>(); for (String role : roles) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { filteredRoles.add(role); @@ -115,34 +113,34 @@ public class Role { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("All user roles were successfully retrieved."); responsePayload.setResponseContent(filteredRoles); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** * Get user roles by providing a filtering criteria(except all internal roles & system roles) from system. * * @return A list of users - * @throws MDMAPIException */ @GET - @Path ("search") - @Produces ({MediaType.APPLICATION_JSON}) - public Response getMatchingRoles(@QueryParam ("filter") String filter) throws MDMAPIException { - AbstractUserStoreManager abstractUserStoreManager = (AbstractUserStoreManager) MDMAPIUtils.getUserStoreManager(); + @Path("search") + @Produces({MediaType.APPLICATION_JSON}) + public Response getMatchingRoles(@QueryParam("filter") String filter) { String[] roles; try { + AbstractUserStoreManager abstractUserStoreManager = + (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { log.debug("Getting the list of user roles using filter : " + filter); } roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList(); + List filteredRoles = new ArrayList<>(); for (String role : roles) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { filteredRoles.add(role); @@ -152,74 +150,57 @@ public class Role { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("All matching user roles were successfully retrieved."); responsePayload.setResponseContent(filteredRoles); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** * Get role permissions. * * @return list of permissions - * @throws MDMAPIException */ @GET - @Path ("permissions") - @Produces ({MediaType.APPLICATION_JSON}) - public ResponsePayload getPermissions(@QueryParam ("rolename") String roleName) throws MDMAPIException { - final UserRealm userRealm = MDMAPIUtils.getUserRealm(); - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - final UIPermissionNode rolePermissions; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; - } - + @Path("permissions") + @Produces({MediaType.APPLICATION_JSON}) + public Response getPermissions(@QueryParam("rolename") String roleName) { try { - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - rolePermissions = userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); - UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; - - for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { - if (permissionNode.getResourcePath().equals("/permission/admin")) { - for (UIPermissionNode node : permissionNode.getNodeList()) { - if (node.getResourcePath().equals("/permission/admin/device-mgt")) { - deviceMgtPermissions[0] = node; - } else if (node.getResourcePath().equals("/permission/admin/login")) { - deviceMgtPermissions[1] = node; - } - } - } + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + org.wso2.carbon.user.core.UserRealm userRealmCore = null; + final UIPermissionNode rolePermissions; + if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { + userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; } - rolePermissions.setNodeList(deviceMgtPermissions); - } catch (UserAdminException e) { + final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); + rolePermissions = getUIPermissionNode(roleName, userRealmProxy); + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("All permissions retrieved"); + responsePayload.setResponseContent(rolePermissions); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } catch (UserAdminException | MDMAPIException e) { String msg = "Error occurred while retrieving the user role"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("All permissions retrieved"); - responsePayload.setResponseContent(rolePermissions); - return responsePayload; } /** * Get user role of the system * * @return user role - * @throws MDMAPIException */ @GET @Path("role") - @Produces ({MediaType.APPLICATION_JSON}) - public ResponsePayload getRole(@QueryParam ("rolename") String roleName) throws MDMAPIException { - final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); - final UserRealm userRealm = MDMAPIUtils.getUserRealm(); - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; - } - + @Produces({MediaType.APPLICATION_JSON}) + public Response getRole(@QueryParam("rolename") String roleName) { RoleWrapper roleWrapper = new RoleWrapper(); try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + org.wso2.carbon.user.core.UserRealm userRealmCore = null; + if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { + userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; + } + final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); if (log.isDebugEnabled()) { log.debug("Getting the list of user roles"); @@ -228,56 +209,57 @@ public class Role { roleWrapper.setRoleName(roleName); roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName)); // Get the permission nodes and hand picking only device management and login perms - final UIPermissionNode rolePermissions = - userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); - UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; - - for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { - if (permissionNode.getResourcePath().equals("/permission/admin")) { - for (UIPermissionNode node : permissionNode.getNodeList()) { - if (node.getResourcePath().equals("/permission/admin/device-mgt")) { - deviceMgtPermissions[0] = node; - } else if (node.getResourcePath().equals("/permission/admin/login")) { - deviceMgtPermissions[1] = node; - } - } - } - } - rolePermissions.setNodeList(deviceMgtPermissions); - ArrayList permList = new ArrayList(); + final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy); + ArrayList permList = new ArrayList<>(); iteratePermissions(rolePermissions, permList); roleWrapper.setPermissionList(rolePermissions); String[] permListAr = new String[permList.size()]; roleWrapper.setPermissions(permList.toArray(permListAr)); } - } catch (UserStoreException e) { + } catch (UserStoreException | UserAdminException | MDMAPIException e) { String msg = "Error occurred while retrieving the user role"; log.error(msg, e); - throw new MDMAPIException(msg, e); - } catch (UserAdminException e) { - String msg = "Error occurred while retrieving the user role"; - log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("All user roles were successfully retrieved."); responsePayload.setResponseContent(roleWrapper); - return responsePayload; + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy) + throws UserAdminException { + final UIPermissionNode rolePermissions = + userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); + UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; + + for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { + if (permissionNode.getResourcePath().equals("/permission/admin")) { + for (UIPermissionNode node : permissionNode.getNodeList()) { + if (node.getResourcePath().equals("/permission/admin/device-mgt")) { + deviceMgtPermissions[0] = node; + } else if (node.getResourcePath().equals("/permission/admin/login")) { + deviceMgtPermissions[1] = node; + } + } + } + } + rolePermissions.setNodeList(deviceMgtPermissions); + return rolePermissions; } /** * API is used to persist a new Role * - * @param roleWrapper - * @return - * @throws MDMAPIException + * @param roleWrapper for role + * @return response */ @POST - @Produces ({MediaType.APPLICATION_JSON}) - public Response addRole(RoleWrapper roleWrapper) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + @Produces({MediaType.APPLICATION_JSON}) + public Response addRole(RoleWrapper roleWrapper) { try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { log.debug("Persisting the role to user store"); } @@ -291,29 +273,27 @@ public class Role { } } userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = e.getMessage(); log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_CREATED).build(); + return Response.status(Response.Status.OK).build(); } /** * API is used to update a role Role * - * @param roleWrapper - * @return - * @throws MDMAPIException + * @param roleWrapper for role + * @return response */ @PUT - @Produces ({MediaType.APPLICATION_JSON}) - public Response updateRole(@QueryParam ("rolename") String roleName, RoleWrapper roleWrapper) throws - MDMAPIException { - final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); - final AuthorizationManager authorizationManager = MDMAPIUtils.getAuthorizationManager(); + @Produces({MediaType.APPLICATION_JSON}) + public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) { String newRoleName = roleWrapper.getRoleName(); try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); if (log.isDebugEnabled()) { log.debug("Updating the role to user store"); } @@ -321,13 +301,13 @@ public class Role { userStoreManager.updateRoleName(roleName, newRoleName); } if (roleWrapper.getUsers() != null) { - SetReferenceTransformer transformer = new SetReferenceTransformer(); + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)), Arrays.asList(roleWrapper.getUsers())); - final String[] usersToAdd = (String[]) - transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); - final String[] usersToDelete = (String[]) - transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); + final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer + .getObjectsToAdd().size()]); + final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer + .getObjectsToRemove().size()]); userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); } if (roleWrapper.getPermissions() != null) { @@ -340,77 +320,74 @@ public class Role { } } } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = e.getMessage(); log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).build(); + return Response.status(Response.Status.OK).build(); } /** * API is used to delete a role and authorizations * - * @param roleName - * @return - * @throws MDMAPIException + * @param roleName to delete + * @return response */ @DELETE - @Produces ({MediaType.APPLICATION_JSON}) - public Response deleteRole(@QueryParam ("rolename") String roleName) throws MDMAPIException { - final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); - final AuthorizationManager authorizationManager = MDMAPIUtils.getAuthorizationManager(); + @Produces({MediaType.APPLICATION_JSON}) + public Response deleteRole(@QueryParam("rolename") String roleName) { try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); if (log.isDebugEnabled()) { log.debug("Deleting the role in user store"); } userStoreManager.deleteRole(roleName); // Delete all authorizations for the current role before deleting authorizationManager.clearRoleAuthorization(roleName); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while deleting the role: " + roleName; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).build(); + return Response.status(Response.Status.OK).build(); } /** * API is used to update users of a role * - * @param roleName - * @param userList - * @return - * @throws MDMAPIException + * @param roleName to update + * @param userList of the users + * @return response */ @PUT - @Path ("users") - @Produces ({MediaType.APPLICATION_JSON}) - public Response updateUsers(@QueryParam ("rolename") String roleName, List userList) - throws MDMAPIException { - final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + @Path("users") + @Produces({MediaType.APPLICATION_JSON}) + public Response updateUsers(@QueryParam("rolename") String roleName, List userList) { try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { log.debug("Updating the users of a role"); } - SetReferenceTransformer transformer = new SetReferenceTransformer(); + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)), - userList); - final String[] usersToAdd = (String[]) - transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); - final String[] usersToDelete = (String[]) - transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); + userList); + final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer + .getObjectsToAdd().size()]); + final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer + .getObjectsToRemove().size()]); userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while saving the users of the role: " + roleName; log.error(msg, e); - throw new MDMAPIException(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).build(); + return Response.status(Response.Status.OK).build(); } - public ArrayList iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList list) { + private ArrayList iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList list) { for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) { list.add(permissionNode.getResourcePath()); if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) { @@ -424,12 +401,22 @@ public class Role { * This method is used to retrieve the role count of the system. * * @return returns the count. - * @throws MDMAPIException */ @GET @Path("count") - public int getRoleCount() throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response getRoleCount() { + try { + List filteredRoles = getRolesFromUserStore(); + Integer count = filteredRoles.size(); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (MDMAPIException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); + } + } + + private List getRolesFromUserStore() throws MDMAPIException { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); String[] roles; try { if (log.isDebugEnabled()) { @@ -439,16 +426,15 @@ public class Role { } catch (UserStoreException e) { String msg = "Error occurred while retrieving the list of user roles."; - log.error(msg, e); throw new MDMAPIException(msg, e); } // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList(); + List filteredRoles = new ArrayList<>(); for (String role : roles) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { filteredRoles.add(role); } } - return filteredRoles.size(); + return filteredRoles; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java index e1e065c1b3..bbfed9dad8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java @@ -30,7 +30,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.util.CredentialManagementResponseBuilder; -import org.wso2.carbon.mdm.api.util.MDMAPIUtils; +import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.beans.UserCredentialWrapper; import org.wso2.carbon.mdm.beans.UserWrapper; @@ -52,30 +52,38 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Random; +import java.util.TreeSet; /** * This class represents the JAX-RS services of User related functionality. */ +@SuppressWarnings("NonJaxWsWebServices") public class User { - private static Log log = LogFactory.getLog(User.class); private static final String ROLE_EVERYONE = "Internal/everyone"; + private static Log log = LogFactory.getLog(User.class); /** * Method to add user to emm-user-store. * * @param userWrapper Wrapper object representing input json payload * @return {Response} Status of the request wrapped inside Response object - * @throws MDMAPIException */ @POST @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response addUser(UserWrapper userWrapper) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response addUser(UserWrapper userWrapper) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (userStoreManager.isExistingUser(userWrapper.getUsername())) { // if user already exists if (log.isDebugEnabled()) { @@ -87,7 +95,7 @@ public class User { responsePayload. setMessageFromServer("User by username: " + userWrapper.getUsername() + " already exists. Therefore, request made to add user was refused."); - return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build(); + return Response.status(Response.Status.CONFLICT).entity(responsePayload).build(); } else { String initialUserPassword = generateInitialUserPassword(); Map defaultUserClaims = @@ -106,12 +114,12 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + " was successfully added."); - return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); + return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Exception in trying to add user by username: " + userWrapper.getUsername(); log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -119,16 +127,15 @@ public class User { * Method to get user information from emm-user-store. * * @param username User-name of the user - * @return {Response} Status of the request wrapped inside Response object - * @throws MDMAPIException + * @return {Response} Status of the request wrapped inside Response object. */ @GET @Path("view") @Produces({MediaType.APPLICATION_JSON}) - public Response getUser(@QueryParam("username") String username) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response getUser(@QueryParam("username") String username) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (userStoreManager.isExistingUser(username)) { UserWrapper user = new UserWrapper(); user.setUsername(username); @@ -142,7 +149,7 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("User information was retrieved successfully."); responsePayload.setResponseContent(user); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } else { // Outputting debug message upon trying to remove non-existing user if (log.isDebugEnabled()) { @@ -152,12 +159,12 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer( "User by username: " + username + " does not exist."); - return Response.status(HttpStatus.SC_NOT_FOUND).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Exception in trying to retrieve user by username: " + username; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -165,17 +172,15 @@ public class User { * Update user in user store * * @param userWrapper Wrapper object representing input json payload - * @return {Response} Status of the request wrapped inside Response object - * @throws MDMAPIException + * @return {Response} Status of the request wrapped inside Response object. */ @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) - throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (userStoreManager.isExistingUser(userWrapper.getUsername())) { Map defaultUserClaims = buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), @@ -221,7 +226,7 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + " was successfully updated."); - return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); + return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } else { if (log.isDebugEnabled()) { log.debug("User by username: " + userWrapper.getUsername() + @@ -232,12 +237,12 @@ public class User { responsePayload. setMessageFromServer("User by username: " + userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was refused."); - return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build(); + return Response.status(Response.Status.CONFLICT).entity(responsePayload).build(); } - } catch (UserStoreException | UnsupportedEncodingException e) { + } catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) { String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -291,15 +296,14 @@ public class User { * Method to remove user from emm-user-store. * * @param username Username of the user - * @return {Response} Status of the request wrapped inside Response object - * @throws MDMAPIException + * @return {Response} Status of the request wrapped inside Response object. */ @DELETE @Produces({MediaType.APPLICATION_JSON}) - public Response removeUser(@QueryParam("username") String username) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response removeUser(@QueryParam("username") String username) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (userStoreManager.isExistingUser(username)) { // if user already exists, trying to remove user userStoreManager.deleteUser(username); @@ -311,7 +315,7 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer( "User by username: " + username + " was successfully removed."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } else { // Outputting debug message upon trying to remove non-existing user if (log.isDebugEnabled()) { @@ -321,12 +325,12 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer( "User by username: " + username + " does not exist for removal."); - return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -336,11 +340,14 @@ public class User { * @param userStoreManager User Store Manager associated with the currently logged in user * @param username Username of the currently logged in user * @return the list of filtered roles - * @throws UserStoreException */ - private List getFilteredRoles(UserStoreManager userStoreManager, String username) - throws UserStoreException { - String[] roleListOfUser = userStoreManager.getRoleListOfUser(username); + private List getFilteredRoles(UserStoreManager userStoreManager, String username) { + String[] roleListOfUser = new String[0]; + try { + roleListOfUser = userStoreManager.getRoleListOfUser(username); + } catch (UserStoreException e) { + e.printStackTrace(); + } List filteredRoles = new ArrayList<>(); for (String role : roleListOfUser) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { @@ -354,18 +361,17 @@ public class User { * Get user's roles by username * * @param username Username of the user - * @return {Response} Status of the request wrapped inside Response object - * @throws MDMAPIException + * @return {Response} Status of the request wrapped inside Response object. */ @GET @Path("roles") @Produces({MediaType.APPLICATION_JSON}) - public Response getRoles(@QueryParam("username") String username) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response getRoles(@QueryParam("username") String username) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (userStoreManager.isExistingUser(username)) { - responsePayload.setResponseContent(Arrays.asList(getFilteredRoles(userStoreManager, username))); + responsePayload.setResponseContent(Collections.singletonList(getFilteredRoles(userStoreManager, username))); // Outputting debug message upon successful removal of user if (log.isDebugEnabled()) { log.debug("User by username: " + username + " was successfully removed."); @@ -374,7 +380,7 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer( "User roles obtained for user " + username); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } else { // Outputting debug message upon trying to remove non-existing user if (log.isDebugEnabled()) { @@ -384,12 +390,12 @@ public class User { responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer( "User by username: " + username + " does not exist for role retrieval."); - return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Exception in trying to retrieve roles for user by username: " + username; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -397,17 +403,16 @@ public class User { * Get the list of all users with all user-related info. * * @return A list of users - * @throws MDMAPIException */ @GET @Produces({MediaType.APPLICATION_JSON}) - public Response getAllUsers() throws MDMAPIException { + public Response getAllUsers() { if (log.isDebugEnabled()) { log.debug("Getting the list of users with all user-related information"); } - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); List userList; try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); String[] users = userStoreManager.listUsers("*", -1); userList = new ArrayList<>(users.length); UserWrapper user; @@ -419,10 +424,10 @@ public class User { user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); userList.add(user); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of users"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); @@ -431,25 +436,24 @@ public class User { responsePayload.setMessageFromServer("All users were successfully retrieved. " + "Obtained user count: " + count); responsePayload.setResponseContent(userList); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** * Get the list of all users with all user-related info. * * @return A list of users - * @throws MDMAPIException */ @GET @Path("{filter}") @Produces({MediaType.APPLICATION_JSON}) - public Response getMatchingUsers(@PathParam("filter") String filter) throws MDMAPIException { + public Response getMatchingUsers(@PathParam("filter") String filter) { if (log.isDebugEnabled()) { log.debug("Getting the list of users with all user-related information using the filter : " + filter); } - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); List userList; try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); String[] users = userStoreManager.listUsers(filter + "*", -1); userList = new ArrayList<>(users.length); UserWrapper user; @@ -461,10 +465,10 @@ public class User { user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); userList.add(user); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of users using the filter : " + filter; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); @@ -473,24 +477,23 @@ public class User { responsePayload.setMessageFromServer("All users were successfully retrieved. " + "Obtained user count: " + count); responsePayload.setResponseContent(userList); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** * Get the list of user names in the system. * * @return A list of user names. - * @throws MDMAPIException */ @GET @Path("view-users") - public Response getAllUsersByUsername(@QueryParam("username") String userName) throws MDMAPIException { + public Response getAllUsersByUsername(@QueryParam("username") String userName) { if (log.isDebugEnabled()) { log.debug("Getting the list of users by name"); } - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); List userList; try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); String[] users = userStoreManager.listUsers("*" + userName + "*", -1); userList = new ArrayList<>(users.length); UserWrapper user; @@ -502,10 +505,10 @@ public class User { user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); userList.add(user); } - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of users"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); @@ -514,31 +517,30 @@ public class User { responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + "Obtained user count: " + count); responsePayload.setResponseContent(userList); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** * Get the list of user names in the system. * * @return A list of user names. - * @throws MDMAPIException */ @GET @Path("users-by-username") - public Response getAllUserNamesByUsername(@QueryParam("username") String userName) throws MDMAPIException { + public Response getAllUserNamesByUsername(@QueryParam("username") String userName) { if (log.isDebugEnabled()) { log.debug("Getting the list of users by name"); } - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); List userList; try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); String[] users = userStoreManager.listUsers("*" + userName + "*", -1); userList = new ArrayList<>(users.length); Collections.addAll(userList, users); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of users"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); @@ -547,7 +549,7 @@ public class User { responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + "Obtained user count: " + count); responsePayload.setResponseContent(userList); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** @@ -555,11 +557,10 @@ public class User { * * @param username Username of the user * @param claimUri required ClaimUri - * @return A list of usernames - * @throws MDMAPIException, UserStoreException + * @return claim value */ private String getClaimValue(String username, String claimUri) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); try { return userStoreManager.getUserClaimValue(username, claimUri, null); } catch (UserStoreException e) { @@ -572,10 +573,8 @@ public class User { * Method used to send an invitation email to a new user to enroll a device. * * @param username Username of the user - * @throws MDMAPIException, UserStoreException, DeviceManagementException */ - private void inviteNewlyAddedUserToEnrollDevice( - String username, String password) throws MDMAPIException { + private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException { if (log.isDebugEnabled()) { log.debug("Sending invitation mail to user by username: " + username); } @@ -587,7 +586,7 @@ public class User { username = "/" + username; } String[] usernameBits = username.split("/"); - DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); Properties props = new Properties(); props.setProperty("username", usernameBits[1]); @@ -611,16 +610,15 @@ public class User { * Method used to send an invitation email to a existing user to enroll a device. * * @param usernames Username list of the users to be invited - * @throws MDMAPIException */ @POST @Path("email-invitation") @Produces({MediaType.APPLICATION_JSON}) - public Response inviteExistingUsersToEnrollDevice(List usernames) throws MDMAPIException { + public Response inviteExistingUsersToEnrollDevice(List usernames) { if (log.isDebugEnabled()) { log.debug("Sending enrollment invitation mail to existing user."); } - DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { for (String username : usernames) { String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); @@ -632,15 +630,15 @@ public class User { EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); deviceManagementProviderService.sendEnrolmentInvitation(metaInfo); } - } catch (DeviceManagementException e) { + } catch (DeviceManagementException | MDMAPIException e) { String msg = "Error occurred while inviting user to enrol their device"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); - return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); + return Response.status(Response.Status.OK).entity(responsePayload).build(); } /** @@ -648,27 +646,25 @@ public class User { * * @param username Username of the device owner * @return A list of devices - * @throws MDMAPIException */ @GET @Produces({MediaType.APPLICATION_JSON}) @Path("devices") - public Object getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx, - @QueryParam("length") int length) - throws MDMAPIException { + public Response getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx, + @QueryParam("length") int length) { DeviceManagementProviderService dmService; try { - dmService = MDMAPIUtils.getDeviceManagementService(); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); if (length > 0) { PaginationRequest request = new PaginationRequest(startIdx, length); request.setOwner(username); - return dmService.getDevicesOfUser(request); + return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(request)).build(); } - return dmService.getDevicesOfUser(username); + return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(username)).build(); } catch (DeviceManagementException e) { String msg = "Device management error"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -676,22 +672,23 @@ public class User { * This method is used to retrieve the user count of the system. * * @return returns the count. - * @throws MDMAPIException + * @ */ @GET @Path("count") - public int getUserCount() throws MDMAPIException { + public Response getUserCount() { try { - String[] users = MDMAPIUtils.getUserStoreManager().listUsers("*", -1); - if (users == null) { - return 0; + String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1); + Integer count = 0; + if (users != null) { + count = users.length; } - return users.length; - } catch (UserStoreException e) { + return Response.status(Response.Status.OK).entity(count).build(); + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while retrieving the list of users that exist within the current tenant"; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @@ -701,33 +698,30 @@ public class User { * @param username * @param userList * @return - * @throws MDMAPIException + * @ */ @PUT @Path("{roleName}/users") @Produces({MediaType.APPLICATION_JSON}) - public Response updateRoles(@PathParam("username") String username, List userList) - throws MDMAPIException { - final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public Response updateRoles(@PathParam("username") String username, List userList) { try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { log.debug("Updating the roles of a user"); } - SetReferenceTransformer transformer = new SetReferenceTransformer(); + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)), userList); - final String[] rolesToAdd = (String[]) - transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); - final String[] rolesToDelete = (String[]) - transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); + final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); + final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd); - } catch (UserStoreException e) { + } catch (UserStoreException | MDMAPIException e) { String msg = "Error occurred while saving the roles for user: " + username; log.error(msg, e); - throw new MDMAPIException(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } - return Response.status(HttpStatus.SC_OK).build(); + return Response.status(Response.Status.OK).build(); } /** @@ -735,13 +729,13 @@ public class User { * * @param credentials Wrapper object representing user credentials. * @return {Response} Status of the request wrapped inside Response object. - * @throws MDMAPIException + * @ */ @POST @Path("change-password") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response resetPassword(UserCredentialWrapper credentials) throws MDMAPIException { + public Response resetPassword(UserCredentialWrapper credentials) { return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials); } @@ -750,13 +744,13 @@ public class User { * * @param credentials Wrapper object representing user credentials. * @return {Response} Status of the request wrapped inside Response object. - * @throws MDMAPIException + * @ */ @POST @Path("reset-password") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response resetPasswordByAdmin(UserCredentialWrapper credentials) throws MDMAPIException { + public Response resetPasswordByAdmin(UserCredentialWrapper credentials) { return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java index 6400367585..94f766f551 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java @@ -37,19 +37,16 @@ public class CredentialManagementResponseBuilder { private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class); - private ResponsePayload responsePayload; - /** * Builds the response to change the password of a user * @param credentials - User credentials * @return Response Object - * @throws MDMAPIException */ - public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword()); userStoreManager.updateCredential(credentials.getUsername(), new String( @@ -57,48 +54,52 @@ public class CredentialManagementResponseBuilder { responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + " was successfully changed."); - return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); + return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } catch (UserStoreException e) { log.error(e.getMessage(), e); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer("Old password does not match."); - return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } catch (UnsupportedEncodingException e) { String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + ". The Character Encoding is not supported."; log.error(errorMsg, e); - throw new MDMAPIException(errorMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build(); + } catch (MDMAPIException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); } - } /** * Builds the response to reset the password of a user * @param credentials - User credentials * @return Response Object - * @throws MDMAPIException */ - public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) throws MDMAPIException { - UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); + public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) { ResponsePayload responsePayload = new ResponsePayload(); try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( decodedNewPassword, "UTF-8")); responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + " was successfully changed."); - return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); + return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } catch (UserStoreException e) { log.error(e.getMessage(), e); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer("Could not change the password."); - return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); } catch (UnsupportedEncodingException e) { String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + ". The Character Encoding is not supported."; log.error(errorMsg, e); - throw new MDMAPIException(errorMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build(); + } catch (MDMAPIException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/DeviceMgtAPIUtils.java similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAPIUtils.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/DeviceMgtAPIUtils.java index d2a3fb9d2f..d7cb8f940f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/DeviceMgtAPIUtils.java @@ -33,18 +33,16 @@ import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderServ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.ntask.core.TaskManager; import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; -import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.ws.rs.core.MediaType; import java.util.List; @@ -52,12 +50,11 @@ import java.util.List; /** * MDMAPIUtils class provides utility function used by CDM REST-API classes. */ -public class MDMAPIUtils { +public class DeviceMgtAPIUtils { - private static final String NOTIFIER_FREQUENCY = "notifierFrequency"; public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE; - - private static Log log = LogFactory.getLog(MDMAPIUtils.class); + private static final String NOTIFIER_FREQUENCY = "notifierFrequency"; + private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class); public static int getNotifierFrequency(TenantConfiguration tenantConfiguration) { List configEntryList = tenantConfiguration.getConfiguration(); @@ -97,6 +94,18 @@ public class MDMAPIUtils { return deviceManagementProviderService; } + public static GroupManagementProviderService getGroupManagementProviderService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + GroupManagementProviderService groupManagementProviderService = + (GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null); + if (groupManagementProviderService == null) { + String msg = "Group Management service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return groupManagementProviderService; + } + public static int getTenantId(String tenantDomain) throws MDMAPIException { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java index e9caa31d27..70651d64c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @@ -19,7 +19,7 @@ package org.wso2.carbon.mdm.util; /** - * Holds the constants used by MDM-Admin web application. + * Holds the constants used by Device Management Admin web application. */ public class Constants { 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 d2442641f1..42fd366369 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 @@ -22,7 +22,7 @@ (URL) , HTTP method and OAUTH2 authorization scope (not-required). When defining dynamic paths for APIs, path variables are denoted by '*' notation. For ex: - Actual API endpoint: mdm-admin/1.0.0/devices/{device-id} + Actual API endpoint: devicemgt_admin/1.0.0/devices/{device-id} URL to be represented here: /devices/* NOTE: All the endpoints of the web app should be available in this file. Otherwise it will result 403 error at the runtime. @@ -40,7 +40,7 @@ Device Management Admin - /device-mgt/emm-admin + /device-mgt/admin / GET @@ -54,98 +54,98 @@ Devices - /device-mgt/emm-admin/devices + /device-mgt/admin/devices / GET Policies - /device-mgt/emm-admin/policies + /device-mgt/admin/policies / GET Notifications - /device-mgt/emm-admin/notifications + /device-mgt/admin/notifications / GET Users - /device-mgt/emm-admin/users + /device-mgt/admin/users / GET Operations - /device-mgt/emm-admin/operations + /device-mgt/admin/operations / GET Applications - /device-mgt/emm-admin/operations/applications + /device-mgt/admin/operations/applications / GET Roles - /device-mgt/emm-admin/roles + /device-mgt/admin/roles / GET Configurations - /device-mgt/emm-admin/platform-configs + /device-mgt/admin/platform-configs / GET View Dashboard - /device-mgt/emm-admin/dashboard + /device-mgt/admin/dashboard / GET List devices - /device-mgt/emm-admin/devices/list + /device-mgt/admin/devices/list /devices GET List devices - /device-mgt/emm-admin/devices/list + /device-mgt/admin/devices/list /devices/types GET Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /devices/types GET Edit policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /devices/types GET View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /devices/view GET @@ -167,21 +167,21 @@ View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /devices/user/*/* GET List devices - /device-mgt/emm-admin/devices/list + /device-mgt/admin/devices/list /devices/count GET List devices - /device-mgt/emm-admin/devices/list + /device-mgt/admin/devices/list /devices/name/*/* GET @@ -190,28 +190,28 @@ View notifications - /device-mgt/emm-admin/notifications/view + /device-mgt/admin/notifications/view /notifications GET Add notification - /device-mgt/emm-admin/notifications/add + /device-mgt/admin/notifications/add /notifications POST Update notification - /device-mgt/emm-admin/notifications/update + /device-mgt/admin/notifications/update /notifications/*/* PUT View notifications - /device-mgt/emm-admin/notifications/view + /device-mgt/admin/notifications/view /notifications/* GET @@ -220,35 +220,35 @@ View user - /device-mgt/emm-admin/users/view + /device-mgt/admin/users/view /operations GET Install application - /device-mgt/emm-admin/operations/applications/install-applications + /device-mgt/admin/operations/applications/install-applications /operations POST Install application - /device-mgt/emm-admin/operations/applications/install-applications + /device-mgt/admin/operations/applications/install-applications /operations/installApp/* POST Uninstall application - /device-mgt/emm-admin/operations/applications/uninstall-applications + /device-mgt/admin/operations/applications/uninstall-applications /operations/uninstallApp/* POST View application - /device-mgt/emm-admin/operations/applications/view-applications + /device-mgt/admin/operations/applications/view-applications /operations/*/*/* GET @@ -262,21 +262,21 @@ View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /operations/*/*/* GET View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /operations/*/* GET View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /operations/paginate/*/* GET @@ -307,14 +307,14 @@ List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /features/* GET View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /features/* GET @@ -331,63 +331,63 @@ /device-mgt/user/devices/view /features GET - emm_admin + List roles - /device-mgt/emm-admin/roles/list + /device-mgt/admin/roles/list /roles GET View user - /device-mgt/emm-admin/users/view + /device-mgt/admin/users/view /roles GET Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /roles GET Update policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /roles GET List roles - /device-mgt/emm-admin/roles/list + /device-mgt/admin/roles/list /roles/permissions GET List roles - /device-mgt/emm-admin/roles/list + /device-mgt/admin/roles/list /roles/* GET Add user - /device-mgt/emm-admin/users/add + /device-mgt/admin/users/add /roles/* GET Update role - /device-mgt/emm-admin/roles/update + /device-mgt/admin/roles/update /roles PUT @@ -397,33 +397,33 @@ - + Update role - /device-mgt/emm-admin/roles/update + /device-mgt/admin/roles/update /roles/users PUT Add role - /device-mgt/emm-admin/roles/add + /device-mgt/admin/roles/add /roles POST Remove role - /device-mgt/emm-admin/roles/remove + /device-mgt/admin/roles/remove /roles DELETE List roles - /device-mgt/emm-admin/roles/list + /device-mgt/admin/roles/list /roles/count GET @@ -432,28 +432,28 @@ List users - /device-mgt/emm-admin/users/list + /device-mgt/admin/users/list /users GET Add user - /device-mgt/emm-admin/users/add + /device-mgt/admin/users/add /users POST View user - /device-mgt/emm-admin/users/view + /device-mgt/admin/users/view /users/view GET Update user - /device-mgt/emm-admin/users/update + /device-mgt/admin/users/update /users PUT @@ -463,40 +463,39 @@ /login /users/change-password POST - emm_admin Reset password - /device-mgt/emm-admin/users/password-reset + /device-mgt/admin/users/password-reset /users/reset-password POST Remove user - /device-mgt/emm-admin/users/remove + /device-mgt/admin/users/remove /users DELETE View user - /device-mgt/emm-admin/users/view + /device-mgt/admin/users/view /users/roles GET - + Add user - /device-mgt/emm-admin/users/add + /device-mgt/admin/users/add /roles POST @@ -510,77 +509,77 @@ List devices - /device-mgt/emm-admin/devices/list + /device-mgt/admin/devices/list /users/devices GET View user - /device-mgt/emm-admin/users/view + /device-mgt/admin/users/view /users/*/* GET List users - /device-mgt/emm-admin/users/list + /device-mgt/admin/users/list /users/count GET List users - /device-mgt/emm-admin/users/list + /device-mgt/admin/users/list /users/view-users GET Add role - /device-mgt/emm-admin/roles/add + /device-mgt/admin/roles/add /users/view-users GET Update role - /device-mgt/emm-admin/roles/update + /device-mgt/admin/roles/update /users/view-users GET Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /users/view-users GET Update policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /users/view-users GET List users - /device-mgt/emm-admin/users/list + /device-mgt/admin/users/list /users/users-by-username GET List users - /device-mgt/emm-admin/users/list + /device-mgt/admin/users/list /users/users-by-username/* GET Invite user - /device-mgt/emm-admin/users/invite + /device-mgt/admin/users/invite /users/email-invitation POST @@ -596,28 +595,28 @@ Add Policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/inactive-policy POST List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /policies/*/* POST List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /policies/*/*/* GET View device - /device-mgt/emm-admin/devices/view + /device-mgt/admin/devices/view /policies/*/*/* GET @@ -631,119 +630,119 @@ Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/active-policy POST Remove policy - /device-mgt/emm-admin/policies/remove + /device-mgt/admin/policies/remove /policies/bulk-remove POST List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /policies GET List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /policies/* GET Update policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /policies/* PUT Remove policy - /device-mgt/emm-admin/policies/remove + /device-mgt/admin/policies/remove /policies DELETE List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /policies/count GET Edit policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /policies/priorities PUT Edit policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /policies/activate PUT Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/activate PUT Edit policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /policies/inactivate PUT Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/inactivate PUT Edit policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /policies/apply-changes PUT Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/start-task/* GET Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/update-task/* GET Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /policies/stop-task GET List policies - /device-mgt/emm-admin/policies/list + /device-mgt/admin/policies/list /policies/*/* GET @@ -752,21 +751,21 @@ Add policy - /device-mgt/emm-admin/policies/add + /device-mgt/admin/policies/add /profiles POST Edit policy - /device-mgt/emm-admin/policies/update + /device-mgt/admin/policies/update /profiles/* PUT Remove policy - /device-mgt/emm-admin/policies/remove + /device-mgt/admin/policies/remove /profiles/* DELETE @@ -776,14 +775,14 @@ Device Information - /device-mgt/emm-admin/information/get + /device-mgt/admin/information/get /information/*/* GET Device Search - /device-mgt/emm-admin/search + /device-mgt/admin/search /information/* GET @@ -797,35 +796,35 @@ - + - + View configuration - /device-mgt/emm-admin/platform-configs/view + /device-mgt/admin/platform-configs/view /configuration GET Add configuration - /device-mgt/emm-admin/platform-configs/add + /device-mgt/admin/platform-configs/add /configuration POST Update configuration - /device-mgt/emm-admin/platform-configs/modify + /device-mgt/admin/platform-configs/modify /configuration PUT @@ -838,21 +837,161 @@ /device-mgt/android/certificate/save /certificates/saveCertificate POST - emm_admin get certificate in the database /device-mgt/android/certificate/Get /certificates/* GET - emm_admin get certificate in the database /device-mgt/android/certificate/Get /certificates/* DELETE - emm_admin - \ No newline at end of file + + + + Group Management + /device-mgt/admin/groups + /groups + POST + + + + Group Management + /device-mgt/admin/groups + /groups/*/* + PUT + + + + Group Management + /device-mgt/admin/groups + /groups/*/* + DELETE + + + + Group Management + /device-mgt/admin/groups + /groups + GET + + + + Group Management + /device-mgt/admin/groups + /groups/user/* + GET + + + + Group Management + /device-mgt/admin/groups + /groups/*/* + GET + + + + Group Management + /device-mgt/admin/groups + /groups/search + GET + + + + Group Management + /device-mgt/admin/groups + /groups/user/*/all + GET + + + + Group Management + /device-mgt/admin/groups + /groups/user/*/count + GET + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/share + PUT + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/unshare + PUT + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/share/roles/*/permissions + PUT + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/share/roles/*/permissions + DELETE + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/share/roles + GET + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/users + GET + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/devices/all + GET + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/devices/count + GET + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/devices/*/* + PUT + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/devices/*/* + DELETE + + + + Group Management + /device-mgt/admin/groups + /groups/*/*/users/*/permissions + GET + + + + 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 e4b794b8a9..c6e489f7f8 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 @@ -17,9 +17,9 @@ ~ under the License. --> - @@ -51,6 +51,15 @@ + + + + + + + + + @@ -155,7 +164,8 @@ --> - + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml index 1ee664987f..ab8d04cbe8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml @@ -1,6 +1,6 @@ + --> Admin-Webapp - JAX-WS/JAX-RS MDM Endpoint + JAX-WS/JAX-RS Device Management Endpoint JAX-WS/JAX-RS Servlet CXFServlet @@ -63,7 +63,7 @@ - MDM-Admin + DeviceMgt-Admin /* diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml index 791f382a9c..b728ed51ea 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml @@ -59,7 +59,7 @@ ${project.build.directory}/maven-shared-archive-resources/webapps - mdm-admin.war + devicemgt_admin.war diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf index ff61b588ec..91d8294fa2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf @@ -1,3 +1,3 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/mdm-admin.war,target:${installFolder}/../../deployment/server/webapps/mdm-admin.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/devicemgt_admin.war,target:${installFolder}/../../deployment/server/webapps/devicemgt_admin.war,overwrite:true);\ \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml index 175e970d1e..ec7962494d 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml @@ -1,18 +1,18 @@ @@ -44,6 +44,11 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.api.feature + zip + org.wso2.carbon.commons org.wso2.carbon.email.verification @@ -97,6 +102,11 @@ org.eclipse.equinox.p2.type.group:false + + + org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.api.feature:${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.core:${carbon.device.mgt.version} diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 2479f90a61..18ec1fd164 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -1,21 +1,21 @@ + ~ 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. + --> @@ -27,7 +27,6 @@ 4.0.0 - org.wso2.carbon.devicemgt device-mgt-feature pom WSO2 Carbon - Device Management Feature diff --git a/pom.xml b/pom.xml index 3eabc1187c..b0bab3e94b 100644 --- a/pom.xml +++ b/pom.xml @@ -275,6 +275,12 @@ zip ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.api.feature + zip + ${carbon.device.mgt.version} + org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.ui.feature From 6d8c3e53151989e8f41ead9307c153816bea6734 Mon Sep 17 00:00:00 2001 From: charithag Date: Mon, 18 Apr 2016 16:44:03 +0530 Subject: [PATCH 02/10] Fix default permission issues --- .../jaggeryapps/devicemgt/api/user-api.jag | 2 - .../jaggeryapps/devicemgt/app/modules/init.js | 1 - .../devicemgt/app/modules/login.js | 3 - .../jaggeryapps/devicemgt/app/modules/user.js | 25 ++- .../devicemgt/app/modules/utility.js | 153 ------------------ 5 files changed, 12 insertions(+), 172 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index 88ddca07d2..2dc839f907 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -46,7 +46,6 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - utility.insertAppPermissions(userModule, "login"); apiWrapperUtil.setupAccessTokenPair("password", { "username": username, "password": password @@ -69,7 +68,6 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - utility.insertAppPermissions(userModule, "login"); apiWrapperUtil.setupAccessTokenPair("password", {"username": username, "password": password}); var permissions = userModule.getUIPermissions(); if (permissions.VIEW_DASHBOARD) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js index 1f2c884af6..2a22b1c987 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js @@ -26,7 +26,6 @@ application.put("carbonServer", carbonServer); var userModule = require("/app/modules/user.js")["userModule"]; var utility = require("/app/modules/utility.js")["utility"]; -utility.insertAppPermissions(userModule, "init"); var permissions = { '/permission/admin/device-mgt/devices': ['ui.execute'], diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 5b53589c98..00e57c7d4f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -25,9 +25,6 @@ var onFail; onSuccess = function (context) { var utility = require("/app/modules/utility.js").utility; var apiWrapperUtil = require("/app/modules/api-wrapper-util.js").apiWrapperUtil; - var userModule = require("/app/modules/user.js").userModule; - - utility.insertAppPermissions(userModule, "login"); var properties = {username: context.input.username, password: context.input.password}; apiWrapperUtil.setupAccessTokenPair("password", properties); }; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js index 69c3ca62ee..1c1139b3aa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js @@ -629,44 +629,43 @@ var userModule = function () { publicMethods.getUIPermissions = function () { var permissions = {}; - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/devices/list") || - publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { permissions["LIST_DEVICES"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/list")) { permissions["LIST_GROUPS"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/users/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/list")) { permissions["LIST_USERS"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/roles/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/list")) { permissions["LIST_ROLES"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/policies/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/list")) { permissions["LIST_POLICIES"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/groups/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/add")) { permissions["ADD_GROUP"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/users/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/add")) { permissions["ADD_USER"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/users/remove")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/remove")) { permissions["REMOVE_USER"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/roles/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/add")) { permissions["ADD_ROLE"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/policies/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/add")) { permissions["ADD_POLICY"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/policies/priority")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/priority")) { permissions["CHANGE_POLICY_PRIORITY"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/dashboard/view")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/dashboard/view")) { permissions["VIEW_DASHBOARD"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/emm-admin/platform-configs/view")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) { permissions["TENANT_CONFIGURATION"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js index 58a30198ce..07fbe79cc7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js @@ -61,159 +61,6 @@ utility = function () { return getOsgiService("org.wso2.carbon.policy.mgt.core.PolicyManagerService"); }; - publicMethods.insertAppPermissions = function (userModule, type) { - // Below are the 2 types of users:- Normal users and Admins - userModule.addPermissions([{ - key: "admin", - name: "Device Management Admin" - }], "device-mgt", type); - userModule.addPermissions([{ - key: "user", - name: "Device Management User" - }], "device-mgt", type); - - // adding permission definitions for device-mgt/admin - userModule.addPermissions([{ - key: "dashboard", - name: "Dashboard" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "dashboard/view", - name: "View Dashboard" - }], "device-mgt/admin", type); - - userModule.addPermissions([{ - key: "devices", - name: "Devices" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "devices/list", - name: "List All Devices" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "devices/add", - name: "Add Device" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "devices/edit", - name: "Edit Device" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "devices/remove", - name: "Remove Device" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "groups", - name: "Groups" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "groups/list", - name: "List All Groups" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "groups/add", - name: "Add Group" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "devices/operation", - name: "Perform Operation on Any Device" - }], "device-mgt/admin", type); - - userModule.addPermissions([{key: "users", name: "Users"}], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "users/add", - name: "Add New Users" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "users/invite", - name: "Invite Users" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "users/list", - name: "List Users" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "users/update", - name: "Update Users" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "users/remove", - name: "Remove Users" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "users/reset-password", - name: "Reset User Passwords" - }], "device-mgt/admin", type); - - userModule.addPermissions([{key: "roles", name: "Roles"}], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "roles/add", - name: "Add New Roles" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "roles/invite", - name: "Invite Roles" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "roles/list", - name: "List Roles" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "roles/remove", - name: "Remove Roles" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "roles/permission", - name: "Update Role Permission" - }], "device-mgt/admin", type); - - - userModule.addPermissions([{ - key: "policies", - name: "Policy" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "policies/add", - name: "Add Policy" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "policies/list", - name: "List Policy" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "policies/edit", - name: "Edit Policy" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "policies/remove", - name: "Remove Policy" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "policies/priority", - name: "Policy Priority" - }], "device-mgt/admin", type); - - // adding permission definitions for device-mgt/user - userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/user", type); - userModule.addPermissions([{ - key: "devices/list", - name: "List Individual Devices" - }], "device-mgt/user", type); - userModule.addPermissions([{ - key: "devices/operation", - name: "Perform Operation on an Individual Device" - }], "device-mgt/user", type); - - userModule.addPermissions([{ - key: "platform-configs", - name: "Platform Configurations" - }], "device-mgt/admin", type); - userModule.addPermissions([{ - key: "platform-configs/view", - name: "View Configurations" - }], "device-mgt/admin", type); - }; - publicMethods.getIoTServerConfig = function (configName) { var path = "/config/iot-config.json"; var file = new File(path); From a5a152985346ce3babc9069615f41aedcb7a5141 Mon Sep 17 00:00:00 2001 From: charithag Date: Tue, 19 Apr 2016 14:54:37 +0530 Subject: [PATCH 03/10] Fix issues in device listing page and device details page --- .../jaggeryapps/devicemgt/api/device-api.jag | 84 +++++++++++++++++++ .../devicemgt/app/modules/device.js | 7 +- .../devicemgt/app/modules/operation.js | 36 ++++---- .../app/pages/cdmf.page.devices/devices.hbs | 4 +- .../app/pages/cdmf.page.devices/devices.js | 30 +++---- .../cdmf.page.devices/public/js/listing.js | 28 +++++-- 6 files changed, 138 insertions(+), 51 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 2d19fd0256..1f7d62b2aa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -25,6 +25,8 @@ var constants = require("/app/modules/constants.js"); var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); +var userModule = require("/app/modules/user.js").userModule; +var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker; var CarbonUtils = Packages.org.wso2.carbon.utils.CarbonUtils; var user = session.get(constants.USER_SESSION_KEY); @@ -159,6 +161,88 @@ if (!user) { var deviceType = elements.deviceType; var deviceName = request.getParameter("name"); result = deviceModule.updateDevice(deviceType, deviceId, deviceName); + } else if (uriMatcher.match("/{context}/api/devices")) { + var url = request.getParameter("url"); + var draw = request.getParameter("draw"); + var length = request.getParameter("length"); + var start = request.getParameter("start"); + var search = request.getParameter("search[value]"); + var deviceName = request.getParameter("columns[1][search][value]"); + var owner = request.getParameter("columns[2][search][value]"); + var status = request.getParameter("columns[3][search][value]"); + var platform = request.getParameter("columns[4][search][value]"); + var ownership = request.getParameter("columns[5][search][value]"); + var targetURL; + + function appendQueryParam (url, queryParam , value) { + if (url.indexOf("?") > 0) { + return url + "&" + queryParam + "=" + value; + } + return url + "?" + queryParam + "=" + value; + } + targetURL = devicemgtProps.httpsURL + request.getParameter("url"); + targetURL = appendQueryParam(targetURL, "draw", draw); + targetURL = appendQueryParam(targetURL, "start", start); + targetURL = appendQueryParam(targetURL, "length", length); + + if (search && search !== "") { + targetURL = appendQueryParam(targetURL, "search", search); + } + + if (deviceName && deviceName !== "") { + targetURL = appendQueryParam(targetURL, "device-name", deviceName); + } + + if (owner && owner !== "") { + targetURL = appendQueryParam(targetURL, "user", owner); + } + + if (status && status !== "") { + targetURL = appendQueryParam(targetURL, "status", status); + } + + if (platform && platform !== "") { + targetURL = appendQueryParam(targetURL, "type", platform); + } + + if (ownership && ownership !== "") { + targetURL = appendQueryParam(targetURL, "ownership", ownership); + } + + serviceInvokers.XMLHttp.get( + targetURL, function (responsePayload) { + response.status = 200; + result = responsePayload; + }, + function (responsePayload) { + response.status = responsePayload.status; + result = responsePayload.responseText; + }); + } else if (uriMatcher.match("/{context}/api/devices/")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { + result = deviceModule.listDevices(); + } else { + response.sendError(403); + } + } else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}")) { + elements = uriMatcher.elements(); + deviceId = elements.deviceId; + type = elements.type; + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { + result = deviceModule.viewDevice(type, deviceId); + }else { + response.sendError(403); + } + } else if (uriMatcher.match("{context}/api/devices/{type}/{deviceId}/{operation}")) { + elements = uriMatcher.elements(); + deviceId = elements.deviceId; + type = elements.type; + operation = elements.operation; + if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/operation")) { + result = deviceModule.performOperation(deviceId, operation, [], type); + } else { + response.sendError(403); + } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index b06a2e436a..c2865c13b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -278,9 +278,10 @@ deviceModule = function () { if (device) { var propertiesList = device["properties"]; var properties = {}; - for (var i = 0; i < propertiesList.length; i++) { - properties[propertiesList[i]["name"]] = - propertiesList[i]["value"]; + if (propertiesList){ + for (var i = 0; i < propertiesList.length; i++) { + properties[propertiesList[i]["name"]] = propertiesList[i]["value"]; + } } var deviceObject = {}; deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js index aded5dac5c..75c9abe9e7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js @@ -21,6 +21,7 @@ var operationModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); + var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker; var publicMethods = {}; var privateMethods = {}; @@ -39,51 +40,45 @@ var operationModule = function () { privateMethods.getOperationsFromFeatures = function (deviceType, operationType) { var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType; var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) { - var features = responsePayload.responseContent; + var features = responsePayload; var featureList = []; var feature; - for (var i = 0; i < features.size(); i++) { + for (var i = 0; i < features.length; i++) { feature = {}; - if (features.get(i).getType() != operationType) { + if (features[i].type != operationType) { continue; - } else if (features.get(i).getType() == 'monitor') { + } else if (features[i].type == 'monitor') { var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; if (analyticStreams) { for (var stream in analyticStreams) { - if (analyticStreams[stream].name == features.get(i).getName()) { + if (analyticStreams[stream].name == features[i].name) { feature.ui_unit = analyticStreams[stream].ui_unit; break; } } } } - feature["operation"] = new String(features.get(i).getCode()); - feature["name"] = new String(features.get(i).getName()); - feature["description"] = new String(features.get(i).getDescription()); - feature["deviceType"] = new String(features.get(i).getDeviceType()); + feature["operation"] = features[i].code; + feature["name"] = features[i].name; + feature["description"] = features[i].description; + feature["deviceType"] = deviceType; feature["params"] = []; - var metaData = features.get(i).getMetadataEntries(); - if (metaData && metaData != null) { - for (var j = 0; j < metaData.size(); j++) { - feature["params"].push(new String(metaData.get(j).getValue())); + var metaData = features[i].metadataEntries; + if (metaData) { + for (var j = 0; j < metaData.length; j++) { + feature["params"].push(metaData[j].value); } featureList.push(feature); } } return featureList; - } - , - function (responsePayload) { + }, function (responsePayload) { var response = {}; response["status"] = "error"; return response; } ); return featuresList; - return featureList; - } catch (e) { - throw e; - } }; publicMethods.getControlOperations = function (deviceType) { @@ -108,7 +103,6 @@ var operationModule = function () { '","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' + constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) + '"}'; - log.warn("header: " + header); return post(endPoint, params, JSON.parse(header), "json"); }; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index a15a5a84b1..e4663a57ba 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -61,7 +61,7 @@
{{unit "cdmf.unit.device.operation-mod"}} {{#if deviceCount}} - +
    @@ -324,7 +324,7 @@ {{/zone}} {{#zone "bottomJs"}} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js index 88cb32d704..6a376bb028 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js @@ -31,25 +31,13 @@ function onRequest(context) { page.groupName = groupName; } page.title = title; - page.permissions = {}; var currentUser = session.get(constants.USER_SESSION_KEY); - var permissions = []; if (currentUser) { - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { - permissions.push("LIST_DEVICES"); - } else if (userModule.isAuthorized("/permission/admin/device-mgt/user/devices/list")) { - permissions.push("LIST_OWN_DEVICES"); - } else if (userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/policies/list")) { - permissions.push("LIST_POLICIES"); - } + page.permissions = {}; + page.permissions.list = stringify(userModule.getUIPermissions()); if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/add")) { permissions.enroll = true; } - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/remove")) { - permissions.push("REMOVE_DEVICE"); - } - - page.permissions.list = permissions; page.currentUser = currentUser; var deviceCount = 0; if (groupName && groupOwner) { @@ -64,15 +52,17 @@ function onRequest(context) { var utility = require("/app/modules/utility.js").utility; var data = deviceModule.getDeviceTypes(); var deviceTypes = []; - if (data.data) { - for (var i = 0; i < data.data.length; i++) { + if (data) { + for (var i = 0; i < data.length; i++) { + var deviceType = utility.getDeviceTypeConfig(data[i].name).deviceType; deviceTypes.push({ - "type": data.data[i].name, - "category": utility.getDeviceTypeConfig(data.data[i].name).deviceType.category - }); + "type": data[i].name, + "category": deviceType.category, + "label": deviceType.label + }); } } - page.deviceTypes = deviceTypes; + page.deviceTypes = stringify(deviceTypes); } } return page; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js index 2711b2b29c..767c37f684 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js @@ -72,8 +72,10 @@ $(document).ready(function () { var i; var permissionList = $("#permission").data("permission"); - for (i = 0; i < permissionList.length; i++) { - $.setPermission(permissionList[i]); + for (var key in permissionList) { + if (permissionList.hasOwnProperty(key)) { + $.setPermission(key); + } } /* for device list sorting drop down */ @@ -171,7 +173,7 @@ function loadDevices(searchType, searchParam){ serviceURL = "/devicemgt_admin/devices"; } else if ($.hasPermission("LIST_OWN_DEVICES")) { //Get authenticated users devices - serviceURL = "/devicemgt_admin/users/devices?username="+currentUser; + serviceURL = "/devicemgt_admin/users/devices?username=" + currentUser; } else { $("#loading-content").remove(); $('#device-table').addClass('hidden'); @@ -181,8 +183,11 @@ function loadDevices(searchType, searchParam){ } function getPropertyValue(deviceProperties, propertyName) { + if (!deviceProperties) { + return; + } var property; - for (var i =0; i < deviceProperties.length; i++) { + for (var i = 0; i < deviceProperties.length; i++) { property = deviceProperties[i]; if (property.name == propertyName) { return property.value; @@ -191,6 +196,16 @@ function loadDevices(searchType, searchParam){ return {}; } + function getDeviceTypeLabel(type){ + var deviceTypes = deviceListing.data("deviceTypes"); + for (var i = 0; i < deviceTypes.length; i++){ + if (deviceTypes[i].type == type){ + return deviceTypes[i].label; + } + } + return type; + } + $('#device-grid').datatables_extended ({ serverSide: true, processing: false, @@ -242,7 +257,10 @@ function loadDevices(searchType, searchParam){ } return html; }}, - { targets: 4, data: 'type' , className: 'fade-edge remove-padding-top' }, + { targets: 4, data: 'type' , className: 'fade-edge remove-padding-top' , + render: function ( status, type, row, meta ) { + return getDeviceTypeLabel(row.type); + }}, { targets: 5, data: 'enrolmentInfo.ownership' , className: 'fade-edge remove-padding-top' }, { targets: 6, data: 'enrolmentInfo.status' , className: 'text-right content-fill text-left-on-grid-view no-wrap' , render: function ( status, type, row, meta ) { From bb33b4ea12a66c1c81acdb9551b30a1ac5c8f4ce Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Wed, 20 Apr 2016 13:37:42 +0530 Subject: [PATCH 04/10] Parameterizing Content-Type and Accept headers. --- .../jaggeryapps/devicemgt/api/invoker-api.jag | 47 ++++++++++------ .../app/modules/backend-service-invoker.js | 54 ++++++++++--------- .../public/js/invoker-lib.js | 30 ++++++----- 3 files changed, 80 insertions(+), 51 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index 45b9127143..ac587def72 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -30,11 +30,13 @@ var result; if (uriMatcher.match("/{context}/api/invoker/execute/")) { var method = request.getContent().actionMethod; - var targetURL = devicemgtProps.httpsURL + request.getContent().actionUrl; + var targetURL = getTargetUrl(devicemgtProps.httpsURL, request.getContent().actionUrl); var payload = request.getContent().actionPayload; + var contentType = request.getHeader(constants.CONTENT_TYPE_IDENTIFIER); + var acceptType = request.getHeader(constants.ACCEPT_IDENTIFIER); if (method == undefined && payload == undefined) { method = parse(request.getContent()).actionMethod; - targetURL = devicemgtProps.httpsURL + parse(request.getContent()).actionUrl; + targetURL = getTargetUrl(devicemgtProps.httpsURL, parse(request.getContent()).actionUrl); payload = parse(request.getContent()).actionPayload; } try { @@ -48,7 +50,9 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) { function (responsePayload) { response.status = responsePayload.status; response.content = responsePayload.responseText; - }); + }, + contentType, + acceptType); break; case constants.HTTP_POST: var responseData = serviceInvokers.XMLHttp.post( @@ -59,7 +63,9 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) { function (responsePayload) { response.status = responsePayload.status; response.content = responsePayload.responseText; - }); + }, + contentType, + acceptType); break; case constants.HTTP_PUT: var responseData = serviceInvokers.XMLHttp.put( @@ -70,19 +76,22 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) { function (responsePayload) { response.status = responsePayload.status; response.content = responsePayload.responseText; - }); + }, + contentType, + acceptType); break; case constants.HTTP_DELETE: - var responseData = - serviceInvokers.XMLHttp.delete( - targetURL, function (responsePayload) { - response.status = 200; - response.content = responsePayload; - }, - function (responsePayload) { - response.status = responsePayload.status; - response.content = responsePayload.responseText; - }); + var responseData = serviceInvokers.XMLHttp.delete( + targetURL, function (responsePayload) { + response.status = 200; + response.content = responsePayload; + }, + function (responsePayload) { + response.status = responsePayload.status; + response.content = responsePayload.responseText; + }, + contentType, + acceptType); break; } } catch (e) { @@ -90,4 +99,12 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) { } } +function getTargetUrl(serverUrl, actionUrl){ + if(actionUrl == undefined || actionUrl.lastIndexOf("http", 0) === 0){ + return actionUrl; + } else { + return serverUrl + actionUrl; + } +} + %> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js index 9aeb2e84de..6e7540b3f0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js @@ -54,11 +54,17 @@ var backendServiceInvoker = function () { * @param errorCallback a function to be called if en error is reserved. * @param count a counter which hold the number of recursive execution */ - privateMethods.execute = function (method, url, successCallback, errorCallback, payload, count) { + privateMethods.execute = function (method, url, successCallback, errorCallback, payload, count, contentType, acceptType) { var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.open(method, url); - xmlHttpRequest.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, constants.APPLICATION_JSON); - xmlHttpRequest.setRequestHeader(constants.ACCEPT_IDENTIFIER, constants.APPLICATION_JSON); + if(!contentType){ + contentType = constants.APPLICATION_JSON; + } + if(!acceptType){ + acceptType = constants.APPLICATION_JSON; + } + xmlHttpRequest.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, contentType); + xmlHttpRequest.setRequestHeader(constants.ACCEPT_IDENTIFIER, acceptType); if (IS_OAUTH_ENABLED) { var accessToken = privateMethods.getAccessToken(); if (!accessToken) { @@ -98,9 +104,9 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - privateMethods.initiateXMLHTTPRequest = function (method, url, successCallback, errorCallback, payload) { + privateMethods.initiateXMLHTTPRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { if (privateMethods.getAccessToken()) { - return privateMethods.execute(method, url, successCallback, errorCallback, payload, 0); + return privateMethods.execute(method, url, successCallback, errorCallback, payload, 0, contentType, acceptType); } }; @@ -112,7 +118,7 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload) { + privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; var httpMethodObject; switch (method) { @@ -138,11 +144,11 @@ var backendServiceInvoker = function () { var Header = Packages.org.apache.commons.httpclient.Header; var header = new Header(); header.setName(constants.CONTENT_TYPE_IDENTIFIER); - header.setValue(constants.APPLICATION_JSON); + header.setValue(contentType); httpMethodObject.addRequestHeader(header); header = new Header(); header.setName(constants.ACCEPT_IDENTIFIER); - header.setValue(constants.APPLICATION_JSON); + header.setValue(acceptType); httpMethodObject.addRequestHeader(header); if (IS_OAUTH_ENABLED) { var accessToken = privateMethods.getAccessToken(); @@ -226,8 +232,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicXMLHTTPInvokers.get = function (url, successCallback, errorCallback) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_GET, url, successCallback, errorCallback); + publicXMLHTTPInvokers.get = function (url, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateXMLHTTPRequest(constants.HTTP_GET, url, successCallback, errorCallback, contentType, acceptType); }; /** @@ -237,8 +243,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicXMLHTTPInvokers.post = function (url, payload, successCallback, errorCallback) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload); + publicXMLHTTPInvokers.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateXMLHTTPRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload, contentType, acceptType); }; /** @@ -248,8 +254,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicXMLHTTPInvokers.put = function (url, payload, successCallback, errorCallback) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload); + publicXMLHTTPInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateXMLHTTPRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType); }; /** @@ -258,8 +264,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicXMLHTTPInvokers.delete = function (url, successCallback, errorCallback) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_DELETE, url, successCallback, errorCallback); + publicXMLHTTPInvokers.delete = function (url, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateXMLHTTPRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType); }; /** @@ -281,8 +287,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.get = function (url, successCallback, errorCallback) { - return privateMethods.initiateHTTPClientRequest(constants.HTTP_GET, url, successCallback, errorCallback); + publicHTTPClientInvokers.get = function (url, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateHTTPClientRequest(constants.HTTP_GET, url, successCallback, errorCallback, contentType, acceptType); }; /** @@ -292,9 +298,9 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback) { + publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) { return privateMethods. - initiateHTTPClientRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload); + initiateHTTPClientRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload, contentType, acceptType); }; /** @@ -304,8 +310,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback) { - return privateMethods.initiateHTTPClientRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload); + publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateHTTPClientRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType); }; /** @@ -314,8 +320,8 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback) { - return privateMethods.initiateHTTPClientRequest(constants.HTTP_DELETE, url, successCallback, errorCallback); + publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback, contentType, acceptType) { + return privateMethods.initiateHTTPClientRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType); }; var publicInvokers = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js index 00aa67e7d5..c94345469f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js @@ -22,33 +22,39 @@ var invokerUtil = function () { var END_POINT = window.location.origin+"/devicemgt/api/invoker/execute/"; - module.get = function (url, successCallback, errorCallback) { + module.get = function (url, successCallback, errorCallback, contentType, acceptType) { var payload = null; - execute("GET", url, payload, successCallback, errorCallback); + execute("GET", url, payload, successCallback, errorCallback, contentType, acceptType); }; - module.post = function (url, payload, successCallback, errorCallback) { - execute("POST", url, payload, successCallback, errorCallback); + module.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) { + execute("POST", url, payload, successCallback, errorCallback, contentType, acceptType); }; - module.put = function (url, payload, successCallback, errorCallback) { - execute("PUT", url, payload, successCallback, errorCallback); + module.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { + execute("PUT", url, payload, successCallback, errorCallback, contentType, acceptType); }; - module.delete = function (url, successCallback, errorCallback) { + module.delete = function (url, successCallback, errorCallback, contentType, acceptType) { var payload = null; - execute("DELETE", url, payload, successCallback, errorCallback); + execute("DELETE", url, payload, successCallback, errorCallback, contentType, acceptType); }; - function execute (methoad, url, payload, successCallback, errorCallback) { + function execute (methoad, url, payload, successCallback, errorCallback, contentType, acceptType) { + if(contentType == undefined){ + contentType = "application/json"; + } + if(acceptType == undefined){ + acceptType = "application/json"; + } var data = { url: END_POINT, type: "POST", - contentType: "application/json", - accept: "application/json", + contentType: contentType, + accept: acceptType, success: successCallback }; console.log(data); var paramValue = {}; paramValue.actionMethod = methoad; paramValue.actionUrl = url; - paramValue.actionPayload = JSON.stringify(payload); + paramValue.actionPayload = payload; data.data = JSON.stringify(paramValue); $.ajax(data).fail(function (jqXHR) { if (jqXHR.status == "401") { From 2d44ec234b76cefc0365c4decfe24f6ce4c58832 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Wed, 20 Apr 2016 13:38:36 +0530 Subject: [PATCH 05/10] Now operations are auto generated and supports query params, path params and form params. --- .../feature/mgt/util/AnnotationUtil.java | 178 +++++++++++------- 1 file changed, 111 insertions(+), 67 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java index 621de44372..8941ad0312 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java @@ -35,6 +35,9 @@ import javax.ws.rs.HttpMethod; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; @@ -61,7 +64,8 @@ public class AnnotationUtil { private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework"; public static final String STRING_ARR = "string_arr"; public static final String STRING = "string"; - private Class featureClazz; + private Class + featureAnnotationClazz; private ClassLoader classLoader; private ServletContext servletContext; @@ -108,7 +112,7 @@ public class AnnotationUtil { if (deviceTypeAnno != null) { Method[] deviceTypeMethod = deviceTypeClazz.getMethods(); String deviceType = invokeMethod(deviceTypeMethod[0], deviceTypeAnno, STRING); - featureClazz = + featureAnnotationClazz = (Class) classLoader.loadClass( org.wso2.carbon.device.mgt.extensions.feature.mgt @@ -130,80 +134,120 @@ public class AnnotationUtil { return features; } - private List getFeatures(Method[] annotatedMethods) throws Throwable { + private List getFeatures(Method[] methodsList) throws Throwable { List featureList = new ArrayList<>(); - for (Method method : annotatedMethods) { - Annotation methodAnnotation = method.getAnnotation(featureClazz); - if (methodAnnotation != null) { - Annotation[] annotations = method.getDeclaredAnnotations(); + for (Method currentMethod : methodsList) { + Annotation featureAnnotation = currentMethod.getAnnotation(featureAnnotationClazz); + if (featureAnnotation != null) { + Feature feature = new Feature(); + feature = processFeatureAnnotation(feature, currentMethod); + Annotation[] annotations = currentMethod.getDeclaredAnnotations(); + Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); + metadataEntry.setId(-1); + Map apiParams = new HashMap<>(); for (int i = 0; i < annotations.length; i++) { - if (annotations[i].annotationType().getName().equals( - org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature.class.getName())) { - Feature feature = new Feature(); - Method[] featureAnnoMethods = featureClazz.getMethods(); - Annotation featureAnno = method.getAnnotation(featureClazz); - - for (int k = 0; k < featureAnnoMethods.length; k++) { - switch (featureAnnoMethods[k].getName()) { - case "name": - feature.setName(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); - break; - case "code": - feature.setCode(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); - break; - case "description": - feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); - break; - case "type": - feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); - break; - } - } - //Extracting method with which feature is exposed - if (annotations[i].annotationType().getName().equals(GET.class.getName())) { - feature.setMethod(HttpMethod.GET); - } - if (annotations[i].annotationType().getName().equals(POST.class.getName())) { - feature.setMethod(HttpMethod.POST); - } - if (annotations[i].annotationType().getName().equals(OPTIONS.class.getName())) { - feature.setMethod(HttpMethod.OPTIONS); - } - if (annotations[i].annotationType().getName().equals(DELETE.class.getName())) { - feature.setMethod(HttpMethod.DELETE); - } - if (annotations[i].annotationType().getName().equals(PUT.class.getName())) { - feature.setMethod(HttpMethod.PUT); - } - try { - Class formParamClazz = (Class) classLoader.loadClass( - FormParam.class.getName()); - Method[] formMethods = formParamClazz.getMethods(); - //Extract method parameter information and store same as feature meta info - List metaInfoList = new ArrayList<>(); - Annotation[][] paramAnnotations = method.getParameterAnnotations(); - for (int j = 0; j < paramAnnotations.length; j++) { - for (Annotation anno : paramAnnotations[j]) { - if (anno.annotationType().getName().equals(FormParam.class.getName())) { - Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry(); - metadataEntry.setId(j); - metadataEntry.setValue(invokeMethod(formMethods[0], anno, STRING)); - metaInfoList.add(metadataEntry); - } - } - } - feature.setMetadataEntries(metaInfoList); - } catch (ClassNotFoundException e) { - log.debug("No Form Param found for class " + featureClazz.getName()); - } - featureList.add(feature); + Annotation currentAnnotation = annotations[i]; + feature = processHttpMethodAnnotation(feature, currentAnnotation); + if (currentAnnotation.annotationType().getName().equals(Path.class.getName())) { + String uri = getPathAnnotationValue(currentMethod); + apiParams.put("uri", uri); } + apiParams = processParamAnnotations(apiParams, currentMethod); } + metadataEntry.setValue(apiParams); + List metaInfoList = new ArrayList<>(); + metaInfoList.add(metadataEntry); + feature.setMetadataEntries(metaInfoList); + featureList.add(feature); } } return featureList; } + private Map processParamAnnotations(Map apiParams, Method currentMethod) throws Throwable{ + try { + apiParams.put("pathParams", processParamAnnotations(currentMethod, PathParam.class)); + apiParams.put("queryParams", processParamAnnotations(currentMethod, QueryParam.class)); + apiParams.put("formParams", processParamAnnotations(currentMethod, FormParam.class)); + } catch (ClassNotFoundException e) { + log.debug("No Form Param found for class " + featureAnnotationClazz.getName()); + } + return apiParams; + } + + private List processParamAnnotations(Method currentMethod, Class clazz) throws Throwable{ + List params = new ArrayList<>(); + try { + Class paramClazz = (Class) classLoader.loadClass(clazz.getName()); + Method[] formMethods = paramClazz.getMethods(); + //Extract method parameter information and store same as feature meta info + Annotation[][] paramAnnotations = currentMethod.getParameterAnnotations(); + Method valueMethod = formMethods[0]; + for (int j = 0; j < paramAnnotations.length; j++) { + for (Annotation anno : paramAnnotations[j]) { + if (anno.annotationType().getName().equals(clazz.getName())) { + params.add(invokeMethod(valueMethod, anno, STRING)); + } + } + } + } catch (ClassNotFoundException e) { + log.debug("No "+ clazz.getName() +" Param found for class " + featureAnnotationClazz.getName()); + } + return params; + } + + private Feature processHttpMethodAnnotation(Feature feature, Annotation currentAnnotation) { + //Extracting method with which feature is exposed + if (currentAnnotation.annotationType().getName().equals(GET.class.getName())) { + feature.setMethod(HttpMethod.GET); + } else if (currentAnnotation.annotationType().getName().equals(POST.class.getName())) { + feature.setMethod(HttpMethod.POST); + } else if (currentAnnotation.annotationType().getName().equals(OPTIONS.class.getName())) { + feature.setMethod(HttpMethod.OPTIONS); + } else if (currentAnnotation.annotationType().getName().equals(DELETE.class.getName())) { + feature.setMethod(HttpMethod.DELETE); + } else if (currentAnnotation.annotationType().getName().equals(PUT.class.getName())) { + feature.setMethod(HttpMethod.PUT); + } + return feature; + } + + private Feature processFeatureAnnotation(Feature feature, Method currentMethod) throws Throwable{ + Method[] featureAnnoMethods = featureAnnotationClazz.getMethods(); + Annotation featureAnno = currentMethod.getAnnotation(featureAnnotationClazz); + for (int k = 0; k < featureAnnoMethods.length; k++) { + switch (featureAnnoMethods[k].getName()) { + case "name": + feature.setName(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + case "code": + feature.setCode(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + case "description": + feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + case "type": + feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING)); + break; + } + } + return feature; + } + + public String getPathAnnotationValue(Method currentMethod) throws Throwable{ + String uri = ""; + try { + Class pathClazz = (Class) classLoader.loadClass(Path.class.getName()); + Annotation pathAnnno = currentMethod.getAnnotation(pathClazz); + Method[] pathMethods = pathClazz.getMethods(); + Method valueMethod = pathMethods[0]; + uri = invokeMethod(valueMethod, pathAnnno, STRING); + } catch (ClassNotFoundException e) { + log.debug("No Path Param found for class " + featureAnnotationClazz.getName()); + } + return uri; + } + /** * When an annotation and method is passed, this method invokes that executes said method against the annotation */ From 6ec5b7a85a21ae0d489e313b196639d3b8b48e3c Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Wed, 20 Apr 2016 13:42:25 +0530 Subject: [PATCH 06/10] Reading Http Method from Features --- .../resources/jaggeryapps/devicemgt/app/modules/operation.js | 1 + 1 file changed, 1 insertion(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js index 75c9abe9e7..c621975708 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js @@ -60,6 +60,7 @@ var operationModule = function () { } feature["operation"] = features[i].code; feature["name"] = features[i].name; + feature["method"] = features[i].method; feature["description"] = features[i].description; feature["deviceType"] = deviceType; feature["params"] = []; From 69e38b3c9840b6cf017ec322838c01a7e143231a Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Wed, 20 Apr 2016 22:02:31 +0530 Subject: [PATCH 07/10] adding JSON strigify on payload if contentType is json --- .../public/js/invoker-lib.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js index c94345469f..1a7c52198b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js @@ -55,6 +55,9 @@ var invokerUtil = function () { paramValue.actionMethod = methoad; paramValue.actionUrl = url; paramValue.actionPayload = payload; + if(acceptType == "application/json"){ + paramValue.actionPayload = JSON.stringify(payload); + } data.data = JSON.stringify(paramValue); $.ajax(data).fail(function (jqXHR) { if (jqXHR.status == "401") { From 8e7052e012a30915e80e0ebbb3e41179137f864b Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Wed, 20 Apr 2016 22:03:01 +0530 Subject: [PATCH 08/10] adding JSON strigify on payload if contentType is json --- .../public/js/invoker-lib.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js index 1a7c52198b..15679db063 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js @@ -55,7 +55,7 @@ var invokerUtil = function () { paramValue.actionMethod = methoad; paramValue.actionUrl = url; paramValue.actionPayload = payload; - if(acceptType == "application/json"){ + if(contentType == "application/json"){ paramValue.actionPayload = JSON.stringify(payload); } data.data = JSON.stringify(paramValue); From 55a95cca8663746179367d4d36735af90dc20b59 Mon Sep 17 00:00:00 2001 From: GPrathap Date: Wed, 20 Apr 2016 22:08:30 +0530 Subject: [PATCH 09/10] bug fixes --- .../devicemgt/app/modules/login.js | 14 ++-- .../jaggeryapps/devicemgt/app/modules/util.js | 3 +- .../uuf-template-app/lib/modules/auth/auth.js | 70 +++++++++---------- 3 files changed, 47 insertions(+), 40 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 00e57c7d4f..1c014f4ab8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -20,13 +20,19 @@ var onSuccess; var onFail; (function () { - var log = new Log("api/user-api.jag"); - + var log = new Log("/app/modules/login.js"); + var constants = require("/app/modules/constants.js"); onSuccess = function (context) { + var properties; var utility = require("/app/modules/utility.js").utility; var apiWrapperUtil = require("/app/modules/api-wrapper-util.js").apiWrapperUtil; - var properties = {username: context.input.username, password: context.input.password}; - apiWrapperUtil.setupAccessTokenPair("password", properties); + if(context.input.samlToken){ + properties = {samlToken: context.input.samlToken}; + apiWrapperUtil.setupAccessTokenPair(constants.GRANT_TYPE_SAML, properties); + }else{ + properties = {username: context.input.username, password: context.input.password}; + apiWrapperUtil.setupAccessTokenPair(constants.GRANT_TYPE_PASSWORD, properties); + } }; onFail = function (error) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js index 718c79acaf..6b58c5ae1e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js @@ -17,6 +17,7 @@ */ var util = function () { + var log = new Log("/app/modules/util.js"); var module = {}; var Base64 = Packages.org.apache.commons.codec.binary.Base64; var String = Packages.java.lang.String; @@ -123,7 +124,7 @@ var util = function () { xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Authorization", "Basic " + clientKeys); xhr.send("grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=" + - encodeURIComponent(encodedExtractedAssertion) + "&scope=" + "PRODUCTION"); + encodeURIComponent(encodedExtractedAssertion) + "&scope=" + "PRODUCTION"); var tokenPair = {}; if (xhr.status == 200) { var data = parse(xhr.responseText); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js index 73563a8c57..922563ed6b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js @@ -56,7 +56,7 @@ var module = {}; cachedAuthModuleConfigs = authModuleConfigs; } else { log.error("Cannot find User module configurations in application configuration file '" - + constants.FILE_APP_CONF + "'."); + + constants.FILE_APP_CONF + "'."); cachedAuthModuleConfigs = {}; } return cachedAuthModuleConfigs; @@ -85,7 +85,7 @@ var module = {}; return (rv) ? rv : {}; } else { log.error("Cannot find login configurations in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF + "'."); + + "application configuration file '" + constants.FILE_APP_CONF + "'."); return {}; } } @@ -113,7 +113,7 @@ var module = {}; return (rv) ? rv : {}; } else { log.error("Cannot find logout configurations in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF + "'."); + + "application configuration file '" + constants.FILE_APP_CONF + "'."); return {}; } } @@ -133,7 +133,7 @@ var module = {}; cachedSsoConfigs = ssoConfigs; } else { log.error("Cannot find SSO configurations in Auth module configurations in application " - + "configuration file '" + constants.FILE_APP_CONF + "'."); + + "configuration file '" + constants.FILE_APP_CONF + "'."); cachedSsoConfigs = {}; } return cachedSsoConfigs; @@ -156,13 +156,13 @@ var module = {}; if (operation == OPERATION_LOGIN) { configs = getLoginConfigurations(event); pageFullName = (event == EVENT_SUCCESS) ? - configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_PAGE] : - configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_PAGE]; + configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_PAGE] : + configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_PAGE]; } else { configs = getLogoutConfigurations(event); pageFullName = (event == EVENT_SUCCESS) ? - configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_PAGE] : - configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_PAGE]; + configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_PAGE] : + configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_PAGE]; } if (pageFullName) { @@ -173,13 +173,13 @@ var module = {}; return page.definition[constants.PAGE_DEFINITION_URI]; } log.warn("Page '" + pageFullName + "' mentioned in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF - + "' is disabled."); + + "application configuration file '" + constants.FILE_APP_CONF + + "' is disabled."); } else { log.error("Page '" + pageFullName + "' mentioned in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF - + "' does not exists."); + + "application configuration file '" + constants.FILE_APP_CONF + + "' does not exists."); } } return "/"; @@ -207,13 +207,13 @@ var module = {}; if (operation == OPERATION_LOGIN) { configs = getLoginConfigurations(event); scriptFilePath = (event == EVENT_SUCCESS) ? - configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_SCRIPT] : - configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_SCRIPT]; + configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_SCRIPT] : + configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_SCRIPT]; } else { configs = getLogoutConfigurations(event); scriptFilePath = (event == EVENT_SUCCESS) ? - configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_SCRIPT] : - configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_SCRIPT]; + configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_SCRIPT] : + configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_SCRIPT]; } if (!scriptFilePath || (scriptFilePath.length == 0)) { @@ -222,8 +222,8 @@ var module = {}; var scriptFile = new File(scriptFilePath); if (!scriptFile.isExists() || scriptFile.isDirectory()) { log.error("Script '" + scriptFilePath + "' mentioned in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF - + "' does not exists."); + + "application configuration file '" + constants.FILE_APP_CONF + + "' does not exists."); return true; } @@ -265,7 +265,7 @@ var module = {}; } else { // event == EVENT_FAIL redirectUri = getRedirectUri(operation, EVENT_FAIL) + "?error=" + scriptArgument.message - + "&" + constants.URL_PARAM_REFERER + "=" + getRelayState(operation); + + "&" + constants.URL_PARAM_REFERER + "=" + getRelayState(operation); } response.sendRedirect(encodeURI(module.getAppContext() + redirectUri)); } @@ -276,8 +276,8 @@ var module = {}; var identityProviderUrl = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_IDENTITY_PROVIDER_URL]; if (!identityProviderUrl || (identityProviderUrl.length == 0)) { var msg = "Identity Provider URL is not given in SSO configurations in Auth module " - + "configurations in application configuration file '" - + constants.FILE_APP_CONF + "'."; + + "configurations in application configuration file '" + + constants.FILE_APP_CONF + "'."; log.error(msg); response.sendError(500, msg); return null; @@ -286,7 +286,7 @@ var module = {}; var issuer = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_ISSUER]; if (!issuer || (issuer.length == 0)) { var msg = "Issuer is not given in SSO configurations in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF + "'."; + + "application configuration file '" + constants.FILE_APP_CONF + "'."; log.error(msg); response.sendError(500, msg); return null; @@ -316,8 +316,8 @@ var module = {}; var identityProviderUrl = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_IDENTITY_PROVIDER_URL]; if (!identityProviderUrl || (identityProviderUrl.length == 0)) { var msg = "Identity Provider URL is not given in SSO configurations in Auth module " - + "configurations in application configuration file '" - + constants.FILE_APP_CONF + "'."; + + "configurations in application configuration file '" + + constants.FILE_APP_CONF + "'."; log.error(msg); response.sendError(500, msg); return null; @@ -331,7 +331,7 @@ var module = {}; var issuer = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_ISSUER]; if (!issuer || (issuer.length == 0)) { var msg = "Issuer is not given in SSO configurations in Auth module configurations in " - + "application configuration file '" + constants.FILE_APP_CONF + "'."; + + "application configuration file '" + constants.FILE_APP_CONF + "'."; log.error(msg); response.sendError(500, msg); return null; @@ -341,10 +341,10 @@ var module = {}; try { var ssoClient = require("sso").client; encodedSAMLAuthRequest = ssoClient.getEncodedSAMLLogoutRequest(username, - ssoSessionIndex, issuer); + ssoSessionIndex, issuer); } catch (e) { log.error("Cannot create SAML logout authorization token for user '" + username - + "' with issuer '" + issuer + "'."); + + "' with issuer '" + issuer + "'."); log.error(e.message, e); response.sendError(500, e.message); return null; @@ -446,17 +446,17 @@ var module = {}; intermediatePage = utils.getFurthestChild(intermediatePage); if (!intermediatePage.disabled) { renderer.renderUiComponent(intermediatePage, requestParams, renderingContext, - lookupTable, response); + lookupTable, response); return; } log.warn("Intermediate page '" + intermediatePageName + " mentioned in Auth module " - + "configurations in application configuration file '" - + constants.FILE_APP_CONF + "' is disabled."); + + "configurations in application configuration file '" + + constants.FILE_APP_CONF + "' is disabled."); } else { log.error("Intermediate page '" + intermediatePageName - + " mentioned in Auth module " - + "configurations in application configuration file '" - + constants.FILE_APP_CONF + "' does not exists."); + + " mentioned in Auth module " + + "configurations in application configuration file '" + + constants.FILE_APP_CONF + "' does not exists."); } } @@ -528,13 +528,13 @@ var module = {}; * string}} */ var ssoSession = ssoClient.decodeSAMLLoginResponse(samlResponseObj, samlResponse, - session.getId()); + session.getId()); if (ssoSession.sessionId) { var ssoSessions = getSsoSessions(); ssoSessions[ssoSession.sessionId] = ssoSession; var carbonUser = (require("carbon")).server.tenantUser(ssoSession.loggedInUser); utils.setCurrentUser(carbonUser.username, carbonUser.domain, carbonUser.tenantId); - var scriptArgument = {input: {}, user: module.getCurrentUser()}; + var scriptArgument = {input: {samlToken: ssoSession.samlToken}, user: module.getCurrentUser()}; handleEvent(OPERATION_LOGIN, EVENT_SUCCESS, scriptArgument); } else { var msg = "Cannot decode SAML login response."; From 84492d70acdab0794de247d015c8ee139e127e66 Mon Sep 17 00:00:00 2001 From: GPrathap Date: Wed, 20 Apr 2016 22:10:04 +0530 Subject: [PATCH 10/10] added constants for authentications types --- .../jaggeryapps/devicemgt/app/modules/api-wrapper-util.js | 7 ++++--- .../jaggeryapps/devicemgt/app/modules/constants.js | 7 +++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js index 76474fb098..1a518bcf22 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js @@ -20,6 +20,7 @@ var apiWrapperUtil = function () { var module = {}; var tokenUtil = require("/app/modules/util.js").util; var constants = require("/app/modules/constants.js"); + var constants = require("/app/modules/constants.js"); module.refreshToken = function () { var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); @@ -32,12 +33,12 @@ var apiWrapperUtil = function () { var clientData = tokenUtil.getDyanmicCredentials(properties); var encodedClientKeys = tokenUtil.encode(clientData.clientId + ":" + clientData.clientSecret); session.put(constants.ENCODED_CLIENT_KEYS_IDENTIFIER, encodedClientKeys); - if (type == "password") { + if (type == constants.GRANT_TYPE_PASSWORD) { tokenPair = tokenUtil.getTokenWithPasswordGrantType(properties.username, encodeURIComponent(properties.password), encodedClientKeys); - } else if (type == "saml") { + } else if (type == constants.GRANT_TYPE_SAML) { tokenPair = tokenUtil. - getTokenWithSAMLGrantType(properties.samlToken, encodedClientKeys, "PRODUCTION"); + getTokenWithSAMLGrantType(properties.samlToken, encodedClientKeys, "PRODUCTION"); } session.put(constants.ACCESS_TOKEN_PAIR_IDENTIFIER, tokenPair); }; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js index f5a5b83348..9e2d1469fb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js @@ -48,8 +48,8 @@ var LANGUAGE_US = "en_US"; var VENDOR_APPLE = "Apple"; var ERRORS = { - "USER_NOT_FOUND": "USER_NOT_FOUND" - }; + "USER_NOT_FOUND": "USER_NOT_FOUND" +}; var USER_STORES_NOISY_CHAR = "\""; var USER_STORES_SPLITTING_CHAR = "\\n"; @@ -70,6 +70,9 @@ var HTTP_POST = "POST"; var HTTP_PUT = "PUT"; var HTTP_DELETE = "DELETE"; +var GRANT_TYPE_PASSWORD = "password"; +var GRANT_TYPE_SAML = "saml"; + var MQTT_QUEUE_CONFIG_NAME = "MQTT"; var HTTP_CONFLICT = 409;