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;
/** /**
@ -30,16 +32,19 @@ public interface NotificationManagementService {
* *
* @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;
@ -49,7 +54,8 @@ public interface NotificationManagementService {
* @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;
@ -59,14 +65,15 @@ public interface NotificationManagementService {
* *
* @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;
@ -51,17 +53,41 @@ public class NotificationManagementServiceImpl implements NotificationManagement
} }
@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;
int tenantId = NotificationDAOUtil.getTenantId();
Device device = this.getDevice(deviceId, tenantId);
if (device == null) {
throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() +
"' and id '" + deviceId.getId() + "'");
}
try {
NotificationManagementDAOFactory.beginTransaction();
notificationId = notificationDAO.addNotification(device.getId(), tenantId, notification);
NotificationManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while adding notification", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId + " was added to the table.");
}
return true;
}
private Device getDevice(DeviceIdentifier deviceId, int tenantId) throws NotificationManagementException {
Device device;
try { try {
tenantId = NotificationDAOUtil.getTenantId();
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
Device device = deviceDAO.getDevice(notification.getDeviceIdentifier(), tenantId); device = deviceDAO.getDevice(deviceId, tenantId);
deviceId = device.getId();
} 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);
@ -71,80 +97,55 @@ public class NotificationManagementServiceImpl implements NotificationManagement
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
try { return device;
NotificationManagementDAOFactory.beginTransaction();
int notificationId = notificationDAO.addNotification(deviceId, tenantId, notification);
NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId +" was added to the table.");
}
if(notificationId > 0) {
status = true;
}
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while adding notification", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return status;
} }
@Override @Override
public boolean updateNotification(Notification notification) throws NotificationManagementException { public boolean updateNotification(Notification notification) throws NotificationManagementException {
boolean status = false;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating Notification : [" + notification.toString() + "]"); log.debug("Updating Notification : [" + notification.toString() + "]");
} }
try { try {
NotificationManagementDAOFactory.beginTransaction(); NotificationManagementDAOFactory.beginTransaction();
if(notificationDAO.updateNotification(notification) > 0 ) { notificationDAO.updateNotification(notification);
status = true;
}
NotificationManagementDAOFactory.commitTransaction(); NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notification.getNotificationId() +
" has updated successfully.");
}
} 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();
} }
return status; if (log.isDebugEnabled()) {
log.debug("Notification id : " + notification.getNotificationId() +
" has updated successfully.");
}
return true;
} }
@Override @Override
public boolean updateNotificationStatus(int notificationId, Notification.Status status) public boolean updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException { throws NotificationManagementException {
boolean operationStatus = false;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating Notification id : " + notificationId); log.debug("Updating Notification id : " + notificationId);
} }
try { try {
NotificationManagementDAOFactory.beginTransaction(); NotificationManagementDAOFactory.beginTransaction();
if(notificationDAO.updateNotificationStatus(notificationId, status) > 0 ) { notificationDAO.updateNotificationStatus(notificationId, status);
operationStatus = true;
}
NotificationManagementDAOFactory.commitTransaction(); NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId +" has updated successfully.");
}
} 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();
} }
return operationStatus; if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId + " has updated successfully.");
}
return true;
} }
@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());
@ -158,7 +159,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement
@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());
@ -169,4 +170,5 @@ public class NotificationManagementServiceImpl implements NotificationManagement
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,11 +33,9 @@ import java.util.List;
*/ */
public class NotificationDAOImpl implements NotificationDAO { public class NotificationDAOImpl implements NotificationDAO {
private static final Log log = LogFactory.getLog(NotificationDAOImpl.class);
@Override @Override
public int addNotification(int deviceId, int tenantId, Notification notification) throws public int addNotification(int deviceId, int tenantId,
NotificationManagementException { Notification notification) throws NotificationManagementException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs; ResultSet rs;
@ -119,8 +114,7 @@ public class NotificationDAOImpl implements NotificationDAO {
} }
@Override @Override
public List<Notification> getAllNotifications(int tenantId) public List<Notification> getAllNotifications(int tenantId) throws NotificationManagementException {
throws NotificationManagementException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -150,8 +144,8 @@ public class NotificationDAOImpl implements NotificationDAO {
} }
@Override @Override
public List<Notification> getNotificationsByStatus(Notification.Status status, 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;
@ -186,17 +180,10 @@ public class NotificationDAOImpl implements NotificationDAO {
private Notification getNotification(ResultSet rs) throws SQLException { private Notification getNotification(ResultSet rs) throws SQLException {
Notification notification = new Notification(); Notification notification = new Notification();
notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); notification.setNotificationId(rs.getInt("NOTIFICATION_ID"));
notification.setDeviceIdentifier(this.getDeviceIdentifier(rs));
notification.setOperationId(rs.getInt("OPERATION_ID")); notification.setOperationId(rs.getInt("OPERATION_ID"));
notification.setDescription(rs.getString("DESCRIPTION")); notification.setDescription(rs.getString("DESCRIPTION"));
notification.setStatus(rs.getString("STATUS")); notification.setStatus(rs.getString("STATUS"));
return notification; 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