Merge branch 'rest-api-improvements' of https://github.com/wso2/carbon-device-mgt into rest-api-improvements

revert-70aa11f8
hasuniea 9 years ago
commit dfc673b08f

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
@ApiModel(value = "NotificationContext")
public class NotificationContext {
private DeviceIdentifier deviceId;
private Notification notification;
public NotificationContext(DeviceIdentifier deviceId, Notification notification) {
this.deviceId = deviceId;
this.notification = notification;
}
@ApiModelProperty(value = "deviceId")
@JsonProperty("deviceId")
public DeviceIdentifier getDeviceId() {
return deviceId;
}
public void setDeviceId(DeviceIdentifier deviceId) {
this.deviceId = deviceId;
}
@ApiModelProperty(value = "notification")
@JsonProperty("notification")
public Notification getNotification() {
return notification;
}
public void setNotification(Notification notification) {
this.notification = notification;
}
}

@ -0,0 +1,106 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import java.util.ArrayList;
import java.util.List;
@ApiModel(value = "Notifications")
public class NotificationList {
private int count;
private String next;
private String previous;
private List<Notification> notifications = new ArrayList<>();
/**
* Number of notifications returned.
*/
@ApiModelProperty(value = "Number of Devices returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
/**
**/
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices")
public List<Notification> getList() {
return notifications;
}
public void setList(List<Notification> notifications) {
this.notifications = notifications;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(count).append(",\n");
sb.append(" next: ").append(next).append(",\n");
sb.append(" previous: ").append(previous).append(",\n");
sb.append(" notifications: [").append(notifications).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import java.util.ArrayList; import java.util.ArrayList;
@ -29,58 +28,10 @@ import java.util.List;
@ApiModel(value = "List of activities", description = "This contains a set of activities that matches a given " + @ApiModel(value = "List of activities", description = "This contains a set of activities that matches a given " +
"criteria as a collection") "criteria as a collection")
public class ActivityList { public class ActivityList extends BasePaginatedResult {
private int count; private List<Activity> activities;
private String next;
private String previous;
private List<Activity> activities = new ArrayList<>();
/**
* Number of Devices returned.
*/
@ApiModelProperty(value = "Number of activities returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
/**
**/
@ApiModelProperty(value = "List of devices returned") @ApiModelProperty(value = "List of devices returned")
@JsonProperty("activities") @JsonProperty("activities")
public List<Activity> getList() { public List<Activity> getList() {
@ -96,9 +47,9 @@ public class ActivityList {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("{\n"); sb.append("{\n");
sb.append(" count: ").append(count).append(",\n"); sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" next: ").append(next).append(",\n"); sb.append(" next: ").append(getNext()).append(",\n");
sb.append(" previous: ").append(previous).append(",\n"); sb.append(" previous: ").append(getPrevious()).append(",\n");
sb.append(" devices: [").append(activities).append("\n"); sb.append(" devices: [").append(activities).append("\n");
sb.append("]}\n"); sb.append("]}\n");
return sb.toString(); return sb.toString();

@ -0,0 +1,72 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
public class BasePaginatedResult {
private int count;
private String next;
private String previous;
/**
* Number of Devices returned.
*/
@ApiModelProperty(value = "Number of resources returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
}

@ -25,58 +25,10 @@ import org.wso2.carbon.device.mgt.common.Device;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class DeviceList { public class DeviceList extends BasePaginatedResult {
private int count;
private String next;
private String previous;
private List<Device> devices = new ArrayList<>(); private List<Device> devices = new ArrayList<>();
/**
* Number of Devices returned.
*/
@ApiModelProperty(value = "Number of Devices returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
/**
**/
@ApiModelProperty(value = "List of devices returned") @ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices") @JsonProperty("devices")
public List<Device> getList() { public List<Device> getList() {
@ -92,9 +44,9 @@ public class DeviceList {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("{\n"); sb.append("{\n");
sb.append(" count: ").append(count).append(",\n"); sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" next: ").append(next).append(",\n"); sb.append(" next: ").append(getNext()).append(",\n");
sb.append(" previous: ").append(previous).append(",\n"); sb.append(" previous: ").append(getPrevious()).append(",\n");
sb.append(" devices: [").append(devices).append("\n"); sb.append(" devices: [").append(devices).append("\n");
sb.append("]}\n"); sb.append("]}\n");
return sb.toString(); return sb.toString();

@ -26,55 +26,10 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import java.util.List; import java.util.List;
@ApiModel(value = "notificationList") @ApiModel(value = "notificationList")
public class NotificationList { public class NotificationList extends BasePaginatedResult {
private int count;
private String next;
private String previous;
private List<Notification> notifications; private List<Notification> notifications;
/**
* Number of notifications returned.
*/
@ApiModelProperty(value = "Number of notifications returned.")
@JsonProperty("count")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* Link to the next subset of resources qualified. \nEmpty if no more resources are to be returned.
*/
@ApiModelProperty(value = "Link to the next subset of resources qualified. \n " +
"Empty if no more resources are to be returned.")
@JsonProperty("next")
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
/**
* Link to the previous subset of resources qualified. \nEmpty if current subset is the first subset returned.
*/
@ApiModelProperty(value = "Link to the previous subset of resources qualified. \n" +
"Empty if current subset is the first subset returned.")
@JsonProperty("previous")
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
@JsonProperty("notifications") @JsonProperty("notifications")
@ApiModelProperty("notifications") @ApiModelProperty("notifications")
public List<Notification> getNotifications() { public List<Notification> getNotifications() {
@ -90,9 +45,9 @@ public class NotificationList {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("{"); sb.append("{");
sb.append(" count: ").append(count).append(","); sb.append(" count: ").append(getCount()).append(",");
sb.append(" next: ").append(next).append(","); sb.append(" next: ").append(getNext()).append(",");
sb.append(" previous: ").append(previous).append(","); sb.append(" previous: ").append(getPrevious()).append(",");
sb.append(" notifications: [").append(notifications).append(""); sb.append(" notifications: [").append(notifications).append("");
sb.append("]}"); sb.append("]}");
return sb.toString(); return sb.toString();

@ -805,4 +805,5 @@ public interface DeviceManagementService {
required = false) required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince); @HeaderParam("If-Modified-Since") String ifModifiedSince);
} }

@ -22,6 +22,9 @@ import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.jaxrs.NotificationContext;
import org.wso2.carbon.device.mgt.jaxrs.NotificationList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
@ -45,16 +48,13 @@ public interface NotificationManagementService {
value = "Getting all device notification details.", value = "Getting all device notification details.",
notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using " notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using "
+ "this REST API", + "this REST API",
response = Notification.class,
responseContainer = "List",
tags = "Device Notification Management") tags = "Device Notification Management")
@ApiResponses( @ApiResponses(
value = { value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully fetched the list of notifications.", message = "OK. \n Successfully fetched the list of notifications.",
response = Notification.class, response = NotificationList.class,
responseContainer = "List",
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
name = "Content-Type", name = "Content-Type",
@ -76,7 +76,8 @@ public interface NotificationManagementService {
message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the notification list.") message = "Internal Server ErrorResponse. \n Server error occurred while fetching the notification list.",
response = ErrorResponse.class)
}) })
@Permission(scope = "device-notification-view", permissions = { @Permission(scope = "device-notification-view", permissions = {
"/permission/admin/device-mgt/admin/notifications/view", "/permission/admin/device-mgt/admin/notifications/view",
@ -86,7 +87,7 @@ public interface NotificationManagementService {
@ApiParam(name = "status", @ApiParam(name = "status",
value = "Status of the notification.", value = "Status of the notification.",
allowableValues = "NEW, CHECKED", allowableValues = "NEW, CHECKED",
required = true) required = false)
@QueryParam("status") String status, @QueryParam("status") String status,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
@ -105,108 +106,4 @@ public interface NotificationManagementService {
@QueryParam("limit") int limit); @QueryParam("limit") int limit);
@PUT
@Path("/{id}/status")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update the device notification status",
notes = "When a user has read the the device notifications, the device notification status must "
+ "change from NEW to CHECKED. Update the device notification status using this REST API.",
tags = "Device Notification Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Notification status has been updated successfully",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the updated device."),
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be deleted does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while modifying status of the notification.")
})
@Permission(scope = "device-notification-modify",
permissions = {"/permission/admin/device-mgt/admin/notifications/modify"})
Response updateNotificationStatus(
@ApiParam(
name = "id",
value = "Notification identifier.",
required = true)
@PathParam("id") int id,
@ApiParam(
name = "status",
value = "Status of the notification.",
allowableValues = "NEW, CHECKED",
required = true) String status);
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add a device notification.",
notes = "Add a device notification, which will then be sent to a device.",
tags = "Device Notification Management")
@ApiResponses(
value = {
@ApiResponse(code = 201, message = "Created. \n Notification has been added successfully.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The URL of the added notification."),
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests.")
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n " +
"Server error occurred while adding the notification.")
})
@Permission(scope = "device-notification-modify",
permissions = {"/permission/admin/device-mgt/admin/notifications/modify"})
Response addNotification(
@ApiParam(
name = "notification",
value = "Notification details to be added.",
required = true) Notification notification);
} }

@ -20,7 +20,9 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.POST; import javax.ws.rs.POST;
@ -47,14 +49,17 @@ public interface ApplicationManagementAdminService {
httpMethod = "POST", httpMethod = "POST",
value = "Application installation API.(Internal API)", value = "Application installation API.(Internal API)",
notes = "This is an internal API used for application installation on a device.", notes = "This is an internal API used for application installation on a device.",
response = Activity.class,
tags = "Application Management Administrative Service") tags = "Application Management Administrative Service")
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse( @ApiResponse(
code = 200, code = 202,
message = "OK. \n Install application operations have been successfully scheduled upon given devices"), message = "OK. \n Install application operation will be delivered to the given devices",
response = Activity.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error."), message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Resource to be processed does not exist."), message = "Not Found. \n Resource to be processed does not exist."),
@ -65,7 +70,8 @@ public interface ApplicationManagementAdminService {
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n " + message = "Internal Server ErrorResponse. \n " +
"Server error occurred while bulk issuing application installation operations upon " + "Server error occurred while bulk issuing application installation operations upon " +
"a given set of devices.") "a given set of devices.",
response = ErrorResponse.class)
}) })
Response installApplication( Response installApplication(
@ApiParam( @ApiParam(
@ -81,14 +87,17 @@ public interface ApplicationManagementAdminService {
httpMethod = "POST", httpMethod = "POST",
value = "Application un-installation API.(Internal API)", value = "Application un-installation API.(Internal API)",
notes = "This is an internal API used for application un-installation on a device.", notes = "This is an internal API used for application un-installation on a device.",
response = Activity.class,
tags = "Application Management Administrative Service") tags = "Application Management Administrative Service")
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse( @ApiResponse(
code = 200, code = 202,
message = "OK. \n Uninstall application operations have been successfully scheduled upon given devices"), message = "OK. \n Uninstall application operation will be delivered to the provided devices",
response = Activity.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error."), message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Resource to be processed does not exist."), message = "Not Found. \n Resource to be processed does not exist."),
@ -99,7 +108,8 @@ public interface ApplicationManagementAdminService {
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n " + message = "Internal Server ErrorResponse. \n " +
"Server error occurred while bulk issuing application un-installation operations upon " + "Server error occurred while bulk issuing application un-installation operations upon " +
"a given set of devices.") "a given set of devices.",
response = ErrorResponse.class)
}) })
Response uninstallApplication( Response uninstallApplication(
@ApiParam( @ApiParam(

@ -65,6 +65,9 @@ public interface DeviceManagementAdminService {
@ApiResponse( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."),
@ApiResponse(
code = 401,
message = "Unauthorized.\n The requested resource access is unauthorized"),
@ApiResponse( @ApiResponse(
code = 406, code = 406,
message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),

@ -22,8 +22,11 @@ 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.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.jaxrs.NotificationContext;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.*; import javax.ws.rs.*;
@ -56,48 +59,16 @@ public class NotificationManagementServiceImpl implements NotificationManagement
notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications(); notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications();
} }
if (notifications == null || notifications.size() == 0) { if (notifications == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No notification is available to be " + return Response.status(Response.Status.NOT_FOUND).entity("No notification is available to be " +
"retrieved").build(); "retrieved").build();
} }
return Response.status(Response.Status.OK).entity(notifications).build(); return Response.status(Response.Status.OK).entity(notifications).build();
} catch (NotificationManagementException e) { } catch (NotificationManagementException e) {
msg = "ErrorResponse occurred while retrieving notification info"; msg = "Error occurred while retrieving notification info";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
} new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
@PUT
@Path("/{id}/status")
@Override
public Response updateNotificationStatus(@PathParam("id") int id, String status) {
try {
RequestValidationUtil.validateNotificationId(id);
RequestValidationUtil.validateNotificationStatus(status);
DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id,
Notification.Status.valueOf(status));
return Response.status(Response.Status.OK).entity("Notification status has successfully been updated").build();
} catch (NotificationManagementException e) {
String msg = "ErrorResponse occurred while updating notification status";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@POST
@Override
public Response addNotification(Notification notification) {
try {
RequestValidationUtil.validateNotification(notification);
DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification);
return Response.status(Response.Status.OK).entity("Notification has successfully been added").build();
} catch (NotificationManagementException e) {
String msg = "ErrorResponse occurred while updating notification status.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }

@ -24,9 +24,14 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Platform; import org.wso2.carbon.device.mgt.common.Platform;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.exception.UnknownApplicationTypeException; import org.wso2.carbon.device.mgt.jaxrs.exception.UnknownApplicationTypeException;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.ApplicationManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.ApplicationManagementAdminService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.util.MDMAndroidOperationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.MDMAndroidOperationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.MDMIOSOperationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.MDMIOSOperationUtil;
@ -53,30 +58,45 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem
public Response installApplication(ApplicationWrapper applicationWrapper) { public Response installApplication(ApplicationWrapper applicationWrapper) {
ApplicationManager appManagerConnector; ApplicationManager appManagerConnector;
Operation operation = null; Operation operation = null;
Activity activity = null;
RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper);
try { try {
appManagerConnector = DeviceMgtAPIUtils.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()) {
if (deviceIdentifier.getType().equals(Platform.ANDROID.toString())) { if (Platform.ANDROID.toString().equals(deviceIdentifier.getType())) {
operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp); operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.IOS.toString())) { } else if (Platform.IOS.toString().equals(deviceIdentifier.getType())) {
operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp); operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp);
} }
} }
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); if (applicationWrapper.getRoleNameList() != null && applicationWrapper.getRoleNameList().size() > 0) {
activity = appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList());
} else if (applicationWrapper.getUserNameList() != null &&
applicationWrapper.getUserNameList().size() > 0) {
activity = appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList());
} else if (applicationWrapper.getDeviceIdentifiers() != null &&
applicationWrapper.getDeviceIdentifiers().size() > 0) {
activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
} else {
throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"No application installation criteria i.e. user/role/device is given").build());
}
} }
return Response.status(Response.Status.ACCEPTED).entity("Application installation request has been sent " + return Response.status(Response.Status.ACCEPTED).entity(activity).build();
"to the device").build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "ErrorResponse occurred while processing application installation request"; String msg = "ErrorResponse occurred while processing application installation request";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (UnknownApplicationTypeException e) { } catch (UnknownApplicationTypeException e) {
String msg = "The type of application requested to be installed is not supported"; String msg = "The type of application requested to be installed is not supported";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }
@ -86,30 +106,46 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem
public Response uninstallApplication(ApplicationWrapper applicationWrapper) { public Response uninstallApplication(ApplicationWrapper applicationWrapper) {
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;
Activity activity = null;
RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper);
try { try {
appManagerConnector = DeviceMgtAPIUtils.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()) {
if (deviceIdentifier.getType().equals(Platform.ANDROID.toString())) { if (Platform.ANDROID.toString().equals(deviceIdentifier.getType())) {
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);
} }
} }
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); if (applicationWrapper.getRoleNameList() != null && applicationWrapper.getRoleNameList().size() > 0) {
activity = appManagerConnector.installApplicationForUserRoles(operation, applicationWrapper.getRoleNameList());
} else if (applicationWrapper.getUserNameList() != null &&
applicationWrapper.getUserNameList().size() > 0) {
activity = appManagerConnector.installApplicationForUsers(operation, applicationWrapper.getUserNameList());
} else if (applicationWrapper.getDeviceIdentifiers() != null &&
applicationWrapper.getDeviceIdentifiers().size() > 0) {
activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
} else {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"No application un-installation criteria i.e. user/role/device is given").build());
}
} }
return Response.status(Response.Status.ACCEPTED).entity("Application un-installation request has " + return Response.status(Response.Status.ACCEPTED).entity(activity).build();
"been sent to the device").build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "ErrorResponse occurred while processing application un-installation request"; String msg = "ErrorResponse occurred while processing application un-installation request";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (UnknownApplicationTypeException e) { } catch (UnknownApplicationTypeException e) {
String msg = "The type of application requested to be un-installed is not supported"; String msg = "The type of application requested to be un-installed is not supported";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }

