Refactoring admin jax-rs to comply with restructured cdm

revert-dabc3590
charithag 9 years ago
parent 8b867e5846
commit 29486fedd5

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
~ 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, ~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except ~ Version 2.0 (the "License"); you may not use this file except
@ -18,23 +18,13 @@
~ under the License. ~ under the License.
--> -->
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation=" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="GroupManager" address="/group_manager">
<jaxrs:serviceBeans>
<bean id="GroupManagerService"
class="org.wso2.carbon.device.mgt.iot.api.GroupManagerService"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="DevicesManager" address="/device_manager"> <jaxrs:server id="DevicesManager" address="/device_manager">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="DevicesManagerService" <bean id="DevicesManagerService"

@ -18,7 +18,6 @@
package org.wso2.carbon.mdm.api; package org.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; 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.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.mdm.api.common.MDMAPIException; 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.EnrollmentCertificate; import org.wso2.carbon.mdm.beans.EnrollmentCertificate;
import org.wso2.carbon.mdm.exception.*; import org.wso2.carbon.mdm.exception.Message;
import org.wso2.carbon.mdm.exception.BadRequestException;
import org.wso2.carbon.mdm.util.MDMUtil;
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.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; 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. * 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" }) @Consumes({ "application/json", "application/xml" })
public class Certificate { public class Certificate {
@ -57,18 +62,16 @@ public class Certificate {
* @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as
* a pem and a serial number. * a pem and a serial number.
* @return Status of the data persist operation. * @return Status of the data persist operation.
* @throws MDMAPIException
*/ */
@POST @POST
@Path("saveCertificate") @Path("saveCertificate")
public Response saveCertificate(@HeaderParam("Accept") String acceptHeader, public Response saveCertificate(@HeaderParam("Accept") String acceptHeader,
EnrollmentCertificate[] enrollmentCertificates) throws MDMAPIException { EnrollmentCertificate[] enrollmentCertificates) {
MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
CertificateManagementService certificateService; CertificateManagementService certificateService;
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<org.wso2.carbon List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
.certificate.mgt.core.bean.Certificate>();
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate;
certificateService = MDMAPIUtils.getCertificateManagementService(); certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
try { try {
for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) {
certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
@ -83,7 +86,7 @@ public class Certificate {
} catch (KeystoreException e) { } catch (KeystoreException e) {
String msg = "Error occurred while converting PEM file to X509Certificate."; String msg = "Error occurred while converting PEM file to X509Certificate.";
log.error(msg, e); 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. * @param serialNumber serial of the certificate needed.
* @return certificate response. * @return certificate response.
* @throws MDMAPIException
*/ */
@GET @GET
@Path("{serialNumber}") @Path("{serialNumber}")
public Response getCertificate(@HeaderParam("Accept") String acceptHeader, public Response getCertificate(@HeaderParam("Accept") String acceptHeader,
@PathParam("serialNumber") String serialNumber) throws MDMAPIException { @PathParam("serialNumber") String serialNumber) {
MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
Message message = new Message(); Message message = new Message();
if (serialNumber == null || serialNumber.isEmpty()) { if (serialNumber == null || serialNumber.isEmpty()) {
message.setErrorMessage("Invalid serial number"); message.setErrorMessage("Invalid serial number");
message.setDiscription("Serial number is missing or invalid."); 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; CertificateResponse certificateResponse;
try { try {
certificateResponse = certificateService.getCertificateBySerial(serialNumber); certificateResponse = certificateService.getCertificateBySerial(serialNumber);
@ -118,7 +120,7 @@ public class Certificate {
} catch (KeystoreException e) { } catch (KeystoreException e) {
String msg = "Error occurred while converting PEM file to X509Certificate"; String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e); 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("start") int startIndex,
@QueryParam("length") int length) @QueryParam("length") int length)
throws MDMAPIException { throws MDMAPIException {
MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
Message message = new Message(); Message message = new Message();
if (startIndex < 0) { if (startIndex < 0) {
message.setErrorMessage("Invalid start index."); message.setErrorMessage("Invalid start index.");
message.setDiscription("Start index cannot be less that 0."); 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) { } else if (length <= 0) {
message.setErrorMessage("Invalid length value."); message.setErrorMessage("Invalid length value.");
message.setDiscription("Length should be a positive integer."); 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); PaginationRequest paginationRequest = new PaginationRequest(startIndex, length);
try { try {
PaginationResult certificates = certificateService.getAllCertificates(paginationRequest); PaginationResult certificates = certificateService.getAllCertificates(paginationRequest);
@ -157,7 +159,7 @@ public class Certificate {
} catch (CertificateManagementDAOException e) { } catch (CertificateManagementDAOException e) {
String msg = "Error occurred while fetching all certificates."; String msg = "Error occurred while fetching all certificates.";
log.error(msg, e); 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}") @Path("{serialNumber}")
public Response removeCertificate(@HeaderParam("Accept") String acceptHeader, public Response removeCertificate(@HeaderParam("Accept") String acceptHeader,
@PathParam("serialNumber") String serialNumber) throws MDMAPIException { @PathParam("serialNumber") String serialNumber) throws MDMAPIException {
MediaType responseMediaType = MDMAPIUtils.getResponseMediaType(acceptHeader); MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
Message message = new Message(); Message message = new Message();
if (serialNumber == null || serialNumber.isEmpty()) { if (serialNumber == null || serialNumber.isEmpty()) {
message.setErrorMessage("Invalid serial number"); message.setErrorMessage("Invalid serial number");
message.setDiscription("Serial number is missing or invalid."); 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; boolean deleted;
try { try {
deleted = certificateService.removeCertificate(serialNumber); deleted = certificateService.removeCertificate(serialNumber);
@ -186,7 +188,7 @@ public class Certificate {
} catch (CertificateManagementDAOException e) { } catch (CertificateManagementDAOException e) {
String msg = "Error occurred while converting PEM file to X509Certificate"; String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e); log.error(msg, e);
return Response.serverError().build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
} }
} }
} }

@ -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.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; 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.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAppConstants; import org.wso2.carbon.mdm.api.util.MDMAppConstants;
import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import javax.jws.WebService; import javax.ws.rs.Consumes;
import javax.ws.rs.*; 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 javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -40,38 +42,37 @@ import java.util.List;
* General Tenant Configuration REST-API implementation. * General Tenant Configuration REST-API implementation.
* All end points support JSON, XMl with content negotiation. * 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" }) @Consumes({ "application/json", "application/xml" })
public class Configuration { public class Configuration {
private static Log log = LogFactory.getLog(Configuration.class); private static Log log = LogFactory.getLog(Configuration.class);
@POST @POST
public ResponsePayload saveTenantConfiguration(TenantConfiguration configuration) public Response saveTenantConfiguration(TenantConfiguration configuration) {
throws MDMAPIException {
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
//Schedule the task service //Schedule the task service
MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration)); DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
Response.status(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Tenant configuration saved successfully."); responseMsg.setMessageFromServer("Tenant configuration saved successfully.");
responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setStatusCode(HttpStatus.SC_CREATED);
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (ConfigurationManagementException e) { } catch (ConfigurationManagementException e) {
String msg = "Error occurred while saving the tenant configuration."; String msg = "Error occurred while saving the tenant configuration.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@GET @GET
public TenantConfiguration getConfiguration() throws MDMAPIException { public Response getConfiguration() {
String msg; String msg;
try { try {
TenantConfiguration tenantConfiguration = MDMAPIUtils.getTenantConfigurationManagementService(). TenantConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService().
getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
ConfigurationEntry configurationEntry = new ConfigurationEntry(); ConfigurationEntry configurationEntry = new ConfigurationEntry();
configurationEntry.setContentType("text"); configurationEntry.setContentType("text");
@ -79,34 +80,33 @@ public class Configuration {
configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency()); configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency());
List<ConfigurationEntry> configList = tenantConfiguration.getConfiguration(); List<ConfigurationEntry> configList = tenantConfiguration.getConfiguration();
if (configList == null) { if (configList == null) {
configList = new ArrayList<ConfigurationEntry>(); configList = new ArrayList<>();
} }
configList.add(configurationEntry); configList.add(configurationEntry);
tenantConfiguration.setConfiguration(configList); tenantConfiguration.setConfiguration(configList);
return tenantConfiguration; return Response.status(Response.Status.OK).entity(tenantConfiguration).build();
} catch (ConfigurationManagementException e) { } catch (ConfigurationManagementException e) {
msg = "Error occurred while retrieving the tenant configuration."; msg = "Error occurred while retrieving the tenant configuration.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@PUT @PUT
public ResponsePayload updateConfiguration(TenantConfiguration configuration) throws MDMAPIException { public Response updateConfiguration(TenantConfiguration configuration) {
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
//Schedule the task service //Schedule the task service
MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration)); DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
Response.status(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Tenant configuration updated successfully."); responseMsg.setMessageFromServer("Tenant configuration updated successfully.");
responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setStatusCode(HttpStatus.SC_CREATED);
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (ConfigurationManagementException e) { } catch (ConfigurationManagementException e) {
String msg = "Error occurred while updating the tenant configuration."; String msg = "Error occurred while updating the tenant configuration.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }

@ -21,14 +21,20 @@ package org.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload; 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.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@ -36,25 +42,24 @@ import java.util.List;
/** /**
* Device related operations * Device related operations
*/ */
public class MobileDevice { @SuppressWarnings("NonJaxWsWebServices")
private static Log log = LogFactory.getLog(MobileDevice.class); 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. * 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. * Hence had to put lot of query params here.
* *
* @return Device List * @return Device List
* @throws MDMAPIException
*/ */
@GET @GET
public Object getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user, public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user,
@QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status, @QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status,
@QueryParam("start") int startIdx, @QueryParam("length") int length, @QueryParam("start") int startIdx, @QueryParam("length") int length,
@QueryParam("device-name") String deviceName, @QueryParam("device-name") String deviceName,
@QueryParam("ownership") EnrolmentInfo.OwnerShip ownership @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) {
) throws MDMAPIException {
try { try {
DeviceManagementProviderService service = MDMAPIUtils.getDeviceManagementService(); DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService();
//Length > 0 means this is a pagination request. //Length > 0 means this is a pagination request.
if (length > 0) { if (length > 0) {
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length); PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
@ -67,10 +72,10 @@ public class MobileDevice {
paginationRequest.setStatus(status.toString()); paginationRequest.setStatus(status.toString());
} }
paginationRequest.setDeviceType(type); paginationRequest.setDeviceType(type);
return service.getAllDevices(paginationRequest); return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build();
} }
List<Device> allDevices = null; List<org.wso2.carbon.device.mgt.common.Device> allDevices;
if ((type != null) && !type.isEmpty()) { if ((type != null) && !type.isEmpty()) {
allDevices = service.getAllDevices(type); allDevices = service.getAllDevices(type);
} else if ((user != null) && !user.isEmpty()) { } else if ((user != null) && !user.isEmpty()) {
@ -84,11 +89,11 @@ public class MobileDevice {
} else { } else {
allDevices = service.getAllDevices(); allDevices = service.getAllDevices();
} }
return allDevices; return Response.status(Response.Status.OK).entity(allDevices).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the device list."; String msg = "Error occurred while fetching the device list.";
log.error(msg, e); 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. * Fetch device details for a given device type and device Id.
* *
* @return Device wrapped inside Response * @return Device wrapped inside Response
* @throws MDMAPIException
*/ */
@GET @GET
@Path("view") @Path("view")
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getDevice(@QueryParam("type") String type, public Response getDevice(@QueryParam("type") String type,
@QueryParam("id") String id) throws MDMAPIException { @QueryParam("id") String id) {
DeviceIdentifier deviceIdentifier = MDMAPIUtils.instantiateDeviceIdentifier(type, id); DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
Device device; org.wso2.carbon.device.mgt.common.Device device;
try { try {
device = deviceManagementProviderService.getDevice(deviceIdentifier); device = deviceManagementProviderService.getDevice(deviceIdentifier);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String error = "Error occurred while fetching the device information."; String msg = "Error occurred while fetching the device information.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
if (device == null) { if (device == null) {
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
responsePayload.setMessageFromServer("Requested device by type: " + responsePayload.setMessageFromServer("Requested device by type: " +
type + " and id: " + id + " does not exist."); 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 { } else {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + "."); responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + ".");
responsePayload.setResponseContent(device); 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 user User Name
* @param tenantDomain tenant domain
* @return Device * @return Device
* @throws MDMAPIException
*/ */
@GET @GET
@Path("user/{user}/{tenantDomain}") @Path("user/{user}")
public List<Device> getDeviceByUser(@PathParam("user") String user, public Response getDevice(@PathParam("user") String user) {
@PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { List<org.wso2.carbon.device.mgt.common.Device> devices;
List<Device> devices;
try { try {
devices = MDMAPIUtils.getDeviceManagementService().getDevicesOfUser(user); devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user);
if (devices == null) { if (devices == null) {
Response.status(Response.Status.NOT_FOUND); return Response.status(Response.Status.NOT_FOUND).build();
}
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();
}
} }
return devices;
/**
* 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) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the devices list of given user."; String msg = "Error occurred while fetching the devices list of given user.";
log.error(msg, e); 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 * Get current device count
* *
* @return device count * @return device count
* @throws MDMAPIException
*/ */
@GET @GET
@Path("count") @Path("count")
public int getDeviceCount() throws MDMAPIException { public Response getDeviceCount() {
try { try {
return MDMAPIUtils.getDeviceManagementService().getDeviceCount(); Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount();
return Response.status(Response.Status.OK).entity(count).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the device count."; String msg = "Error occurred while fetching the device count.";
log.error(msg, e); 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 deviceName Device name
* @param tenantDomain Callee tenant domain * @param tenantDomain Callee tenant domain
* @return list of devices. * @return list of devices.
* @throws MDMAPIException If some unusual behaviour is observed while fetching the device list
*/ */
@GET @GET
@Path("name/{name}/{tenantDomain}") @Path("name/{name}/{tenantDomain}")
public List<Device> getDevicesByName(@PathParam("name") String deviceName, public Response getDevicesByName(@PathParam("name") String deviceName,
@PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { @PathParam("tenantDomain") String tenantDomain) {
List<org.wso2.carbon.device.mgt.common.Device> devices;
List<Device> devices;
try { try {
devices = MDMAPIUtils.getDeviceManagementService().getDevicesByName(deviceName); devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName);
return Response.status(Response.Status.OK).entity(devices).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the devices list of device name."; String msg = "Error occurred while fetching the devices list of device name.";
log.error(msg, e); 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. * Get the list of available device types.
* *
* @return list of device types. * @return list of device types.
* @throws MDMAPIException If some unusual behaviour is observed while fetching the device list
*/ */
@GET @GET
@Path("types") @Path("types")
public List<DeviceType> getDeviceTypes() throws MDMAPIException { public Response getDeviceTypes() {
List<DeviceType> deviceTypes; List<DeviceType> deviceTypes;
try { try {
deviceTypes = MDMAPIUtils.getDeviceManagementService().getAvailableDeviceTypes(); deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes();
return Response.status(Response.Status.OK).entity(deviceTypes).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types."; String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
return deviceTypes;
} }
} }

@ -19,7 +19,6 @@
package org.wso2.carbon.mdm.api; package org.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.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.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; 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.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@SuppressWarnings("NonJaxWsWebServices")
public class DeviceInformation { public class DeviceInformation {
private static Log log = LogFactory.getLog(DeviceInformation.class); private static Log log = LogFactory.getLog(DeviceInformation.class);
@GET @GET
@Path("{type}/{id}") @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; DeviceInformationManager informationManager;
DeviceInfo deviceInfo; DeviceInfo deviceInfo;
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
deviceIdentifier.setType(type); deviceIdentifier.setType(type);
informationManager = MDMAPIUtils.getDeviceInformationManagerService(); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier);
} catch (DeviceDetailsMgtException e) { } catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device information."; String msg = "Error occurred while getting the device information.";
log.error(msg, e); 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 @GET
@Path("location/{type}/{id}") @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; DeviceInformationManager informationManager;
DeviceLocation deviceLocation; DeviceLocation deviceLocation;
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
deviceIdentifier.setType(type); deviceIdentifier.setType(type);
informationManager = MDMAPIUtils.getDeviceInformationManagerService(); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier); deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
} catch (DeviceDetailsMgtException e) { } catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device location."; String msg = "Error occurred while getting the device location.";
log.error(msg, e); 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();
} }
} }

@ -1,10 +1,10 @@
/* /*
* 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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* 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
* *
@ -21,14 +21,18 @@ package org.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
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.api.util.ResponsePayload;
import javax.jws.WebService; import javax.ws.rs.Consumes;
import javax.ws.rs.*; 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 javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@ -36,72 +40,69 @@ import java.util.List;
* DeviceNotification management REST-API implementation. * DeviceNotification management REST-API implementation.
* All end points support JSON, XMl with content negotiation. * All end points support JSON, XMl with content negotiation.
*/ */
@WebService @SuppressWarnings("NonJaxWsWebServices")
@Produces({ "application/json", "application/xml" }) @Produces({"application/json", "application/xml"})
@Consumes({ "application/json", "application/xml" }) @Consumes({ "application/json", "application/xml" })
public class DeviceNotification { public class DeviceNotification {
private static Log log = LogFactory.getLog(Configuration.class); private static Log log = LogFactory.getLog(Configuration.class);
@GET @GET
public List<Notification> getNotifications() throws MDMAPIException { public Response getNotifications() {
String msg; String msg;
try { try {
return MDMAPIUtils.getNotificationManagementService().getAllNotifications(); List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications();
return Response.status(Response.Status.OK).entity(notifications).build();
} catch (NotificationManagementException e) { } catch (NotificationManagementException e) {
msg = "Error occurred while retrieving the notification list."; msg = "Error occurred while retrieving the notification list.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@GET @GET
@Path("{status}") @Path("{status}")
public List<Notification> getNotificationsByStatus(@PathParam("status") Notification.Status status) public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) {
throws MDMAPIException {
String msg; String msg;
try { try {
return MDMAPIUtils.getNotificationManagementService().getNotificationsByStatus(status); List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status);
return Response.status(Response.Status.OK).entity(notifications).build();
} catch (NotificationManagementException e) { } catch (NotificationManagementException e) {
msg = "Error occurred while retrieving the notification list."; msg = "Error occurred while retrieving the notification list.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@PUT @PUT
@Path("{id}/{status}") @Path("{id}/{status}")
public ResponsePayload updateNotificationStatus(@PathParam("id") int id, public Response updateNotificationStatus(@PathParam("id") int id,
@PathParam("status") Notification.Status status) @PathParam("status") Notification.Status status) {
throws MDMAPIException{
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
MDMAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status); DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status);
Response.status(HttpStatus.SC_ACCEPTED);
responseMsg.setMessageFromServer("Notification status updated successfully."); responseMsg.setMessageFromServer("Notification status updated successfully.");
responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED); responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED);
return responseMsg; return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build();
} catch (NotificationManagementException e) { } catch (NotificationManagementException e) {
String msg = "Error occurred while updating notification status."; String msg = "Error occurred while updating notification status.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@POST @POST
public ResponsePayload addNotification(Notification notification) public Response addNotification(Notification notification) {
throws MDMAPIException{
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
MDMAPIUtils.getNotificationManagementService().addNotification(notification); DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification);
Response.status(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Notification has added successfully."); responseMsg.setMessageFromServer("Notification has added successfully.");
responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setStatusCode(HttpStatus.SC_CREATED);
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (NotificationManagementException e) { } catch (NotificationManagementException e) {
String msg = "Error occurred while updating notification status."; String msg = "Error occurred while updating notification status.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }

@ -19,38 +19,37 @@
package org.wso2.carbon.mdm.api; package org.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; 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.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; 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.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class DeviceSearch { public class DeviceSearch {
private static Log log = LogFactory.getLog(DeviceSearch.class); private static Log log = LogFactory.getLog(DeviceSearch.class);
@GET @GET
public Response getDeviceInfo(SearchContext searchContext) throws MDMAPIException { public Response getDeviceInfo(SearchContext searchContext) {
SearchManagerService searchManagerService; SearchManagerService searchManagerService;
List<DeviceWrapper> devices; List<DeviceWrapper> devices;
try { try {
searchManagerService = MDMAPIUtils.getSearchManagerService(); searchManagerService = DeviceMgtAPIUtils.getSearchManagerService();
devices = searchManagerService.search(searchContext); devices = searchManagerService.search(searchContext);
} catch (SearchMgtException e) { } catch (SearchMgtException e) {
String msg = "Error occurred while searching the device information."; String msg = "Error occurred while searching the device information.";
log.error(msg, e); 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();
} }
} }

@ -22,15 +22,20 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
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; import java.util.List;
/** /**
* Features * Features
*/ */
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"})
public class Feature { public class Feature {
@ -40,24 +45,21 @@ public class Feature {
* Get all features for Mobile Device Type * Get all features for Mobile Device Type
* *
* @return Feature * @return Feature
* @throws MDMAPIException
*
*/ */
@GET @GET
@Path("/{type}") @Path("/{type}")
public List<org.wso2.carbon.device.mgt.common.Feature> getFeatures(@PathParam("type") String type) public Response getFeatures(@PathParam("type") String type) {
throws MDMAPIException {
List<org.wso2.carbon.device.mgt.common.Feature> features; List<org.wso2.carbon.device.mgt.common.Feature> features;
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
try { try {
dmService = MDMAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
features = dmService.getFeatureManager(type).getFeatures(); features = dmService.getFeatureManager(type).getFeatures();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving the list of features"; String msg = "Error occurred while retrieving the list of features";
log.error(msg, e); 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();
} }
} }

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.api; package org.wso2.carbon.mdm.api;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -29,7 +29,7 @@ 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.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.iot.util.APIUtil; import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -46,7 +46,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
@SuppressWarnings("NonJaxWsWebServices") @SuppressWarnings("NonJaxWsWebServices")
public class GroupManagerService { public class Group {
private static final String DEFAULT_ADMIN_ROLE = "admin"; private static final String DEFAULT_ADMIN_ROLE = "admin";
private static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations"; private static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations";
@ -62,33 +62,31 @@ public class GroupManagerService {
private static final String[] DEFAULT_VIEW_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/view"}; 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 final String[] DEFAULT_VIEW_EVENTS_PERMISSIONS = {"/permission/device-mgt/user/groups/device_events"};
private static Log log = LogFactory.getLog(GroupManagerService.class); private static Log log = LogFactory.getLog(Group.class);
@Path("/groups")
@POST @POST
@Produces("application/json") @Consumes("application/json")
public Response createGroup(@FormParam("groupName") String groupName, public Response createGroup(DeviceGroup group) {
@FormParam("description") String description) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
DeviceGroup group = new DeviceGroup(); if (group == null) {
group.setName(groupName); return Response.status(Response.Status.BAD_REQUEST).build();
group.setDescription(description); }
group.setOwner(owner); group.setOwner(owner);
group.setDateOfCreation(new Date().getTime()); group.setDateOfCreation(new Date().getTime());
group.setDateOfLastUpdate(new Date().getTime()); group.setDateOfLastUpdate(new Date().getTime());
try { try {
GroupManagementProviderService groupManagementService = APIUtil.getGroupManagementProviderService(); GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
groupManagementService.createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); groupManagementService.createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, groupName, owner, groupManagementService.addGroupSharingRole(owner, group.getName(), owner,
DEFAULT_OPERATOR_ROLE, DEFAULT_OPERATOR_ROLE,
DEFAULT_OPERATOR_PERMISSIONS); DEFAULT_OPERATOR_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, groupName, owner, DEFAULT_STATS_MONITOR_ROLE, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_STATS_MONITOR_ROLE,
DEFAULT_STATS_MONITOR_PERMISSIONS); DEFAULT_STATS_MONITOR_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, groupName, owner, DEFAULT_VIEW_POLICIES, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_POLICIES,
DEFAULT_VIEW_POLICIES_PERMISSIONS); DEFAULT_VIEW_POLICIES_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, groupName, owner, DEFAULT_MANAGE_POLICIES, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_MANAGE_POLICIES,
DEFAULT_MANAGE_POLICIES_PERMISSIONS); DEFAULT_MANAGE_POLICIES_PERMISSIONS);
groupManagementService.addGroupSharingRole(owner, groupName, owner, DEFAULT_VIEW_EVENTS, groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_EVENTS,
DEFAULT_VIEW_EVENTS_PERMISSIONS); DEFAULT_VIEW_EVENTS_PERMISSIONS);
return Response.status(Response.Status.CREATED).build(); return Response.status(Response.Status.CREATED).build();
} catch (GroupAlreadyEixistException e) { } catch (GroupAlreadyEixistException e) {
@ -99,14 +97,14 @@ public class GroupManagerService {
} }
} }
@Path("/groups/{owner}/{groupName}") @Path("/{owner}/{groupName}")
@PUT @PUT
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
DeviceGroup deviceGroup) { DeviceGroup deviceGroup) {
try { try {
APIUtil.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner); DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner);
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getErrorMessage(), e); log.error(e.getErrorMessage(), e);
@ -114,12 +112,11 @@ public class GroupManagerService {
} }
} }
@Path("/groups/{owner}/{groupName}") @Path("/{owner}/{groupName}")
@DELETE @DELETE
@Produces("application/json")
public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try { try {
APIUtil.getGroupManagementProviderService().deleteGroup(groupName, owner); DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner);
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage()); log.error(e.getMessage());
@ -127,12 +124,31 @@ public class GroupManagerService {
} }
} }
@Path("/groups")
@GET @GET
@Produces("application/json") @Produces("application/json")
public Response getGroups(@QueryParam("start") int startIndex, @PathParam("rowCount") int rowCount) { public Response getGroups(@QueryParam("start") int startIndex, @PathParam("rowCount") int rowCount) {
try { try {
PaginationResult paginationResult = APIUtil.getGroupManagementProviderService().getGroups(startIndex, rowCount); 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) { if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult).build(); return Response.status(Response.Status.OK).entity(paginationResult).build();
} else { } else {
@ -144,12 +160,12 @@ public class GroupManagerService {
} }
} }
@Path("/groups/{owner}/{groupName}") @Path("/{owner}/{groupName}")
@GET @GET
@Produces("application/json") @Produces("application/json")
public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
try { try {
DeviceGroup deviceGroup = APIUtil.getGroupManagementProviderService().getGroup(groupName, owner); DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner);
if (deviceGroup != null) { if (deviceGroup != null) {
return Response.status(Response.Status.OK).entity(deviceGroup).build(); return Response.status(Response.Status.OK).entity(deviceGroup).build();
} else { } else {
@ -161,13 +177,13 @@ public class GroupManagerService {
} }
} }
@Path("/groups/search") @Path("/search")
@GET @GET
@Produces("application/json") @Produces("application/json")
public Response findGroups(@QueryParam("groupName") String groupName, public Response findGroups(@QueryParam("groupName") String groupName,
@QueryParam("userName") String userName) { @QueryParam("userName") String userName) {
try { try {
List<DeviceGroup> groups = APIUtil.getGroupManagementProviderService() List<DeviceGroup> groups = DeviceMgtAPIUtils.getGroupManagementProviderService()
.findInGroups(groupName, userName); .findInGroups(groupName, userName);
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
groups.toArray(deviceGroups); groups.toArray(deviceGroups);
@ -178,13 +194,13 @@ public class GroupManagerService {
} }
} }
@Path("/groups") @Path("/user/{user}/all")
@GET @GET
@Produces("application/json") @Produces("application/json")
public Response getGroups(@QueryParam("userName") String userName, public Response getGroups(@PathParam("user") String userName,
@QueryParam("permission") String permission) { @QueryParam("permission") String permission) {
try { try {
GroupManagementProviderService groupManagementService = APIUtil.getGroupManagementProviderService(); GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
List<DeviceGroup> groups; List<DeviceGroup> groups;
if (permission != null) { if (permission != null) {
groups = groupManagementService.getGroups(userName, permission); groups = groupManagementService.getGroups(userName, permission);
@ -200,12 +216,12 @@ public class GroupManagerService {
} }
} }
@Path("/groups/count") @Path("/user/{user}/count")
@GET @GET
@Produces("application/json") @Produces("application/json")
public Response getGroupCount(@QueryParam("userName") String userName) { public Response getGroupCount(@PathParam("user") String userName) {
try { try {
int count = APIUtil.getGroupManagementProviderService().getGroupCount(userName); int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName);
return Response.status(Response.Status.OK).entity(count).build(); return Response.status(Response.Status.OK).entity(count).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
@ -213,7 +229,7 @@ public class GroupManagerService {
} }
} }
@Path("/groups/{owner}/{groupName}/share") @Path("/{owner}/{groupName}/share")
@PUT @PUT
@Produces("application/json") @Produces("application/json")
public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@ -221,7 +237,7 @@ public class GroupManagerService {
@FormParam("roleName") String sharingRole) { @FormParam("roleName") String sharingRole) {
try { try {
boolean isShared = APIUtil.getGroupManagementProviderService().shareGroup( boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup(
shareUser, groupName, owner, sharingRole); shareUser, groupName, owner, sharingRole);
if (isShared) { if (isShared) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -234,14 +250,14 @@ public class GroupManagerService {
} }
} }
@Path("/groups/{owner}/{groupName}/unshare") @Path("/{owner}/{groupName}/unshare")
@PUT @PUT
@Produces("application/json") @Produces("application/json")
public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@FormParam("unShareUser") String unShareUser, @FormParam("unShareUser") String unShareUser,
@FormParam("roleName") String sharingRole) { @FormParam("roleName") String sharingRole) {
try { try {
boolean isUnShared = APIUtil.getGroupManagementProviderService().unshareGroup( boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup(
unShareUser, groupName, owner, sharingRole); unShareUser, groupName, owner, sharingRole);
if (isUnShared) { if (isUnShared) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -254,7 +270,7 @@ public class GroupManagerService {
} }
} }
@Path("/groups/{owner}/{groupName}/share/roles/{roleName}/permissions") @Path("/{owner}/{groupName}/share/roles/{roleName}/permissions")
@PUT @PUT
@Produces("application/json") @Produces("application/json")
public Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName, public Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName,
@ -263,7 +279,7 @@ public class GroupManagerService {
@FormParam("permissions") String[] permissions) { @FormParam("permissions") String[] permissions) {
try { try {
boolean isAdded = APIUtil.getGroupManagementProviderService().addGroupSharingRole( boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole(
shareUser, groupName, owner, roleName, permissions); shareUser, groupName, owner, roleName, permissions);
if (isAdded) { if (isAdded) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -277,13 +293,13 @@ public class GroupManagerService {
} }
@DELETE @DELETE
@Path("/groups/{owner}/{groupName}/share/roles/{roleName}/permissions") @Path("/{owner}/{groupName}/share/roles/{roleName}/permissions")
@Produces("application/json") @Produces("application/json")
public Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName, public Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("owner") String owner,
@PathParam("roleName") String roleName) { @PathParam("roleName") String roleName) {
try { try {
boolean isRemoved = APIUtil.getGroupManagementProviderService().removeGroupSharingRole( boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole(
groupName, owner, roleName); groupName, owner, roleName);
if (isRemoved) { if (isRemoved) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -297,16 +313,16 @@ public class GroupManagerService {
} }
@GET @GET
@Path("/groups/{owner}/{groupName}/share/roles") @Path("/{owner}/{groupName}/share/roles")
@Produces("application/json") @Produces("application/json")
public Response getRoles(@PathParam("groupName") String groupName, public Response getRoles(@PathParam("groupName") String groupName,
@PathParam("owner") String owner, @QueryParam("userName") String userName) { @PathParam("owner") String owner, @QueryParam("userName") String userName) {
try { try {
List<String> roles; List<String> roles;
if (userName != null && !userName.isEmpty()) { if (userName != null && !userName.isEmpty()) {
roles = APIUtil.getGroupManagementProviderService().getRoles(userName, groupName, owner); roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner);
} else { } else {
roles = APIUtil.getGroupManagementProviderService().getRoles(groupName, owner); roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
} }
String[] rolesArray = new String[roles.size()]; String[] rolesArray = new String[roles.size()];
roles.toArray(rolesArray); roles.toArray(rolesArray);
@ -318,12 +334,12 @@ public class GroupManagerService {
} }
@GET @GET
@Path("/groups/{owner}/{groupName}/users") @Path("/{owner}/{groupName}/users")
@Produces("application/json") @Produces("application/json")
public Response getUsers(@PathParam("groupName") String groupName, public Response getUsers(@PathParam("groupName") String groupName,
@PathParam("owner") String owner) { @PathParam("owner") String owner) {
try { try {
List<GroupUser> users = APIUtil.getGroupManagementProviderService().getUsers( List<GroupUser> users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers(
groupName, owner); groupName, owner);
GroupUser[] usersArray = new GroupUser[users.size()]; GroupUser[] usersArray = new GroupUser[users.size()];
users.toArray(usersArray); users.toArray(usersArray);
@ -335,12 +351,12 @@ public class GroupManagerService {
} }
@GET @GET
@Path("/groups/{owner}/{groupName}/devices/all") @Path("/{owner}/{groupName}/devices/all")
@Produces("application/json") @Produces("application/json")
public Response getDevices(@PathParam("groupName") String groupName, public Response getDevices(@PathParam("groupName") String groupName,
@PathParam("owner") String owner) { @PathParam("owner") String owner) {
try { try {
List<Device> devices = APIUtil.getGroupManagementProviderService().getDevices( List<Device> devices = DeviceMgtAPIUtils.getGroupManagementProviderService().getDevices(
groupName, owner); groupName, owner);
Device[] deviceArray = new Device[devices.size()]; Device[] deviceArray = new Device[devices.size()];
devices.toArray(deviceArray); devices.toArray(deviceArray);
@ -352,12 +368,12 @@ public class GroupManagerService {
} }
@GET @GET
@Path("/groups/{owner}/{groupName}/devices/count") @Path("/{owner}/{groupName}/devices/count")
@Produces("application/json") @Produces("application/json")
public Response getDeviceCount(@PathParam("groupName") String groupName, public Response getDeviceCount(@PathParam("groupName") String groupName,
@PathParam("owner") String owner) { @PathParam("owner") String owner) {
try { try {
int count = APIUtil.getGroupManagementProviderService().getDeviceCount(groupName, owner); int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner);
return Response.status(Response.Status.OK).entity(count).build(); return Response.status(Response.Status.OK).entity(count).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
@ -366,7 +382,7 @@ public class GroupManagerService {
} }
@PUT @PUT
@Path("/groups/{owner}/{groupName}/devices/{deviceType}/{deviceId}") @Path("/{owner}/{groupName}/devices/{deviceType}/{deviceId}")
@Produces("application/json") @Produces("application/json")
public Response addDevice(@PathParam("groupName") String groupName, public Response addDevice(@PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
@ -374,7 +390,7 @@ public class GroupManagerService {
@FormParam("userName") String userName) { @FormParam("userName") String userName) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
boolean isAdded = APIUtil.getGroupManagementProviderService().addDevice( boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice(
deviceIdentifier, groupName, owner); deviceIdentifier, groupName, owner);
if (isAdded) { if (isAdded) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -388,14 +404,14 @@ public class GroupManagerService {
} }
@DELETE @DELETE
@Path("/groups/{owner}/{groupName}/devices/{deviceType}/{deviceId}") @Path("/{owner}/{groupName}/devices/{deviceType}/{deviceId}")
@Produces("application/json") @Produces("application/json")
public Response removeDevice(@PathParam("groupName") String groupName, public Response removeDevice(@PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType) { @PathParam("deviceType") String deviceType) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
boolean isRemoved = APIUtil.getGroupManagementProviderService().removeDevice( boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice(
deviceIdentifier, groupName, owner); deviceIdentifier, groupName, owner);
if (isRemoved) { if (isRemoved) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -409,13 +425,13 @@ public class GroupManagerService {
} }
@GET @GET
@Path("/groups/{owner}/{groupName}/users/{userName}/permissions") @Path("/{owner}/{groupName}/users/{userName}/permissions")
@Produces("application/json") @Produces("application/json")
public Response getPermissions(@PathParam("userName") String userName, public Response getPermissions(@PathParam("userName") String userName,
@PathParam("groupName") String groupName, @PathParam("groupName") String groupName,
@PathParam("owner") String owner) { @PathParam("owner") String owner) {
try { try {
String[] permissions = APIUtil.getGroupManagementProviderService() String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService()
.getPermissions(userName, groupName, owner); .getPermissions(userName, groupName, owner);
return Response.status(Response.Status.OK).entity(permissions).build(); return Response.status(Response.Status.OK).entity(permissions).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {

@ -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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -10,8 +10,8 @@
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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 * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
@ -22,17 +22,21 @@ import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload; 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.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
/** /**
* This class represents license related operations. * This class represents license related operations.
*/ */
@SuppressWarnings("NonJaxWsWebServices")
public class License { public class License {
private static Log log = LogFactory.getLog(License.class); private static Log log = LogFactory.getLog(License.class);
@ -43,18 +47,17 @@ public class License {
* @param deviceType Device type, ex: android, ios * @param deviceType Device type, ex: android, ios
* @param languageCode Language code, ex: en_US * @param languageCode Language code, ex: en_US
* @return Returns the license text * @return Returns the license text
* @throws MDMAPIException If the device type or language code arguments are not available or invalid.
*/ */
@GET @GET
@Path ("{deviceType}/{languageCode}") @Path ("{deviceType}/{languageCode}")
@Produces ({MediaType.APPLICATION_JSON}) @Produces ({MediaType.APPLICATION_JSON})
public Response getLicense(@PathParam ("deviceType") String deviceType, 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; org.wso2.carbon.device.mgt.common.license.mgt.License license;
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload;
try { try {
license = MDMAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode); license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode);
if (license == null) { if (license == null) {
return Response.status(HttpStatus.SC_NOT_FOUND).build(); return Response.status(HttpStatus.SC_NOT_FOUND).build();
} }
@ -65,9 +68,9 @@ public class License {
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type"; String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type";
log.error(msg, e); 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 deviceType Device type, ex: android, ios
* @param license License object * @param license License object
* @return Returns the acknowledgement for the action * @return Returns the acknowledgement for the action
* @throws MDMAPIException
*/ */
@POST @POST
@Path ("{deviceType}") @Path ("{deviceType}")
public Response addLicense(@PathParam ("deviceType") String 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; ResponsePayload responsePayload;
try { try {
MDMAPIUtils.getDeviceManagementService().addLicense(deviceType, license); DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license);
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK). responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
messageFromServer("License added successfully for '" + deviceType + "' device type"). messageFromServer("License added successfully for '" + deviceType + "' device type").
build(); build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while adding license for '" + deviceType + "' device type"; String msg = "Error occurred while adding license for '" + deviceType + "' device type";
log.error(msg, e); 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();
} }
} }

@ -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.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.context.DeviceOperationContext; 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.MDMAndroidOperationUtil;
import org.wso2.carbon.mdm.api.util.MDMIOSOperationUtil; import org.wso2.carbon.mdm.api.util.MDMIOSOperationUtil;
import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.ApplicationWrapper; import org.wso2.carbon.mdm.beans.ApplicationWrapper;
import org.wso2.carbon.mdm.beans.MobileApp; 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 javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Operation related REST-API implementation. * Operation related REST-API implementation.
*/ */
@SuppressWarnings("NonJaxWsWebServices")
@Produces({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"})
public class Operation { public class Operation {
private static Log log = LogFactory.getLog(Operation.class); private static Log log = LogFactory.getLog(Operation.class);
/* @deprecated */ /* @deprecated */
@GET @GET
public List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> getAllOperations() public Response getAllOperations() {
throws MDMAPIException {
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations; List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
try { try {
dmService = MDMAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operations = dmService.getOperations(null); operations = dmService.getOperations(null);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "Error occurred while fetching the operations for the device."; String msg = "Error occurred while fetching the operations for the device.";
log.error(msg, e); 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 @GET
@Path("paginate/{type}/{id}") @Path("paginate/{type}/{id}")
public PaginationResult getDeviceOperations( public Response getDeviceOperations(
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("start") int startIdx, @PathParam("type") String type, @PathParam("id") String id, @QueryParam("start") int startIdx,
@QueryParam("length") int length, @QueryParam("search") String search) @QueryParam("length") int length, @QueryParam("search") String search) {
throws MDMAPIException {
PaginationResult operations; PaginationResult operations;
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
@ -84,147 +88,133 @@ public class Operation {
try { try {
deviceIdentifier.setType(type); deviceIdentifier.setType(type);
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
dmService = MDMAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operations = dmService.getOperations(deviceIdentifier, paginationRequest); operations = dmService.getOperations(deviceIdentifier, paginationRequest);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "Error occurred while fetching the operations for the device."; String msg = "Error occurred while fetching the operations for the device.";
log.error(msg, e); 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 @GET
@Path("{type}/{id}") @Path("{type}/{id}")
public List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> getDeviceOperations( public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) {
@PathParam("type") String type, @PathParam("id") String id)
throws MDMAPIException {
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations; List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
try { try {
deviceIdentifier.setType(type); deviceIdentifier.setType(type);
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
dmService = MDMAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operations = dmService.getOperations(deviceIdentifier); operations = dmService.getOperations(deviceIdentifier);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "Error occurred while fetching the operations for the device."; String msg = "Error occurred while fetching the operations for the device.";
log.error(msg, e); 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();
} }
/* @deprecated */ /* @deprecated */
@POST @POST
public ResponsePayload addOperation(DeviceOperationContext operationContext) throws MDMAPIException { public Response addOperation(DeviceOperationContext operationContext) {
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
dmService = MDMAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
int operationId = dmService.addOperation(operationContext.getOperation(), int operationId = dmService.addOperation(operationContext.getOperation(), operationContext.getDevices());
operationContext.getDevices()); if (operationId > 0) {
if (operationId>0) { responseMsg.setStatusCode(HttpStatus.SC_CREATED);
Response.status(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Operation has added successfully."); responseMsg.setMessageFromServer("Operation has added successfully.");
} }
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "Error occurred while saving the operation"; String msg = "Error occurred while saving the operation";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@GET @GET
@Path("{type}/{id}/apps") @Path("{type}/{id}/apps")
public List<? extends Application> getInstalledApps( public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) {
@PathParam("type") String type,
@PathParam("id") String id)
throws MDMAPIException {
List<Application> applications; List<Application> applications;
ApplicationManagementProviderService appManagerConnector; ApplicationManagementProviderService appManagerConnector;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
try { try {
deviceIdentifier.setType(type); deviceIdentifier.setType(type);
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
appManagerConnector = MDMAPIUtils.getAppManagementService(); appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier); applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier);
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while fetching the apps of the device."; String msg = "Error occurred while fetching the apps of the device.";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
return applications; return Response.status(Response.Status.CREATED).entity(applications).build();
} }
@POST @POST
@Path("installApp/{tenantDomain}") @Path("installApp/{tenantDomain}")
public ResponsePayload installApplication(ApplicationWrapper applicationWrapper, public Response installApplication(ApplicationWrapper applicationWrapper,
@PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { @PathParam("tenantDomain") String tenantDomain) {
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
ApplicationManager appManagerConnector; ApplicationManager appManagerConnector;
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
ArrayList<DeviceIdentifier> deviceIdentifiers;
try { try {
appManagerConnector = MDMAPIUtils.getAppManagementService(); appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
MobileApp mobileApp = applicationWrapper.getApplication(); MobileApp mobileApp = applicationWrapper.getApplication();
if (applicationWrapper.getDeviceIdentifiers() != null) { if (applicationWrapper.getDeviceIdentifiers() != null) {
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
deviceIdentifiers = new ArrayList<DeviceIdentifier>();
if (deviceIdentifier.getType().equals(Platform.android.toString())) { if (deviceIdentifier.getType().equals(Platform.android.toString())) {
operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp); operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp); operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp);
} }
deviceIdentifiers.add(deviceIdentifier);
} }
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); 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."); responseMsg.setMessageFromServer("Application installation request has been sent to the device.");
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException | MDMAPIException e) {
String msg = "Error occurred while saving the operation"; String msg = "Error occurred while saving the operation";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@POST @POST
@Path("uninstallApp/{tenantDomain}") @Path("uninstallApp/{tenantDomain}")
public ResponsePayload uninstallApplication(ApplicationWrapper applicationWrapper, public Response uninstallApplication(ApplicationWrapper applicationWrapper,
@PathParam("tenantDomain") String tenantDomain) throws MDMAPIException { @PathParam("tenantDomain") String tenantDomain) {
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
ApplicationManager appManagerConnector; ApplicationManager appManagerConnector;
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
ArrayList<DeviceIdentifier> deviceIdentifiers;
try { try {
appManagerConnector = MDMAPIUtils.getAppManagementService(); appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
MobileApp mobileApp = applicationWrapper.getApplication(); MobileApp mobileApp = applicationWrapper.getApplication();
if (applicationWrapper.getDeviceIdentifiers() != null) { if (applicationWrapper.getDeviceIdentifiers() != null) {
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
deviceIdentifiers = new ArrayList<DeviceIdentifier>();
if (deviceIdentifier.getType().equals(Platform.android.toString())) { if (deviceIdentifier.getType().equals(Platform.android.toString())) {
operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp); operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp); operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp);
} }
deviceIdentifiers.add(deviceIdentifier);
} }
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); 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."); responseMsg.setMessageFromServer("Application removal request has been sent to the device.");
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException | MDMAPIException e) {
String msg = "Error occurred while saving the operation"; String msg = "Error occurred while saving the operation";
log.error(msg, e); log.error(msg, e);
throw new MDMAPIException(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
} }

@ -23,7 +23,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.mdm.api.common.MDMAPIException; 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.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.PolicyWrapper; import org.wso2.carbon.mdm.beans.PolicyWrapper;
import org.wso2.carbon.mdm.beans.PriorityUpdatedPolicyWrapper; 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.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; 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.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class Policy { public class Policy {
private static Log log = LogFactory.getLog(Policy.class); private static Log log = LogFactory.getLog(Policy.class);
@POST @POST
@Path("inactive-policy") @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(); ResponsePayload responseMsg = new ResponsePayload();
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
policy.setPolicyName(policyWrapper.getPolicyName()); policy.setPolicyName(policyWrapper.getPolicyName());
@ -62,25 +69,14 @@ public class Policy {
policy.setTenantId(policyWrapper.getTenantId()); policy.setTenantId(policyWrapper.getTenantId());
policy.setCompliance(policyWrapper.getCompliance()); policy.setCompliance(policyWrapper.getCompliance());
try { return addPolicy(policyManagementService, responseMsg, policy);
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);
}
} }
@POST @POST
@Path("active-policy") @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(); ResponsePayload responseMsg = new ResponsePayload();
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
policy.setPolicyName(policyWrapper.getPolicyName()); policy.setPolicyName(policyWrapper.getPolicyName());
@ -94,87 +90,91 @@ public class Policy {
policy.setCompliance(policyWrapper.getCompliance()); policy.setCompliance(policyWrapper.getCompliance());
policy.setActive(true); policy.setActive(true);
return addPolicy(policyManagementService, responseMsg, policy);
}
private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg,
org.wso2.carbon.policy.mgt.common.Policy policy) {
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.addPolicy(policy); pap.addPolicy(policy);
Response.status(HttpStatus.SC_CREATED);
responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Policy has been added successfully."); responseMsg.setMessageFromServer("Policy has been added successfully.");
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@GET @GET
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getAllPolicies() throws MDMAPIException { public Response getAllPolicies() {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<org.wso2.carbon.policy.mgt.common.Policy> policies; List<org.wso2.carbon.policy.mgt.common.Policy> policies;
try { try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicies(); policies = policyAdministratorPoint.getPolicies();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending all retrieved device policies."); responsePayload.setMessageFromServer("Sending all retrieved device policies.");
responsePayload.setResponseContent(policies); responsePayload.setResponseContent(policies);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); return Response.status(Response.Status.OK).entity(responsePayload).build();
} }
@GET @GET
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
@Path("{id}") @Path("{id}")
public Response getPolicy(@PathParam("id") int policyId) throws MDMAPIException { public Response getPolicy(@PathParam("id") int policyId) {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
final org.wso2.carbon.policy.mgt.common.Policy policy; final org.wso2.carbon.policy.mgt.common.Policy policy;
try { try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policy = policyAdministratorPoint.getPolicy(policyId); policy = policyAdministratorPoint.getPolicy(policyId);
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
if (policy == null){ if (policy == null){
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
responsePayload.setMessageFromServer("Policy for ID " + policyId + " 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 responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending all retrieved device policies."); responsePayload.setMessageFromServer("Sending all retrieved device policies.");
responsePayload.setResponseContent(policy); responsePayload.setResponseContent(policy);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); return Response.status(Response.Status.OK).entity(responsePayload).build();
} }
@GET @GET
@Path("count") @Path("count")
public int getPolicyCount() throws MDMAPIException { public Response getPolicyCount() {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try { try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
return policyAdministratorPoint.getPolicyCount(); Integer count = policyAdministratorPoint.getPolicyCount();
return Response.status(Response.Status.OK).entity(count).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@PUT @PUT
@Path("{id}") @Path("{id}")
public ResponsePayload updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) {
throws MDMAPIException {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
policy.setPolicyName(policyWrapper.getPolicyName()); policy.setPolicyName(policyWrapper.getPolicyName());
@ -191,14 +191,13 @@ public class Policy {
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.updatePolicy(policy); pap.updatePolicy(policy);
Response.status(HttpStatus.SC_OK);
responseMsg.setStatusCode(HttpStatus.SC_CREATED); responseMsg.setStatusCode(HttpStatus.SC_CREATED);
responseMsg.setMessageFromServer("Policy has been updated successfully."); responseMsg.setMessageFromServer("Policy has been updated successfully.");
return responseMsg; return Response.status(Response.Status.CREATED).entity(responseMsg).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception in policy update."; String msg = "Policy Management related exception in policy update.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@ -206,11 +205,10 @@ public class Policy {
@Path("priorities") @Path("priorities")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies) public Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies) {
throws MDMAPIException { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService();
List<org.wso2.carbon.policy.mgt.common.Policy> policiesToUpdate = List<org.wso2.carbon.policy.mgt.common.Policy> policiesToUpdate =
new ArrayList<org.wso2.carbon.policy.mgt.common.Policy>(priorityUpdatedPolicies.size()); new ArrayList<>(priorityUpdatedPolicies.size());
int i; int i;
for (i = 0; i < priorityUpdatedPolicies.size(); i++) { for (i = 0; i < priorityUpdatedPolicies.size(); i++) {
org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy(); 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(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate); policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate);
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Exception in updating policy priorities."; String msg = "Exception in updating policy priorities.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
if (policiesUpdated) { if (policiesUpdated) {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy Priorities successfully updated."); 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 { } else {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Policy priorities did not update. 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") @Path("bulk-remove")
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response bulkRemovePolicy(List<Integer> policyIds) throws MDMAPIException { public Response bulkRemovePolicy(List<Integer> policyIds) {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
boolean policyDeleted = true; boolean policyDeleted = true;
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
@ -255,43 +253,42 @@ public class Policy {
} }
} }
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Exception in deleting policies."; String msg = "Exception in deleting policies.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
if (policyDeleted) { if (policyDeleted) {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policies have been successfully deleted."); 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 { } else {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Policy does not exist."); 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 @PUT
@Produces("application/json") @Produces("application/json")
@Path("activate") @Path("activate")
public Response activatePolicy(List<Integer> policyIds) throws MDMAPIException { public Response activatePolicy(List<Integer> policyIds) {
try { try {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
for(int i : policyIds) { for(int i : policyIds) {
pap.activatePolicy(i); pap.activatePolicy(i);
} }
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Exception in activating policies."; String msg = "Exception in activating policies.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Selected policies have been successfully activated."); 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 @PUT
@ -300,132 +297,134 @@ public class Policy {
public Response inactivatePolicy(List<Integer> policyIds) throws MDMAPIException { public Response inactivatePolicy(List<Integer> policyIds) throws MDMAPIException {
try { try {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
for(int i : policyIds) { for(int i : policyIds) {
pap.inactivatePolicy(i); pap.inactivatePolicy(i);
} }
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Exception in inactivating policies."; String msg = "Exception in inactivating policies.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Selected policies have been successfully inactivated."); 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 @PUT
@Produces("application/json") @Produces("application/json")
@Path("apply-changes") @Path("apply-changes")
public Response applyChanges() throws MDMAPIException { public Response applyChanges() {
try { try {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.publishChanges(); pap.publishChanges();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Exception in applying changes."; String msg = "Exception in applying changes.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Changes have been successfully updated."); 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 @GET
@Path("start-task/{milliseconds}") @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 { try {
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
taskScheduleService.startTask(monitoringFrequency); taskScheduleService.startTask(monitoringFrequency);
} catch (PolicyMonitoringTaskException e) { } catch (PolicyMonitoringTaskException e) {
String error = "Policy Management related exception."; String msg = "Policy Management related exception.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy monitoring service started successfully."); 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 @GET
@Path("update-task/{milliseconds}") @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 { try {
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
taskScheduleService.updateTask(monitoringFrequency); taskScheduleService.updateTask(monitoringFrequency);
} catch (PolicyMonitoringTaskException e) { } catch (PolicyMonitoringTaskException e) {
String error = "Policy Management related exception."; String msg = "Policy Management related exception.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy monitoring service updated successfully."); 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 @GET
@Path("stop-task") @Path("stop-task")
public Response stopTaskService() throws MDMAPIException { public Response stopTaskService() {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try { try {
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
taskScheduleService.stopTask(); taskScheduleService.stopTask();
} catch (PolicyMonitoringTaskException e) { } catch (PolicyMonitoringTaskException e) {
String error = "Policy Management related exception."; String msg = "Policy Management related exception.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Policy monitoring service stopped successfully."); 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 @GET
@Path("{type}/{id}") @Path("{type}/{id}")
public ComplianceData getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) throws public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) {
MDMAPIException {
try { try {
DeviceIdentifier deviceIdentifier = MDMAPIUtils.instantiateDeviceIdentifier(type, id); DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
return policyManagementService.getDeviceCompliance(deviceIdentifier); ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier);
return Response.status(Response.Status.OK).entity(complianceData).build();
} catch (PolicyComplianceException e) { } catch (PolicyComplianceException e) {
String error = "Error occurred while getting the compliance data."; String msg = "Error occurred while getting the compliance data.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@GET @GET
@Path("{type}/{id}/active-policy") @Path("{type}/{id}/active-policy")
public org.wso2.carbon.policy.mgt.common.Policy getDeviceActivePolicy(@PathParam("type") String type, public Response getDeviceActivePolicy(@PathParam("type") String type,
@PathParam("id") String id) throws MDMAPIException { @PathParam("id") String id) {
try { try {
DeviceIdentifier deviceIdentifier = MDMAPIUtils.instantiateDeviceIdentifier(type, id); DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
return policyManagementService.getAppliedPolicyToDevice(deviceIdentifier); org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService
.getAppliedPolicyToDevice(deviceIdentifier);
return Response.status(Response.Status.OK).entity(policy).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Error occurred while getting the current policy."; String msg = "Error occurred while getting the current policy.";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
} }

@ -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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -17,11 +17,9 @@
*/ */
package org.wso2.carbon.mdm.api; package org.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload; import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
@ -33,57 +31,55 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@SuppressWarnings("NonJaxWsWebServices")
public class Profile { public class Profile {
private static Log log = LogFactory.getLog(Profile.class); private static Log log = LogFactory.getLog(Profile.class);
@POST @POST
public org.wso2.carbon.policy.mgt.common.Profile addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) throws MDMAPIException { public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
profile = pap.addProfile(profile); profile = pap.addProfile(profile);
Response.status(HttpStatus.SC_CREATED); return Response.status(Response.Status.OK).entity(profile).build();
return profile;
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@POST @POST
@Path("{id}") @Path("{id}")
public ResponsePayload updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile, @PathParam("id") String profileId) public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile,
throws MDMAPIException { @PathParam("id") String profileId) {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
pap.updateProfile(profile); pap.updateProfile(profile);
Response.status(HttpStatus.SC_OK);
responseMsg.setMessageFromServer("Profile has been updated successfully."); responseMsg.setMessageFromServer("Profile has been updated successfully.");
return responseMsg; return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@DELETE @DELETE
@Path("{id}") @Path("{id}")
public ResponsePayload deleteProfile(@PathParam("id") int profileId) throws MDMAPIException { public Response deleteProfile(@PathParam("id") int profileId) {
PolicyManagerService policyManagementService = MDMAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
ResponsePayload responseMsg = new ResponsePayload(); ResponsePayload responseMsg = new ResponsePayload();
try { try {
PolicyAdministratorPoint pap = policyManagementService.getPAP(); PolicyAdministratorPoint pap = policyManagementService.getPAP();
org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId); org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId);
pap.deleteProfile(profile); pap.deleteProfile(profile);
Response.status(HttpStatus.SC_OK);
responseMsg.setMessageFromServer("Profile has been deleted successfully."); responseMsg.setMessageFromServer("Profile has been deleted successfully.");
return responseMsg; return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String error = "Policy Management related exception"; String msg = "Policy Management related exception";
log.error(error, e); log.error(msg, e);
throw new MDMAPIException(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
} }

@ -24,23 +24,35 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.mdm.api.common.MDMAPIException; 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.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.RoleWrapper; import org.wso2.carbon.mdm.beans.RoleWrapper;
import org.wso2.carbon.mdm.util.SetReferenceTransformer; 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.core.common.AbstractUserStoreManager;
import org.wso2.carbon.user.mgt.UserRealmProxy; import org.wso2.carbon.user.mgt.UserRealmProxy;
import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import org.wso2.carbon.user.mgt.common.UserAdminException; 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.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@SuppressWarnings("NonJaxWsWebServices")
public class Role { public class Role {
private static Log log = LogFactory.getLog(Role.class); private static Log log = LogFactory.getLog(Role.class);
@ -49,63 +61,49 @@ public class Role {
* Get user roles (except all internal roles) from system. * Get user roles (except all internal roles) from system.
* *
* @return A list of users * @return A list of users
* @throws MDMAPIException
*/ */
@GET @GET
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getRoles() throws MDMAPIException { public Response getRoles() {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); List<String> filteredRoles;
String[] roles;
try { try {
if (log.isDebugEnabled()) { filteredRoles = getRolesFromUserStore();
log.debug("Getting the list of user roles"); } catch (MDMAPIException e) {
} log.error(e.getErrorMessage(), e);
roles = userStoreManager.getRoleNames(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
} 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<String> filteredRoles = new ArrayList<String>();
for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
filteredRoles.add(role);
}
} }
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All user roles were successfully retrieved."); responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
responsePayload.setResponseContent(filteredRoles); 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. * Get user roles by user store(except all internal roles) from system.
* *
* @return A list of users * @return A list of users
* @throws MDMAPIException
*/ */
@GET @GET
@Path ("{userStore}") @Path("{userStore}")
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getRoles(@PathParam ("userStore") String userStore) throws MDMAPIException { public Response getRoles(@PathParam("userStore") String userStore) {
AbstractUserStoreManager abstractUserStoreManager = (AbstractUserStoreManager) MDMAPIUtils.getUserStoreManager();
String[] roles; String[] roles;
try { try {
AbstractUserStoreManager abstractUserStoreManager =
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles"); 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."; String msg = "Error occurred while retrieving the list of user roles.";
log.error(msg, e); 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 // removing all internal roles and roles created for Service-providers
List<String> filteredRoles = new ArrayList<String>(); List<String> filteredRoles = new ArrayList<>();
for (String role : roles) { for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
filteredRoles.add(role); filteredRoles.add(role);
@ -115,34 +113,34 @@ public class Role {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All user roles were successfully retrieved."); responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
responsePayload.setResponseContent(filteredRoles); 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. * Get user roles by providing a filtering criteria(except all internal roles & system roles) from system.
* *
* @return A list of users * @return A list of users
* @throws MDMAPIException
*/ */
@GET @GET
@Path ("search") @Path("search")
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getMatchingRoles(@QueryParam ("filter") String filter) throws MDMAPIException { public Response getMatchingRoles(@QueryParam("filter") String filter) {
AbstractUserStoreManager abstractUserStoreManager = (AbstractUserStoreManager) MDMAPIUtils.getUserStoreManager();
String[] roles; String[] roles;
try { try {
AbstractUserStoreManager abstractUserStoreManager =
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles using filter : " + filter); log.debug("Getting the list of user roles using filter : " + filter);
} }
roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true); 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; String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter;
log.error(msg, e); 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 // removing all internal roles and roles created for Service-providers
List<String> filteredRoles = new ArrayList<String>(); List<String> filteredRoles = new ArrayList<>();
for (String role : roles) { for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
filteredRoles.add(role); filteredRoles.add(role);
@ -152,74 +150,57 @@ public class Role {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All matching user roles were successfully retrieved."); responsePayload.setMessageFromServer("All matching user roles were successfully retrieved.");
responsePayload.setResponseContent(filteredRoles); responsePayload.setResponseContent(filteredRoles);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); return Response.status(Response.Status.OK).entity(responsePayload).build();
} }
/** /**
* Get role permissions. * Get role permissions.
* *
* @return list of permissions * @return list of permissions
* @throws MDMAPIException
*/ */
@GET @GET
@Path ("permissions") @Path("permissions")
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public ResponsePayload getPermissions(@QueryParam ("rolename") String roleName) throws MDMAPIException { public Response getPermissions(@QueryParam("rolename") String roleName) {
final UserRealm userRealm = MDMAPIUtils.getUserRealm(); try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
org.wso2.carbon.user.core.UserRealm userRealmCore = null; org.wso2.carbon.user.core.UserRealm userRealmCore = null;
final UIPermissionNode rolePermissions; final UIPermissionNode rolePermissions;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
} }
try {
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
rolePermissions = userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
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);
} catch (UserAdminException e) {
String msg = "Error occurred while retrieving the user role";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All permissions retrieved"); responsePayload.setMessageFromServer("All permissions retrieved");
responsePayload.setResponseContent(rolePermissions); responsePayload.setResponseContent(rolePermissions);
return responsePayload; 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);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} }
/** /**
* Get user role of the system * Get user role of the system
* *
* @return user role * @return user role
* @throws MDMAPIException
*/ */
@GET @GET
@Path("role") @Path("role")
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public ResponsePayload getRole(@QueryParam ("rolename") String roleName) throws MDMAPIException { public Response getRole(@QueryParam("rolename") String roleName) {
final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); RoleWrapper roleWrapper = new RoleWrapper();
final UserRealm userRealm = MDMAPIUtils.getUserRealm(); try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
org.wso2.carbon.user.core.UserRealm userRealmCore = null; org.wso2.carbon.user.core.UserRealm userRealmCore = null;
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
} }
RoleWrapper roleWrapper = new RoleWrapper();
try {
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of user roles"); log.debug("Getting the list of user roles");
@ -228,6 +209,27 @@ public class Role {
roleWrapper.setRoleName(roleName); roleWrapper.setRoleName(roleName);
roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName)); roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName));
// Get the permission nodes and hand picking only device management and login perms // Get the permission nodes and hand picking only device management and login perms
final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
ArrayList<String> permList = new ArrayList<>();
iteratePermissions(rolePermissions, permList);
roleWrapper.setPermissionList(rolePermissions);
String[] permListAr = new String[permList.size()];
roleWrapper.setPermissions(permList.toArray(permListAr));
}
} catch (UserStoreException | UserAdminException | MDMAPIException e) {
String msg = "Error occurred while retrieving the user role";
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("All user roles were successfully retrieved.");
responsePayload.setResponseContent(roleWrapper);
return Response.status(Response.Status.OK).entity(responsePayload).build();
}
private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy)
throws UserAdminException {
final UIPermissionNode rolePermissions = final UIPermissionNode rolePermissions =
userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2];
@ -244,40 +246,20 @@ public class Role {
} }
} }
rolePermissions.setNodeList(deviceMgtPermissions); rolePermissions.setNodeList(deviceMgtPermissions);
ArrayList<String> permList = new ArrayList<String>(); return rolePermissions;
iteratePermissions(rolePermissions, permList);
roleWrapper.setPermissionList(rolePermissions);
String[] permListAr = new String[permList.size()];
roleWrapper.setPermissions(permList.toArray(permListAr));
}
} catch (UserStoreException 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);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
responsePayload.setResponseContent(roleWrapper);
return responsePayload;
} }
/** /**
* API is used to persist a new Role * API is used to persist a new Role
* *
* @param roleWrapper * @param roleWrapper for role
* @return * @return response
* @throws MDMAPIException
*/ */
@POST @POST
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response addRole(RoleWrapper roleWrapper) throws MDMAPIException { public Response addRole(RoleWrapper roleWrapper) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Persisting the role to user store"); log.debug("Persisting the role to user store");
} }
@ -291,29 +273,27 @@ public class Role {
} }
} }
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = e.getMessage(); String msg = e.getMessage();
log.error(msg, e); 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 * API is used to update a role Role
* *
* @param roleWrapper * @param roleWrapper for role
* @return * @return response
* @throws MDMAPIException
*/ */
@PUT @PUT
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response updateRole(@QueryParam ("rolename") String roleName, RoleWrapper roleWrapper) throws public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) {
MDMAPIException {
final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = MDMAPIUtils.getAuthorizationManager();
String newRoleName = roleWrapper.getRoleName(); String newRoleName = roleWrapper.getRoleName();
try { try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating the role to user store"); log.debug("Updating the role to user store");
} }
@ -321,13 +301,13 @@ public class Role {
userStoreManager.updateRoleName(roleName, newRoleName); userStoreManager.updateRoleName(roleName, newRoleName);
} }
if (roleWrapper.getUsers() != null) { if (roleWrapper.getUsers() != null) {
SetReferenceTransformer transformer = new SetReferenceTransformer(); SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)), transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)),
Arrays.asList(roleWrapper.getUsers())); Arrays.asList(roleWrapper.getUsers()));
final String[] usersToAdd = (String[]) final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); .getObjectsToAdd().size()]);
final String[] usersToDelete = (String[]) final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); .getObjectsToRemove().size()]);
userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd);
} }
if (roleWrapper.getPermissions() != null) { if (roleWrapper.getPermissions() != null) {
@ -340,77 +320,74 @@ public class Role {
} }
} }
} }
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = e.getMessage(); String msg = e.getMessage();
log.error(msg, e); 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 * API is used to delete a role and authorizations
* *
* @param roleName * @param roleName to delete
* @return * @return response
* @throws MDMAPIException
*/ */
@DELETE @DELETE
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response deleteRole(@QueryParam ("rolename") String roleName) throws MDMAPIException { public Response deleteRole(@QueryParam("rolename") String roleName) {
final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = MDMAPIUtils.getAuthorizationManager();
try { try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Deleting the role in user store"); log.debug("Deleting the role in user store");
} }
userStoreManager.deleteRole(roleName); userStoreManager.deleteRole(roleName);
// Delete all authorizations for the current role before deleting // Delete all authorizations for the current role before deleting
authorizationManager.clearRoleAuthorization(roleName); authorizationManager.clearRoleAuthorization(roleName);
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while deleting the role: " + roleName; String msg = "Error occurred while deleting the role: " + roleName;
log.error(msg, e); 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 * API is used to update users of a role
* *
* @param roleName * @param roleName to update
* @param userList * @param userList of the users
* @return * @return response
* @throws MDMAPIException
*/ */
@PUT @PUT
@Path ("users") @Path("users")
@Produces ({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response updateUsers(@QueryParam ("rolename") String roleName, List<String> userList) public Response updateUsers(@QueryParam("rolename") String roleName, List<String> userList) {
throws MDMAPIException {
final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
try { try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating the users of a role"); log.debug("Updating the users of a role");
} }
SetReferenceTransformer transformer = new SetReferenceTransformer(); SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)), transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)),
userList); userList);
final String[] usersToAdd = (String[]) final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); .getObjectsToAdd().size()]);
final String[] usersToDelete = (String[]) final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); .getObjectsToRemove().size()]);
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while saving the users of the role: " + roleName; String msg = "Error occurred while saving the users of the role: " + roleName;
log.error(msg, e); 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<String> iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList<String> list) { private ArrayList<String> iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList<String> list) {
for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) { for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) {
list.add(permissionNode.getResourcePath()); list.add(permissionNode.getResourcePath());
if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) { 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. * This method is used to retrieve the role count of the system.
* *
* @return returns the count. * @return returns the count.
* @throws MDMAPIException
*/ */
@GET @GET
@Path("count") @Path("count")
public int getRoleCount() throws MDMAPIException { public Response getRoleCount() {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); try {
List<String> 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<String> getRolesFromUserStore() throws MDMAPIException {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] roles; String[] roles;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -439,16 +426,15 @@ public class Role {
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of user roles."; String msg = "Error occurred while retrieving the list of user roles.";
log.error(msg, e);
throw new MDMAPIException(msg, e); throw new MDMAPIException(msg, e);
} }
// removing all internal roles and roles created for Service-providers // removing all internal roles and roles created for Service-providers
List<String> filteredRoles = new ArrayList<String>(); List<String> filteredRoles = new ArrayList<>();
for (String role : roles) { for (String role : roles) {
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
filteredRoles.add(role); filteredRoles.add(role);
} }
} }
return filteredRoles.size(); return filteredRoles;
} }
} }

@ -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.device.mgt.core.service.EmailMetaInfo;
import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.CredentialManagementResponseBuilder; 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.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.UserCredentialWrapper; import org.wso2.carbon.mdm.beans.UserCredentialWrapper;
import org.wso2.carbon.mdm.beans.UserWrapper; 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.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException; 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. * This class represents the JAX-RS services of User related functionality.
*/ */
@SuppressWarnings("NonJaxWsWebServices")
public class User { public class User {
private static Log log = LogFactory.getLog(User.class);
private static final String ROLE_EVERYONE = "Internal/everyone"; private static final String ROLE_EVERYONE = "Internal/everyone";
private static Log log = LogFactory.getLog(User.class);
/** /**
* Method to add user to emm-user-store. * Method to add user to emm-user-store.
* *
* @param userWrapper Wrapper object representing input json payload * @param userWrapper Wrapper object representing input json payload
* @return {Response} Status of the request wrapped inside Response object * @return {Response} Status of the request wrapped inside Response object
* @throws MDMAPIException
*/ */
@POST @POST
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response addUser(UserWrapper userWrapper) throws MDMAPIException { public Response addUser(UserWrapper userWrapper) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(userWrapper.getUsername())) { if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
// if user already exists // if user already exists
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -87,7 +95,7 @@ public class User {
responsePayload. responsePayload.
setMessageFromServer("User by username: " + userWrapper.getUsername() + setMessageFromServer("User by username: " + userWrapper.getUsername() +
" already exists. Therefore, request made to add user was refused."); " 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 { } else {
String initialUserPassword = generateInitialUserPassword(); String initialUserPassword = generateInitialUserPassword();
Map<String, String> defaultUserClaims = Map<String, String> defaultUserClaims =
@ -106,12 +114,12 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" was successfully added."); " 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(); String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
log.error(msg, e); 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. * Method to get user information from emm-user-store.
* *
* @param username User-name of the user * @param username User-name of the user
* @return {Response} Status of the request wrapped inside Response object * @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException
*/ */
@GET @GET
@Path("view") @Path("view")
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getUser(@QueryParam("username") String username) throws MDMAPIException { public Response getUser(@QueryParam("username") String username) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) { if (userStoreManager.isExistingUser(username)) {
UserWrapper user = new UserWrapper(); UserWrapper user = new UserWrapper();
user.setUsername(username); user.setUsername(username);
@ -142,7 +149,7 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("User information was retrieved successfully."); responsePayload.setMessageFromServer("User information was retrieved successfully.");
responsePayload.setResponseContent(user); responsePayload.setResponseContent(user);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); return Response.status(Response.Status.OK).entity(responsePayload).build();
} else { } else {
// Outputting debug message upon trying to remove non-existing user // Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -152,12 +159,12 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer( responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist."); "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; String msg = "Exception in trying to retrieve user by username: " + username;
log.error(msg, e); 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 * Update user in user store
* *
* @param userWrapper Wrapper object representing input json payload * @param userWrapper Wrapper object representing input json payload
* @return {Response} Status of the request wrapped inside Response object * @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException
*/ */
@PUT @PUT
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) {
throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(userWrapper.getUsername())) { if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
Map<String, String> defaultUserClaims = Map<String, String> defaultUserClaims =
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
@ -221,7 +226,7 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" was successfully updated."); " was successfully updated.");
return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); return Response.status(Response.Status.CREATED).entity(responsePayload).build();
} else { } else {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() + log.debug("User by username: " + userWrapper.getUsername() +
@ -232,12 +237,12 @@ public class User {
responsePayload. responsePayload.
setMessageFromServer("User by username: " + userWrapper.getUsername() + setMessageFromServer("User by username: " + userWrapper.getUsername() +
" doesn't exists. Therefore, request made to update user was refused."); " 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(); String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
log.error(msg, e); 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. * Method to remove user from emm-user-store.
* *
* @param username Username of the user * @param username Username of the user
* @return {Response} Status of the request wrapped inside Response object * @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException
*/ */
@DELETE @DELETE
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response removeUser(@QueryParam("username") String username) throws MDMAPIException { public Response removeUser(@QueryParam("username") String username) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) { if (userStoreManager.isExistingUser(username)) {
// if user already exists, trying to remove user // if user already exists, trying to remove user
userStoreManager.deleteUser(username); userStoreManager.deleteUser(username);
@ -311,7 +315,7 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer( responsePayload.setMessageFromServer(
"User by username: " + username + " was successfully removed."); "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 { } else {
// Outputting debug message upon trying to remove non-existing user // Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -321,12 +325,12 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer( responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist for removal."); "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; String msg = "Exception in trying to remove user by username: " + username;
log.error(msg, e); 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 userStoreManager User Store Manager associated with the currently logged in user
* @param username Username of the currently logged in user * @param username Username of the currently logged in user
* @return the list of filtered roles * @return the list of filtered roles
* @throws UserStoreException
*/ */
private List<String> getFilteredRoles(UserStoreManager userStoreManager, String username) private List<String> getFilteredRoles(UserStoreManager userStoreManager, String username) {
throws UserStoreException { String[] roleListOfUser = new String[0];
String[] roleListOfUser = userStoreManager.getRoleListOfUser(username); try {
roleListOfUser = userStoreManager.getRoleListOfUser(username);
} catch (UserStoreException e) {
e.printStackTrace();
}
List<String> filteredRoles = new ArrayList<>(); List<String> filteredRoles = new ArrayList<>();
for (String role : roleListOfUser) { for (String role : roleListOfUser) {
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
@ -354,18 +361,17 @@ public class User {
* Get user's roles by username * Get user's roles by username
* *
* @param username Username of the user * @param username Username of the user
* @return {Response} Status of the request wrapped inside Response object * @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException
*/ */
@GET @GET
@Path("roles") @Path("roles")
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getRoles(@QueryParam("username") String username) throws MDMAPIException { public Response getRoles(@QueryParam("username") String username) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (userStoreManager.isExistingUser(username)) { 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 // Outputting debug message upon successful removal of user
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed."); log.debug("User by username: " + username + " was successfully removed.");
@ -374,7 +380,7 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer( responsePayload.setMessageFromServer(
"User roles obtained for user " + username); "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 { } else {
// Outputting debug message upon trying to remove non-existing user // Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -384,12 +390,12 @@ public class User {
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer( responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist for role retrieval."); "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; String msg = "Exception in trying to retrieve roles for user by username: " + username;
log.error(msg, e); 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. * Get the list of all users with all user-related info.
* *
* @return A list of users * @return A list of users
* @throws MDMAPIException
*/ */
@GET @GET
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getAllUsers() throws MDMAPIException { public Response getAllUsers() {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information"); log.debug("Getting the list of users with all user-related information");
} }
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<UserWrapper> userList; List<UserWrapper> userList;
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*", -1); String[] users = userStoreManager.listUsers("*", -1);
userList = new ArrayList<>(users.length); userList = new ArrayList<>(users.length);
UserWrapper user; UserWrapper user;
@ -419,10 +424,10 @@ public class User {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user); userList.add(user);
} }
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users"; String msg = "Error occurred while retrieving the list of users";
log.error(msg, e); 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 responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
@ -431,25 +436,24 @@ public class User {
responsePayload.setMessageFromServer("All users were successfully retrieved. " + responsePayload.setMessageFromServer("All users were successfully retrieved. " +
"Obtained user count: " + count); "Obtained user count: " + count);
responsePayload.setResponseContent(userList); 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. * Get the list of all users with all user-related info.
* *
* @return A list of users * @return A list of users
* @throws MDMAPIException
*/ */
@GET @GET
@Path("{filter}") @Path("{filter}")
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response getMatchingUsers(@PathParam("filter") String filter) throws MDMAPIException { public Response getMatchingUsers(@PathParam("filter") String filter) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information using the filter : " + filter); log.debug("Getting the list of users with all user-related information using the filter : " + filter);
} }
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<UserWrapper> userList; List<UserWrapper> userList;
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers(filter + "*", -1); String[] users = userStoreManager.listUsers(filter + "*", -1);
userList = new ArrayList<>(users.length); userList = new ArrayList<>(users.length);
UserWrapper user; UserWrapper user;
@ -461,10 +465,10 @@ public class User {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user); userList.add(user);
} }
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users using the filter : " + filter; String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
log.error(msg, e); 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 responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
@ -473,24 +477,23 @@ public class User {
responsePayload.setMessageFromServer("All users were successfully retrieved. " + responsePayload.setMessageFromServer("All users were successfully retrieved. " +
"Obtained user count: " + count); "Obtained user count: " + count);
responsePayload.setResponseContent(userList); 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. * Get the list of user names in the system.
* *
* @return A list of user names. * @return A list of user names.
* @throws MDMAPIException
*/ */
@GET @GET
@Path("view-users") @Path("view-users")
public Response getAllUsersByUsername(@QueryParam("username") String userName) throws MDMAPIException { public Response getAllUsersByUsername(@QueryParam("username") String userName) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of users by name"); log.debug("Getting the list of users by name");
} }
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<UserWrapper> userList; List<UserWrapper> userList;
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*" + userName + "*", -1); String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
userList = new ArrayList<>(users.length); userList = new ArrayList<>(users.length);
UserWrapper user; UserWrapper user;
@ -502,10 +505,10 @@ public class User {
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user); userList.add(user);
} }
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users"; String msg = "Error occurred while retrieving the list of users";
log.error(msg, e); 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 responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
@ -514,31 +517,30 @@ public class User {
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
"Obtained user count: " + count); "Obtained user count: " + count);
responsePayload.setResponseContent(userList); 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. * Get the list of user names in the system.
* *
* @return A list of user names. * @return A list of user names.
* @throws MDMAPIException
*/ */
@GET @GET
@Path("users-by-username") @Path("users-by-username")
public Response getAllUserNamesByUsername(@QueryParam("username") String userName) throws MDMAPIException { public Response getAllUserNamesByUsername(@QueryParam("username") String userName) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the list of users by name"); log.debug("Getting the list of users by name");
} }
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<String> userList; List<String> userList;
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
String[] users = userStoreManager.listUsers("*" + userName + "*", -1); String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
userList = new ArrayList<>(users.length); userList = new ArrayList<>(users.length);
Collections.addAll(userList, users); Collections.addAll(userList, users);
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while retrieving the list of users"; String msg = "Error occurred while retrieving the list of users";
log.error(msg, e); 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 responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
@ -547,7 +549,7 @@ public class User {
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
"Obtained user count: " + count); "Obtained user count: " + count);
responsePayload.setResponseContent(userList); 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 username Username of the user
* @param claimUri required ClaimUri * @param claimUri required ClaimUri
* @return A list of usernames * @return claim value
* @throws MDMAPIException, UserStoreException
*/ */
private String getClaimValue(String username, String claimUri) throws MDMAPIException { private String getClaimValue(String username, String claimUri) throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
try { try {
return userStoreManager.getUserClaimValue(username, claimUri, null); return userStoreManager.getUserClaimValue(username, claimUri, null);
} catch (UserStoreException e) { } 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. * Method used to send an invitation email to a new user to enroll a device.
* *
* @param username Username of the user * @param username Username of the user
* @throws MDMAPIException, UserStoreException, DeviceManagementException
*/ */
private void inviteNewlyAddedUserToEnrollDevice( private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException {
String username, String password) throws MDMAPIException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Sending invitation mail to user by username: " + username); log.debug("Sending invitation mail to user by username: " + username);
} }
@ -587,7 +586,7 @@ public class User {
username = "/" + username; username = "/" + username;
} }
String[] usernameBits = username.split("/"); String[] usernameBits = username.split("/");
DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
Properties props = new Properties(); Properties props = new Properties();
props.setProperty("username", usernameBits[1]); 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. * 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 * @param usernames Username list of the users to be invited
* @throws MDMAPIException
*/ */
@POST @POST
@Path("email-invitation") @Path("email-invitation")
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) throws MDMAPIException { public Response inviteExistingUsersToEnrollDevice(List<String> usernames) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Sending enrollment invitation mail to existing user."); log.debug("Sending enrollment invitation mail to existing user.");
} }
DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
try { try {
for (String username : usernames) { for (String username : usernames) {
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
@ -632,15 +630,15 @@ public class User {
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
deviceManagementProviderService.sendEnrolmentInvitation(metaInfo); deviceManagementProviderService.sendEnrolmentInvitation(metaInfo);
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException | MDMAPIException e) {
String msg = "Error occurred while inviting user to enrol their device"; String msg = "Error occurred while inviting user to enrol their device";
log.error(msg, e); 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 responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); 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 * @param username Username of the device owner
* @return A list of devices * @return A list of devices
* @throws MDMAPIException
*/ */
@GET @GET
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
@Path("devices") @Path("devices")
public Object getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx, public Response getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx,
@QueryParam("length") int length) @QueryParam("length") int length) {
throws MDMAPIException {
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
try { try {
dmService = MDMAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
if (length > 0) { if (length > 0) {
PaginationRequest request = new PaginationRequest(startIdx, length); PaginationRequest request = new PaginationRequest(startIdx, length);
request.setOwner(username); 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) { } catch (DeviceManagementException e) {
String msg = "Device management error"; String msg = "Device management error";
log.error(msg, e); 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. * This method is used to retrieve the user count of the system.
* *
* @return returns the count. * @return returns the count.
* @throws MDMAPIException * @
*/ */
@GET @GET
@Path("count") @Path("count")
public int getUserCount() throws MDMAPIException { public Response getUserCount() {
try { try {
String[] users = MDMAPIUtils.getUserStoreManager().listUsers("*", -1); String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1);
if (users == null) { Integer count = 0;
return 0; if (users != null) {
count = users.length;
} }
return users.length; return Response.status(Response.Status.OK).entity(count).build();
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = String msg =
"Error occurred while retrieving the list of users that exist within the current tenant"; "Error occurred while retrieving the list of users that exist within the current tenant";
log.error(msg, e); 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 username
* @param userList * @param userList
* @return * @return
* @throws MDMAPIException * @
*/ */
@PUT @PUT
@Path("{roleName}/users") @Path("{roleName}/users")
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response updateRoles(@PathParam("username") String username, List<String> userList) public Response updateRoles(@PathParam("username") String username, List<String> userList) {
throws MDMAPIException {
final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
try { try {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating the roles of a user"); log.debug("Updating the roles of a user");
} }
SetReferenceTransformer transformer = new SetReferenceTransformer(); SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)), transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)),
userList); userList);
final String[] rolesToAdd = (String[]) final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]);
transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]);
final String[] rolesToDelete = (String[])
transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]);
userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd); userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd);
} catch (UserStoreException e) { } catch (UserStoreException | MDMAPIException e) {
String msg = "Error occurred while saving the roles for user: " + username; String msg = "Error occurred while saving the roles for user: " + username;
log.error(msg, e); 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. * @param credentials Wrapper object representing user credentials.
* @return {Response} Status of the request wrapped inside Response object. * @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException * @
*/ */
@POST @POST
@Path("change-password") @Path("change-password")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response resetPassword(UserCredentialWrapper credentials) throws MDMAPIException { public Response resetPassword(UserCredentialWrapper credentials) {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials); return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials);
} }
@ -750,13 +744,13 @@ public class User {
* *
* @param credentials Wrapper object representing user credentials. * @param credentials Wrapper object representing user credentials.
* @return {Response} Status of the request wrapped inside Response object. * @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException * @
*/ */
@POST @POST
@Path("reset-password") @Path("reset-password")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response resetPasswordByAdmin(UserCredentialWrapper credentials) throws MDMAPIException { public Response resetPasswordByAdmin(UserCredentialWrapper credentials) {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials);
} }

@ -37,19 +37,16 @@ public class CredentialManagementResponseBuilder {
private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class); private static Log log = LogFactory.getLog(CredentialManagementResponseBuilder.class);
private ResponsePayload responsePayload;
/** /**
* Builds the response to change the password of a user * Builds the response to change the password of a user
* @param credentials - User credentials * @param credentials - User credentials
* @return Response Object * @return Response Object
* @throws MDMAPIException
*/ */
public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) throws MDMAPIException { public static Response buildChangePasswordResponse(UserCredentialWrapper credentials) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword()); byte[] decodedOldPassword = Base64.decodeBase64(credentials.getOldPassword());
userStoreManager.updateCredential(credentials.getUsername(), new String( userStoreManager.updateCredential(credentials.getUsername(), new String(
@ -57,48 +54,52 @@ public class CredentialManagementResponseBuilder {
responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() +
" was successfully changed."); " was successfully changed.");
return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); return Response.status(Response.Status.CREATED).entity(responsePayload).build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Old password does not match."); 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) { } catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + String errorMsg = "Could not change the password of the user: " + credentials.getUsername() +
". The Character Encoding is not supported."; ". The Character Encoding is not supported.";
log.error(errorMsg, e); 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 * Builds the response to reset the password of a user
* @param credentials - User credentials * @param credentials - User credentials
* @return Response Object * @return Response Object
* @throws MDMAPIException
*/ */
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) throws MDMAPIException { public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload(); ResponsePayload responsePayload = new ResponsePayload();
try { try {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword());
userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String(
decodedNewPassword, "UTF-8")); decodedNewPassword, "UTF-8"));
responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() +
" was successfully changed."); " was successfully changed.");
return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); return Response.status(Response.Status.CREATED).entity(responsePayload).build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer("Could not change the password."); 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) { } catch (UnsupportedEncodingException e) {
String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + String errorMsg = "Could not change the password of the user: " + credentials.getUsername() +
". The Character Encoding is not supported."; ". The Character Encoding is not supported.";
log.error(errorMsg, e); 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();
} }
} }

@ -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.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; 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.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.mdm.api.common.MDMAPIException; 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.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; 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.AuthorizationManager;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import java.util.List; import java.util.List;
@ -52,12 +50,11 @@ import java.util.List;
/** /**
* MDMAPIUtils class provides utility function used by CDM REST-API classes. * 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; public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE;
private static final String NOTIFIER_FREQUENCY = "notifierFrequency";
private static Log log = LogFactory.getLog(MDMAPIUtils.class); private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class);
public static int getNotifierFrequency(TenantConfiguration tenantConfiguration) { public static int getNotifierFrequency(TenantConfiguration tenantConfiguration) {
List<ConfigurationEntry> configEntryList = tenantConfiguration.getConfiguration(); List<ConfigurationEntry> configEntryList = tenantConfiguration.getConfiguration();
@ -97,6 +94,18 @@ public class MDMAPIUtils {
return deviceManagementProviderService; 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 { public static int getTenantId(String tenantDomain) throws MDMAPIException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);

@ -855,4 +855,167 @@
<scope>emm_admin</scope> <scope>emm_admin</scope>
</Permission> </Permission>
<!-- End of Certificate related APIs --> <!-- End of Certificate related APIs -->
<!-- Group related APIs -->
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups</url>
<method>POST</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*</url>
<method>PUT</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*</url>
<method>DELETE</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/user/*</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/search</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/user/*/all</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/user/*/count</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/share</url>
<method>PUT</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/unshare</url>
<method>PUT</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/share/roles/*/permissions</url>
<method>PUT</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/share/roles/*/permissions</url>
<method>DELETE</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/share/roles</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/users</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/devices/all</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/devices/count</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/devices/*/*</url>
<method>PUT</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/devices/*/*</url>
<method>DELETE</method>
<scope>emm_admin</scope>
</Permission>
<Permission>
<name>Group Management</name>
<path>/device-mgt/admin/groups</path>
<url>/groups/*/*/users/*/permissions</url>
<method>GET</method>
<scope>emm_admin</scope>
</Permission>
<!-- End of Group related APIs -->
</PermissionConfiguration> </PermissionConfiguration>

@ -17,9 +17,9 @@
~ under the License. ~ under the License.
--> -->
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation=" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
@ -51,6 +51,15 @@
<ref bean="errorHandler"/> <ref bean="errorHandler"/>
</jaxrs:providers> </jaxrs:providers>
</jaxrs:server> </jaxrs:server>
<jaxrs:server id="deviceGroupService" address="/groups">
<jaxrs:serviceBeans>
<ref bean="groupServiceBean"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="errorHandler"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="userService" address="/users"> <jaxrs:server id="userService" address="/users">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<ref bean="userServiceBean"/> <ref bean="userServiceBean"/>
@ -155,7 +164,8 @@
</jaxrs:server> </jaxrs:server>
--> -->
<bean id="operationServiceBean" class="org.wso2.carbon.mdm.api.Operation"/> <bean id="operationServiceBean" class="org.wso2.carbon.mdm.api.Operation"/>
<bean id="deviceServiceBean" class="org.wso2.carbon.mdm.api.MobileDevice"/> <bean id="deviceServiceBean" class="org.wso2.carbon.mdm.api.Device"/>
<bean id="groupServiceBean" class="org.wso2.carbon.mdm.api.Group"/>
<bean id="userServiceBean" class="org.wso2.carbon.mdm.api.User"/> <bean id="userServiceBean" class="org.wso2.carbon.mdm.api.User"/>
<bean id="roleServiceBean" class="org.wso2.carbon.mdm.api.Role"/> <bean id="roleServiceBean" class="org.wso2.carbon.mdm.api.Role"/>
<bean id="featureServiceBean" class="org.wso2.carbon.mdm.api.Feature"/> <bean id="featureServiceBean" class="org.wso2.carbon.mdm.api.Feature"/>

Loading…
Cancel
Save