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 io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
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 " +
"criteria as a collection")
public class ActivityList {
public class ActivityList extends BasePaginatedResult {
private int count;
private String next;
private String previous;
private List<Activity> activities;
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")
@JsonProperty("activities")
public List<Activity> getList() {
@ -96,9 +47,9 @@ public class ActivityList {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(count).append(",\n");
sb.append(" next: ").append(next).append(",\n");
sb.append(" previous: ").append(previous).append(",\n");
sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" next: ").append(getNext()).append(",\n");
sb.append(" previous: ").append(getPrevious()).append(",\n");
sb.append(" devices: [").append(activities).append("\n");
sb.append("]}\n");
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.List;
public class DeviceList {
private int count;
private String next;
private String previous;
public class DeviceList extends BasePaginatedResult {
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")
@JsonProperty("devices")
public List<Device> getList() {
@ -92,9 +44,9 @@ public class DeviceList {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(count).append(",\n");
sb.append(" next: ").append(next).append(",\n");
sb.append(" previous: ").append(previous).append(",\n");
sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" next: ").append(getNext()).append(",\n");
sb.append(" previous: ").append(getPrevious()).append(",\n");
sb.append(" devices: [").append(devices).append("\n");
sb.append("]}\n");
return sb.toString();

@ -26,55 +26,10 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import java.util.List;
@ApiModel(value = "notificationList")
public class NotificationList {
public class NotificationList extends BasePaginatedResult {
private int count;
private String next;
private String previous;
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")
@ApiModelProperty("notifications")
public List<Notification> getNotifications() {
@ -90,9 +45,9 @@ public class NotificationList {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append(" count: ").append(count).append(",");
sb.append(" next: ").append(next).append(",");
sb.append(" previous: ").append(previous).append(",");
sb.append(" count: ").append(getCount()).append(",");
sb.append(" next: ").append(getNext()).append(",");
sb.append(" previous: ").append(getPrevious()).append(",");
sb.append(" notifications: [").append(notifications).append("");
sb.append("]}");
return sb.toString();

@ -805,4 +805,5 @@ public interface DeviceManagementService {
required = false)
@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.Permission;
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.core.MediaType;
@ -45,16 +48,13 @@ public interface NotificationManagementService {
value = "Getting all device notification details.",
notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using "
+ "this REST API",
response = Notification.class,
responseContainer = "List",
tags = "Device Notification Management")
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of notifications.",
response = Notification.class,
responseContainer = "List",
response = NotificationList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
@ -76,7 +76,8 @@ public interface NotificationManagementService {
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching the 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/admin/device-mgt/admin/notifications/view",
@ -86,7 +87,7 @@ public interface NotificationManagementService {
@ApiParam(name = "status",
value = "Status of the notification.",
allowableValues = "NEW, CHECKED",
required = true)
required = false)
@QueryParam("status") String status,
@ApiParam(
name = "If-Modified-Since",
@ -105,108 +106,4 @@ public interface NotificationManagementService {
@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 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.ErrorResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
@ -47,14 +49,17 @@ public interface ApplicationManagementAdminService {
httpMethod = "POST",
value = "Application installation API.(Internal API)",
notes = "This is an internal API used for application installation on a device.",
response = Activity.class,
tags = "Application Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Install application operations have been successfully scheduled upon given devices"),
code = 202,
message = "OK. \n Install application operation will be delivered to the given devices",
response = Activity.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be processed does not exist."),
@ -65,7 +70,8 @@ public interface ApplicationManagementAdminService {
code = 500,
message = "Internal Server ErrorResponse. \n " +
"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(
@ApiParam(
@ -81,14 +87,17 @@ public interface ApplicationManagementAdminService {
httpMethod = "POST",
value = "Application un-installation API.(Internal API)",
notes = "This is an internal API used for application un-installation on a device.",
response = Activity.class,
tags = "Application Management Administrative Service")
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Uninstall application operations have been successfully scheduled upon given devices"),
code = 202,
message = "OK. \n Uninstall application operation will be delivered to the provided devices",
response = Activity.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Resource to be processed does not exist."),
@ -99,7 +108,8 @@ public interface ApplicationManagementAdminService {
code = 500,
message = "Internal Server ErrorResponse. \n " +
"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(
@ApiParam(

@ -65,6 +65,9 @@ public interface DeviceManagementAdminService {
@ApiResponse(
code = 304,
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(
code = 406,
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.wso2.carbon.device.mgt.common.notification.mgt.Notification;
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.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.*;
@ -56,48 +59,16 @@ public class NotificationManagementServiceImpl implements NotificationManagement
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 " +
"retrieved").build();
}
return Response.status(Response.Status.OK).entity(notifications).build();
} catch (NotificationManagementException e) {
msg = "ErrorResponse occurred while retrieving notification info";
msg = "Error occurred while retrieving notification info";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(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();
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(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.app.mgt.ApplicationManagementException;
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.jaxrs.beans.ErrorResponse;
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.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.MDMAndroidOperationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.MDMIOSOperationUtil;
@ -53,30 +58,45 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem
public Response installApplication(ApplicationWrapper applicationWrapper) {
ApplicationManager appManagerConnector;
Operation operation = null;
Activity activity = null;
RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper);
try {
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
MobileApp mobileApp = applicationWrapper.getApplication();
if (applicationWrapper.getDeviceIdentifiers() != null) {
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
if (deviceIdentifier.getType().equals(Platform.ANDROID.toString())) {
if (Platform.ANDROID.toString().equals(deviceIdentifier.getType())) {
operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.IOS.toString())) {
} else if (Platform.IOS.toString().equals(deviceIdentifier.getType())) {
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 " +
"to the device").build();
return Response.status(Response.Status.ACCEPTED).entity(activity).build();
} catch (ApplicationManagementException e) {
String msg = "ErrorResponse occurred while processing application installation request";
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) {
String msg = "The type of application requested to be installed is not supported";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}
@ -86,30 +106,46 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem
public Response uninstallApplication(ApplicationWrapper applicationWrapper) {
ApplicationManager appManagerConnector;
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
Activity activity = null;
RequestValidationUtil.validateApplicationInstallationContext(applicationWrapper);
try {
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
MobileApp mobileApp = applicationWrapper.getApplication();
if (applicationWrapper.getDeviceIdentifiers() != null) {
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
if (deviceIdentifier.getType().equals(Platform.ANDROID.toString())) {
if (Platform.ANDROID.toString().equals(deviceIdentifier.getType())) {
operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp);
} else if (deviceIdentifier.getType().equals(Platform.IOS.toString())) {
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 " +
"been sent to the device").build();
return Response.status(Response.Status.ACCEPTED).entity(activity).build();
} catch (ApplicationManagementException e) {
String msg = "ErrorResponse occurred while processing application un-installation request";
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) {
String msg = "The type of application requested to be un-installed is not supported";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
}
}

@ -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.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.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.impl.util.UnauthorizedAccessException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.*;
@ -45,18 +50,28 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
List<Device> devices;
try {
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(name);
if (devices == null || devices.size() == 0) {
int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
throw new UnauthorizedAccessException(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(
"Current logged in user is not authorized to perform this operation").build());
}
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 '" +
name + "', is currently enrolled in the system").build();
}
return Response.status(Response.Status.OK).entity(devices).build();
} 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);
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;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
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 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
}
@JsonProperty(value = "notificationId", required = false)
@ApiModelProperty(name = "notificationId", value = "Defines the notification ID.", required = false)
private int notificationId;
@JsonProperty(value = "deviceIdentifier", required = true)
@ApiModelProperty(name = "deviceIdentifier", value = "Defines the device identification properties.",
required = true)
private DeviceIdentifier deviceIdentifier;
@JsonProperty(value = "id", required = false)
@ApiModelProperty(name = "id", value = "Defines the notification ID.", required = false)
private int id;
@JsonProperty(value = "description", required = false)
@ApiModelProperty(name = "description", value = "Provides the message you want to send to the user.",
@ -72,19 +67,11 @@ public class Notification {
}
public int getNotificationId() {
return notificationId;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
return id;
}
public DeviceIdentifier getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
public void setNotificationId(int id) {
this.id = id;
}
public String getDescription() {
@ -106,12 +93,11 @@ public class Notification {
@Override
public String toString() {
return "notification {" +
"notificationId='" + notificationId + '\'' +
", deviceId=" + deviceIdentifier.getId() +
", deviceType=" + deviceIdentifier.getType() +
" id='" + id + '\'' +
", status=" + status +
", description='" + description + '\'' +
", operationId='" + operationId + '\'' +
'}';
}
}

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.common.notification.mgt;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List;
/**
@ -25,50 +27,55 @@ import java.util.List;
*/
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.
* @return boolean status of the operation.
* @throws NotificationManagementException if something goes wrong while adding the Notification.
*/
boolean addNotification(Notification notification) throws NotificationManagementException;
* @param notification - Notification to be added to database.
* @return boolean status of the operation.
* @throws NotificationManagementException
* if something goes wrong while adding the Notification.
*/
boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException;
/**
* Method to update a notification in the database.
*
* @param notification - Notification to be updated in the database.
* @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.
*
* @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.
* @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
NotificationManagementException;
boolean updateNotificationStatus(int notificationId, Notification.Status status) throws
NotificationManagementException;
/**
* Method to fetch all the notifications in the database.
*
* @return List of all Notifications in the database.
* @throws NotificationManagementException
*
*/
List<Notification> getAllNotifications() throws NotificationManagementException;
List<Notification> getAllNotifications() throws NotificationManagementException;
/**
*
* @param status - Status of the notifications to be fetched from database.
* @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
NotificationManagementException;
List<Notification> getNotificationsByStatus(Notification.Status status) throws
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.LogFactory;
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.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
@ -40,133 +42,133 @@ import java.util.List;
*/
public class NotificationManagementServiceImpl implements NotificationManagementService {
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
private NotificationDAO notificationDAO;
private DeviceDAO deviceDAO;
public NotificationManagementServiceImpl() {
this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
}
@Override
public boolean addNotification(Notification notification) throws NotificationManagementException {
boolean status = false;
int deviceId, tenantId;
if (log.isDebugEnabled()) {
log.debug("Adding a Notification : [" + notification.toString() + "]");
}
try {
tenantId = NotificationDAOUtil.getTenantId();
DeviceManagementDAOFactory.openConnection();
Device device = deviceDAO.getDevice(notification.getDeviceIdentifier(), tenantId);
deviceId = device.getId();
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection to" +
" the data source", e);
} catch (DeviceManagementDAOException e) {
throw new NotificationManagementException("Error occurred while retriving device data for " +
" adding notification", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
try {
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
public boolean updateNotification(Notification notification) throws NotificationManagementException {
boolean status = false;
if (log.isDebugEnabled()) {
log.debug("Updating Notification : [" + notification.toString() + "]");
}
try {
NotificationManagementDAOFactory.beginTransaction();
if(notificationDAO.updateNotification(notification) > 0 ) {
status = true;
}
NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notification.getNotificationId() +
" has updated successfully.");
}
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating notification ", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return status;
}
@Override
public boolean updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException {
boolean operationStatus = false;
if (log.isDebugEnabled()) {
log.debug("Updating Notification id : " + notificationId);
}
try {
NotificationManagementDAOFactory.beginTransaction();
if(notificationDAO.updateNotificationStatus(notificationId, status) > 0 ) {
operationStatus = true;
}
NotificationManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId +" has updated successfully.");
}
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating notification", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
return operationStatus;
}
@Override
public List<Notification> getAllNotifications() throws NotificationManagementException{
try {
NotificationManagementDAOFactory.openConnection();
return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId());
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection to" +
" the data source", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
}
@Override
public List<Notification> getNotificationsByStatus(Notification.Status status)
throws NotificationManagementException{
try {
NotificationManagementDAOFactory.openConnection();
return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId());
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection " +
"to the data source", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
}
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
private NotificationDAO notificationDAO;
private DeviceDAO deviceDAO;
public NotificationManagementServiceImpl() {
this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
}
@Override
public boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) {
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 {
DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceId, tenantId);
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection to" +
" the data source", e);
} catch (DeviceManagementDAOException e) {
throw new NotificationManagementException("Error occurred while retriving device data for " +
" adding notification", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return device;
}
@Override
public boolean updateNotification(Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) {
log.debug("Updating Notification : [" + notification.toString() + "]");
}
try {
NotificationManagementDAOFactory.beginTransaction();
notificationDAO.updateNotification(notification);
NotificationManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating notification ", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notification.getNotificationId() +
" has updated successfully.");
}
return true;
}
@Override
public boolean updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException {
if (log.isDebugEnabled()) {
log.debug("Updating Notification id : " + notificationId);
}
try {
NotificationManagementDAOFactory.beginTransaction();
notificationDAO.updateNotificationStatus(notificationId, status);
NotificationManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
NotificationManagementDAOFactory.rollbackTransaction();
throw new NotificationManagementException("Error occurred while updating notification", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
if (log.isDebugEnabled()) {
log.debug("Notification id : " + notificationId + " has updated successfully.");
}
return true;
}
@Override
public List<Notification> getAllNotifications() throws NotificationManagementException {
try {
NotificationManagementDAOFactory.openConnection();
return notificationDAO.getAllNotifications(NotificationDAOUtil.getTenantId());
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection to" +
" the data source", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
}
@Override
public List<Notification> getNotificationsByStatus(Notification.Status status)
throws NotificationManagementException {
try {
NotificationManagementDAOFactory.openConnection();
return notificationDAO.getNotificationsByStatus(status, NotificationDAOUtil.getTenantId());
} catch (SQLException e) {
throw new NotificationManagementException("Error occurred while opening a connection " +
"to the data source", e);
} finally {
NotificationManagementDAOFactory.closeConnection();
}
}
}

@ -18,9 +18,6 @@
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.NotificationManagementException;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO;
@ -36,167 +33,157 @@ import java.util.List;
*/
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
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
public int updateNotification(Notification notification)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
int rows;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " +
"WHERE NOTIFICATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, notification.getOperationId());
stmt.setString(2, notification.getStatus().toString());
stmt.setString(3, notification.getDescription());
stmt.setInt(4, notification.getNotificationId());
rows = stmt.executeUpdate();
} catch (Exception e) {
throw new NotificationManagementException("Error occurred while updating the " +
"Notification id : " + notification.getNotificationId(), e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, null);
}
return rows;
}
@Override
public int updateNotification(Notification notification)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
int rows;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET OPERATION_ID = ?, STATUS = ?, DESCRIPTION = ? " +
"WHERE NOTIFICATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, notification.getOperationId());
stmt.setString(2, notification.getStatus().toString());
stmt.setString(3, notification.getDescription());
stmt.setInt(4, notification.getNotificationId());
rows = stmt.executeUpdate();
} catch (Exception e) {
throw new NotificationManagementException("Error occurred while updating the " +
"Notification id : " + notification.getNotificationId(), e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, null);
}
return rows;
}
@Override
public int updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
int rows;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setInt(2, notificationId);
rows = stmt.executeUpdate();
} catch (Exception e) {
throw new NotificationManagementException("Error occurred while updating the status of " +
"Notification id : " + notificationId, e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, null);
}
return rows;
}
@Override
public int updateNotificationStatus(int notificationId, Notification.Status status)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
int rows;
try {
conn = NotificationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_NOTIFICATION SET STATUS = ? WHERE NOTIFICATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setInt(2, notificationId);
rows = stmt.executeUpdate();
} catch (Exception e) {
throw new NotificationManagementException("Error occurred while updating the status of " +
"Notification id : " + notificationId, e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, null);
}
return rows;
}
@Override
public List<Notification> getAllNotifications(int tenantId) throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Notification> notifications = null;
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 = ?) 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.setInt(2, 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", e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
@Override
public List<Notification> getAllNotifications(int tenantId)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Notification> notifications = null;
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 = ?) 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.setInt(2, 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", e);
} finally {
NotificationDAOUtil.cleanupResources(stmt, rs);
}
return notifications;
}
@Override
public List<Notification> getNotificationsByStatus(Notification.Status status,
int tenantId) throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Notification> notifications = null;
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;
}
@Override
public List<Notification> getNotificationsByStatus(Notification.Status status, int tenantId)
throws NotificationManagementException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Notification> notifications = null;
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.setOperationId(rs.getInt("OPERATION_ID"));
notification.setDescription(rs.getString("DESCRIPTION"));
notification.setStatus(rs.getString("STATUS"));
return notification;
}
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