@ -20,9 +20,14 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin;
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.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnauthorizedAccessException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.*; import javax.ws.rs.*;
@ -45,18 +50,28 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
@HeaderParam("If-Modified-Since") String ifModifiedSince, @HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset, @QueryParam("offset") int offset,
@QueryParam("limit") int limit) { @QueryParam("limit") int limit) {
List<Device> devices;
try { try {
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name); int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (devices == null || devices.size() == 0) { if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
throw new UnauthorizedAccessException(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(
"Current logged in user is not authorized to perform this operation").build());
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name);
if (devices == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" + return Response.status(Response.Status.NOT_FOUND).entity("No device, which carries the name '" +
name + "', is currently enrolled in the system").build(); name + "', is currently enrolled in the system").build();
} }
return Response.status(Response.Status.OK).entity(devices).build(); return Response.status(Response.Status.OK).entity(devices).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "ErrorResponse occurred while fetching the devices that carry the name '" + name + "'"; String msg = "Error occurred while fetching the devices that carry the name '" + name + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
} }

@ -18,8 +18,8 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import java.util.ArrayList; import java.util.ArrayList;
@ -207,4 +207,42 @@ public class RequestValidationUtil {
} }
} }
public static void validateApplicationInstallationContext(ApplicationWrapper installationCtx) {
int count = 0;
if (installationCtx.getDeviceIdentifiers() != null && installationCtx.getDeviceIdentifiers().size() > 0) {
count++;
}
if (installationCtx.getUserNameList() != null && installationCtx.getUserNameList().size() > 0) {
count++;
}
if (installationCtx.getRoleNameList() != null && installationCtx.getRoleNameList().size() > 0) {
count++;
}
if (count > 1) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("The incoming request has " +
"more than one application installation criteria defined").build());
}
}
public static void validateApplicationUninstallationContext(ApplicationWrapper installationCtx) {
int count = 0;
if (installationCtx.getDeviceIdentifiers() != null && installationCtx.getDeviceIdentifiers().size() > 0) {
count++;
}
if (installationCtx.getUserNameList() != null && installationCtx.getUserNameList().size() > 0) {
count++;
}
if (installationCtx.getRoleNameList() != null && installationCtx.getRoleNameList().size() > 0) {
count++;
}
if (count > 1) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("The incoming request has " +
"more than one application un-installation criteria defined").build());
}
}
} }

@ -0,0 +1,34 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class UnauthorizedAccessException extends WebApplicationException {
private static final long serialVersionUID = 147943579458906890L;
public UnauthorizedAccessException(ErrorResponse error) {
super(Response.status(Response.Status.UNAUTHORIZED).entity(error).build());
}
}

@ -0,0 +1,45 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.common;
public class EntityDoesNotExistException extends RuntimeException {
private static final long serialVersionUID = -3161279331929070297L;
public EntityDoesNotExistException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EntityDoesNotExistException(String message, Throwable cause) {
super(message, cause);
}
public EntityDoesNotExistException(String msg) {
super(msg);
}
public EntityDoesNotExistException() {
super();
}
public EntityDoesNotExistException(Throwable cause) {
super(cause);
}
}

@ -38,14 +38,9 @@ public class Notification {
ALERT ALERT
} }
@JsonProperty(value = "notificationId", required = false) @JsonProperty(value = "id", required = false)
@ApiModelProperty(name = "notificationId", value = "Defines the notification ID.", required = false) @ApiModelProperty(name = "id", value = "Defines the notification ID.", required = false)
private int notificationId; private int id;
@JsonProperty(value = "deviceIdentifier", required = true)
@ApiModelProperty(name = "deviceIdentifier", value = "Defines the device identification properties.",
required = true)
private DeviceIdentifier deviceIdentifier;
@JsonProperty(value = "description", required = false) @JsonProperty(value = "description", required = false)
@ApiModelProperty(name = "description", value = "Provides the message you want to send to the user.", @ApiModelProperty(name = "description", value = "Provides the message you want to send to the user.",
@ -72,19 +67,11 @@ public class Notification {
} }
public int getNotificationId() { public int getNotificationId() {
return notificationId; return id;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
} }
public DeviceIdentifier getDeviceIdentifier() { public void setNotificationId(int id) {
return deviceIdentifier; this.id = id;
}
public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
} }
public String getDescription() { public String getDescription() {
@ -106,12 +93,11 @@ public class Notification {
@Override @Override
public String toString() { public String toString() {
return "notification {" + return "notification {" +
"notificationId='" + notificationId + '\'' + " id='" + id + '\'' +
", deviceId=" + deviceIdentifier.getId() +
", deviceType=" + deviceIdentifier.getType() +
", status=" + status + ", status=" + status +
", description='" + description + '\'' + ", description='" + description + '\'' +
", operationId='" + operationId + '\'' + ", operationId='" + operationId + '\'' +
'}'; '}';
} }
} }

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.common.notification.mgt; package org.wso2.carbon.device.mgt.common.notification.mgt;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List; import java.util.List;
/** /**
@ -25,50 +27,55 @@ import java.util.List;
*/ */
public interface NotificationManagementService { public interface NotificationManagementService {
/** /**
* Method to add a notification to the database. * Method to add a notification to the database.
* *
* @param notification - Notification to be added to database. * @param notification - Notification to be added to database.
* @return boolean status of the operation. * @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while adding the Notification. * @throws NotificationManagementException
*/ * if something goes wrong while adding the Notification.
boolean addNotification(Notification notification) throws NotificationManagementException; */
boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException;
/** /**
* Method to update a notification in the database. * Method to update a notification in the database.
* *
* @param notification - Notification to be updated in the database. * @param notification - Notification to be updated in the database.
* @return boolean status of the operation. * @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while updating the Notification. * @throws NotificationManagementException
* if something goes wrong while updating the Notification.
*/ */
boolean updateNotification(Notification notification) throws NotificationManagementException; boolean updateNotification(Notification notification) throws NotificationManagementException;
/** /**
* Method to update the notification status of a Notification in the database. * Method to update the notification status of a Notification in the database.
* *
* @param notificationId - Notification id of the notification to be updated. * @param notificationId - Notification id of the notification to be updated.
* @param status - New notification status. * @param status - New notification status.
* @return boolean status of the operation. * @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while updating the Notification. * @throws NotificationManagementException
* if something goes wrong while updating the Notification.
*/ */
boolean updateNotificationStatus(int notificationId, Notification.Status status) throws boolean updateNotificationStatus(int notificationId, Notification.Status status) throws
NotificationManagementException; NotificationManagementException;
/** /**
* Method to fetch all the notifications in the database. * Method to fetch all the notifications in the database.
* *
* @return List of all Notifications in the database. * @return List of all Notifications in the database.
* @throws NotificationManagementException * @throws NotificationManagementException
*
*/ */
List<Notification> getAllNotifications() throws NotificationManagementException; List<Notification> getAllNotifications() throws NotificationManagementException;
/** /**
*
* @param status - Status of the notifications to be fetched from database. * @param status - Status of the notifications to be fetched from database.
* @return A list of notifications matching the given status. * @return A list of notifications matching the given status.
* @throws NotificationManagementException if something goes wrong while fetching the Notification. * @throws NotificationManagementException
* if something goes wrong while fetching the Notification.
*/ */
List<Notification> getNotificationsByStatus(Notification.Status status) throws List<Notification> getNotificationsByStatus(Notification.Status status) throws
NotificationManagementException; NotificationManagementException;
} }

@ -21,6 +21,8 @@ package org.wso2.carbon.device.mgt.core.notification.mgt;
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; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EntityDoesNotExistException;
import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
@ -40,133 +42,133 @@ import java.util.List;
*/ */
public class NotificationManagementServiceImpl implements NotificationManagementService { public class NotificationManagementServiceImpl implements NotificationManagementService {
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class); private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
private NotificationDAO notificationDAO; private NotificationDAO notificationDAO;
private DeviceDAO deviceDAO; private DeviceDAO deviceDAO;
public NotificationManagementServiceImpl() { public NotificationManagementServiceImpl() {
this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO(); this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
} }
@Override @Override
public boolean addNotification(Notification notification) throws NotificationManagementException { public boolean addNotification(DeviceIdentifier deviceId,
boolean status = false; Notification notification) throws NotificationManagementException {
int deviceId, tenantId; if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) { log.debug("Adding a Notification : [" + notification.toString() + "]");
log.debug("Adding a Notification : [" + notification.toString() + "]"); }
} int notificationId;
try { int tenantId = NotificationDAOUtil.getTenantId();
tenantId = NotificationDAOUtil.getTenantId();
DeviceManagementDAOFactory.openConnection(); Device device = this.getDevice(deviceId, tenantId);
Device device = deviceDAO.getDevice(notification.getDeviceIdentifier(), tenantId); if (device == null) {
deviceId = device.getId(); throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() +
} catch (SQLException e) { "' and id '" + deviceId.getId() + "'");
throw new NotificationManagementException("Error occurred while opening a connection to" + }
" the data source", e);
} catch (DeviceManagementDAOException e) { try {
throw new NotificationManagementException("Error occurred while retriving device data for " + NotificationManagementDAOFactory.beginTransaction();
" adding notification", e); notificationId = notificationDAO.addNotification(device.getId(), tenantId, notification);
} finally { NotificationManagementDAOFactory.commitTransaction();
DeviceManagementDAOFactory.closeConnection(); } catch (TransactionManagementException e) {
} NotificationManagementDAOFactory.rollbackTransaction();
try { throw new NotificationManagementException("Error occurred while adding notification", e);
NotificationManagementDAOFactory.beginTransaction(); } finally {
int notificationId = notificationDAO.addNotification(deviceId, tenantId, notification); NotificationManagementDAOFactory.closeConnection();
NotificationManagementDAOFactory.commitTransaction(); }
if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) { log.debug("Notification id : " + notificationId + " was added to the table.");
log.debug("Notification id : " + notificationId +" was added to the table."); }
} return true;
if(notificationId > 0) { }
status = true;
} private Device getDevice(DeviceIdentifier deviceId, int tenantId) throws NotificationManagementException {
} catch (TransactionManagementException e) { Device device;
NotificationManagementDAOFactory.rollbackTransaction(); try {
throw new NotificationManagementException("Error occurred while adding notification", e); DeviceManagementDAOFactory.openConnection();
} finally { device = deviceDAO.getDevice(deviceId, tenantId);
NotificationManagementDAOFactory.closeConnection(); } catch (SQLException e) {
} throw new NotificationManagementException("Error occurred while opening a connection to" +
return status; " the data source", e);
} } catch (DeviceManagementDAOException e) {
throw new NotificationManagementException("Error occurred while retriving device data for " +
@Override " adding notification", e);
public boolean updateNotification(Notification notification) throws NotificationManagementException { } finally {
boolean status = false; DeviceManagementDAOFactory.closeConnection();
if (log.isDebugEnabled()) { }
log.debug("Updating Notification : [" + notification.toString() + "]"); return device;
} }
try {
NotificationManagementDAOFactory.beginTransaction(); @Override
if(notificationDAO.updateNotification(notification) > 0 ) { public boolean updateNotification(Notification notification) throws NotificationManagementException {
status = true; if (log.isDebugEnabled()) {
} log.debug("Updating Notification : [" + notification.toString() + "]");
NotificationManagementDAOFactory.commitTransaction(); }
try {
if (log.isDebugEnabled()) { NotificationManagementDAOFactory.beginTransaction();
log.debug("Notification id : " + notification.getNotificationId() + notificationDAO.updateNotification(notification);
" has updated successfully."); NotificationManagementDAOFactory.commitTransaction();
} } catch (TransactionManagementException e) {
} catch (TransactionManagementException e) { NotificationManagementDAOFactory.rollbackTransaction();
NotificationManagementDAOFactory.rollbackTransaction(); throw new NotificationManagementException("Error occurred while updating notification ", e);
throw new NotificationManagementException("Error occurred while updating notification ", e); } finally {
} finally { NotificationManagementDAOFactory.closeConnection();
NotificationManagementDAOFactory.closeConnection(); }
} if (log.isDebugEnabled()) {
return status; log.debug("Notification id : " + notification.getNotificationId() +
} " has updated successfully.");
}
@Override return true;
public boolean updateNotificationStatus(int notificationId, Notification.Status status) }
throws NotificationManagementException {
boolean operationStatus = false; @Override
if (log.isDebugEnabled()) { public boolean updateNotificationStatus(int notificationId, Notification.Status status)
log.debug("Updating Notification id : " + notificationId); throws NotificationManagementException {
} if (log.isDebugEnabled()) {
try { log.debug("Updating Notification id : " + notificationId);
NotificationManagementDAOFactory.beginTransaction(); }
if(notificationDAO.updateNotificationStatus(notificationId, status) > 0 ) { try {
operationStatus = true; NotificationManagementDAOFactory.beginTransaction();
} notificationDAO.updateNotificationStatus(notificationId, status);
NotificationManagementDAOFactory.commitTransaction(); NotificationManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
if (log.isDebugEnabled()) { NotificationManagementDAOFactory.rollbackTransaction();
log.debug("Notification id : " + notificationId +" has updated successfully."); throw new NotificationManagementException("Error occurred while updating notification", e);
} } finally {
} catch (TransactionManagementException e) { NotificationManagementDAOFactory.closeConnection();
NotificationManagementDAOFactory.rollbackTransaction(); }
throw new NotificationManagementException("Error occurred while updating notification", e); if (log.isDebugEnabled()) {
} finally { log.debug("Notification id : " + notificationId + " has updated successfully.");
NotificationManagementDAOFactory.closeConnection(); }
} return true;
return operationStatus; }
}
@Override
@Override public List<Notification> getAllNotifications() throws NotificationManagementException {
public List<Notification> getAllNotifications() throws NotificationManagementException{ try {
try { NotificationManagementDAOFactory.openConnection();
NotificationManagementDAOFactory.openConnection(); return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId());
return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId()); } catch (SQLException e) {
} catch (SQLException e) { throw new NotificationManagementException("Error occurred while opening a connection to" +
throw new NotificationManagementException("Error occurred while opening a connection to" + " the data source", e);
" the data source", e); } finally {
} finally { NotificationManagementDAOFactory.closeConnection();
NotificationManagementDAOFactory.closeConnection(); }
} }
}
@Override
@Override public List<Notification> getNotificationsByStatus(Notification.Status status)
public List<Notification> getNotificationsByStatus(Notification.Status status) throws NotificationManagementException {
throws NotificationManagementException{ try {
try { NotificationManagementDAOFactory.openConnection();
NotificationManagementDAOFactory.openConnection(); return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId());
return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId()); } catch (SQLException e) {
} catch (SQLException e) { throw new NotificationManagementException("Error occurred while opening a connection " +
throw new NotificationManagementException("Error occurred while opening a connection " + "to the data source", e);
"to the data source", e); } finally {
} finally { NotificationManagementDAOFactory.closeConnection();
NotificationManagementDAOFactory.closeConnection(); }
} }
}
} }

@ -18,9 +18,6 @@
package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO;
@ -36,167 +33,157 @@ import java.util.List;
*/ */
public class NotificationDAOImpl implements NotificationDAO { public class NotificationDAOImpl implements NotificationDAO {
private static final Log log = LogFactory.getLog(NotificationDAOImpl.class); @Override
public int addNotification(int deviceId, int tenantId,
Notification notification) throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs;
int notificationId = -1;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql =
"INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setInt(2, notification.getOperationId());
stmt.setString(3, notification.getStatus().toString());
stmt.setString(4, notification.getDescription());
stmt.setInt(5, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
notificationId = rs.getInt(1);
}
} catch (Exception e) {
throw new NotificationManagementException("Error occurred while adding the " +
"Notification for device id : " + deviceId,
e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, null);
}
return notificationId;
}
@Override @Override
public int addNotification(int deviceId, int tenantId, Notification notification) throws public int updateNotification(Notification notification)
NotificationManagementException { throws NotificationManagementException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs; int rows;
int notificationId = -1; try {
try { conn = NotificationManagementDAOFactory.getConnection();
conn = NotificationManagementDAOFactory.getConnection(); String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " +
String sql = "WHERE NOTIFICATION_ID = ?";
"INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) " + stmt = conn.prepareStatement(sql);
"VALUES (?, ?, ?, ?, ?)"; stmt.setInt(1, notification.getOperationId());
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(2, notification.getStatus().toString());
stmt.setInt(1, deviceId); stmt.setString(3, notification.getDescription());
stmt.setInt(2, notification.getOperationId()); stmt.setInt(4, notification.getNotificationId());
stmt.setString(3, notification.getStatus().toString()); rows = stmt.executeUpdate();
stmt.setString(4, notification.getDescription()); } catch (Exception e) {
stmt.setInt(5, tenantId); throw new NotificationManagementException("Error occurred while updating the " +
stmt.execute(); "Notification id : " + notification.getNotificationId(), e);
rs = stmt.getGeneratedKeys(); } finally {
if (rs.next()) { NotificationDAOUtil.cleanupResources(stmt, null);
notificationId = rs.getInt(1); }
} return rows;
} catch (Exception e) { }
throw new NotificationManagementException("Error occurred while adding the " +
"Notification for device id : " + deviceId,
e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, null);
}
return notificationId;
}
@Override @Override
public int updateNotification(Notification notification) public int updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException { throws NotificationManagementException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
int rows; int rows;
try { try {
conn = NotificationManagementDAOFactory.getConnection(); conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " + String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?";
"WHERE NOTIFICATION_ID = ?"; stmt = conn.prepareStatement(sql);
stmt = conn.prepareStatement(sql); stmt.setString(1, status.toString());
stmt.setInt(1, notification.getOperationId()); stmt.setInt(2, notificationId);
stmt.setString(2, notification.getStatus().toString()); rows = stmt.executeUpdate();
stmt.setString(3, notification.getDescription()); } catch (Exception e) {
stmt.setInt(4, notification.getNotificationId()); throw new NotificationManagementException("Error occurred while updating the status of " +
rows = stmt.executeUpdate(); "Notification id : " + notificationId, e);
} catch (Exception e) { } finally {
throw new NotificationManagementException("Error occurred while updating the " + NotificationDAOUtil.cleanupResources(stmt, null);
"Notification id : " + notification.getNotificationId(), e); }
} finally { return rows;
NotificationDAOUtil.cleanupResources(stmt, null); }
}
return rows;
}
@Override @Override
public int updateNotificationStatus(int notificationId, Notification.Status status) public List<Notification> getAllNotifications(int tenantId) throws NotificationManagementException {
throws NotificationManagementException { Connection conn;
Connection conn; PreparedStatement stmt = null;
PreparedStatement stmt = null; ResultSet rs = null;
int rows; List<Notification> notifications = null;
try { try {
conn = NotificationManagementDAOFactory.getConnection(); conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?"; String sql =
stmt = conn.prepareStatement(sql); "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," +
stmt.setString(1, status.toString()); " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " +
stmt.setInt(2, notificationId); "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " +
rows = stmt.executeUpdate(); "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?";
} catch (Exception e) { stmt = conn.prepareStatement(sql);
throw new NotificationManagementException("Error occurred while updating the status of " + stmt.setInt(1, tenantId);
"Notification id : " + notificationId, e); stmt.setInt(2, tenantId);
} finally { rs = stmt.executeQuery();
NotificationDAOUtil.cleanupResources(stmt, null); notifications = new ArrayList<>();
} while (rs.next()) {
return rows; notifications.add(this.getNotification(rs));
} }
} catch (SQLException e) {
throw new NotificationManagementException(
"Error occurred while retrieving information of all notifications", e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
@Override @Override
public List<Notification> getAllNotifications(int tenantId) public List<Notification> getNotificationsByStatus(Notification.Status status,
throws NotificationManagementException { int tenantId) throws NotificationManagementException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
List<Notification> notifications = null; List<Notification> notifications = null;
try { try {
conn = NotificationManagementDAOFactory.getConnection(); conn = NotificationManagementDAOFactory.getConnection();
String sql = String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," +
"SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " +
" d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " +
"NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " +
"TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " +
stmt = conn.prepareStatement(sql); "AND TENANT_ID = ?";
stmt.setInt(1, tenantId); stmt = conn.prepareStatement(sql);
stmt.setInt(2, tenantId); stmt.setInt(1, tenantId);
rs = stmt.executeQuery(); stmt.setString(2, status.toString());
notifications = new ArrayList<>(); stmt.setInt(3, tenantId);
while (rs.next()) { rs = stmt.executeQuery();
notifications.add(this.getNotification(rs)); notifications = new ArrayList<>();
} while (rs.next()) {
} catch (SQLException e) { notifications.add(this.getNotification(rs));
throw new NotificationManagementException( }
"Error occurred while retrieving information of all notifications", e); } catch (SQLException e) {
} finally { throw new NotificationManagementException(
NotificationDAOUtil.cleanupResources(stmt, rs); "Error occurred while retrieving information of all " +
} "notifications by status : " + status, e);
return notifications; } finally {
} NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
@Override private Notification getNotification(ResultSet rs) throws SQLException {
public List<Notification> getNotificationsByStatus(Notification.Status status, int tenantId) Notification notification = new Notification();
throws NotificationManagementException { notification.setNotificationId(rs.getInt("NOTIFICATION_ID"));
Connection conn; notification.setOperationId(rs.getInt("OPERATION_ID"));
PreparedStatement stmt = null; notification.setDescription(rs.getString("DESCRIPTION"));
ResultSet rs = null; notification.setStatus(rs.getString("STATUS"));
List<Notification> notifications = null; return notification;
try { }
conn = NotificationManagementDAOFactory.getConnection();
String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," +
" n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " +
"DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " +
"OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " +
"TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " +
"AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, status.toString());
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
notifications = new ArrayList<>();
while (rs.next()) {
notifications.add(this.getNotification(rs));
}
} catch (SQLException e) {
throw new NotificationManagementException(
"Error occurred while retrieving information of all " +
"notifications by status : " + status, e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
private Notification getNotification(ResultSet rs) throws SQLException {
Notification notification = new Notification();
notification.setNotificationId(rs.getInt("NOTIFICATION_ID"));
notification.setDeviceIdentifier(this.getDeviceIdentifier(rs));
notification.setOperationId(rs.getInt("OPERATION_ID"));
notification.setDescription(rs.getString("DESCRIPTION"));
notification.setStatus(rs.getString("STATUS"));
return notification;
}
private DeviceIdentifier getDeviceIdentifier(ResultSet rs) throws SQLException {
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(rs.getString("DEVICE_IDENTIFICATION"));
identifier.setType(rs.getString("DEVICE_TYPE"));
return identifier;
}
} }
Loading…
Cancel
Save