Improving jax-rs APIS of CDM-F

revert-70aa11f8
prabathabey 9 years ago
parent 13db7c906f
commit fd7a137b07

@ -0,0 +1,108 @@
/*
* 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.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;
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 {
private int count;
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")
@JsonProperty("activities")
public List<Activity> getList() {
return activities;
}
public void setList(List<Activity> activities) {
this.activities = activities;
}
@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(" devices: [").append(activities).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -22,6 +22,8 @@ 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.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList;
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;
@ -44,7 +46,6 @@ public interface ActivityInfoProviderService {
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
response = Activity.class,
value = "Retrieve details of a particular activity.", value = "Retrieve details of a particular activity.",
notes = "This will return information of a particular activity i.e. meta information of an operation, " + notes = "This will return information of a particular activity i.e. meta information of an operation, " +
"etc; including the responses from the devices.", "etc; including the responses from the devices.",
@ -71,12 +72,20 @@ public interface ActivityInfoProviderService {
code = 304, code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of " + message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."), "the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n No activity is found under the provided id."),
@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"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.") message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.",
response = ErrorResponse.class)
}) })
@Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"})
Response getActivity( Response getActivity(
@ -96,8 +105,6 @@ public interface ActivityInfoProviderService {
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
response = Activity.class,
responseContainer = "List",
value = "Retrieve details of a particular activity.", value = "Retrieve details of a particular activity.",
notes = "This will return information of a particular activities i.e. meta information of operations, " + notes = "This will return information of a particular activities i.e. meta information of operations, " +
"etc; including the responses from the devices which happened after given time.", "etc; including the responses from the devices which happened after given time.",
@ -106,8 +113,7 @@ public interface ActivityInfoProviderService {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Activity details are successfully fetched", message = "OK. \n Activity details are successfully fetched",
response = Activity.class, response = ActivityList.class,
responseContainer = "List",
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
name = "Content-Type", name = "Content-Type",
@ -130,7 +136,8 @@ public interface ActivityInfoProviderService {
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 activity data.") message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.",
response = ErrorResponse.class)
}) })
@Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"})
Response getActivities( Response getActivities(
@ -138,8 +145,8 @@ public interface ActivityInfoProviderService {
name = "timestamp", name = "timestamp",
value = "Validates if the requested variant has not been modified since the time specified, this " + value = "Validates if the requested variant has not been modified since the time specified, this " +
"should be provided in unix format in seconds.", "should be provided in unix format in seconds.",
required = false) required = true)
@QueryParam("timestamp") String timestamp, @QueryParam("timestamp") long timestamp,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Validates if the requested variant has not been modified since the time specified", value = "Validates if the requested variant has not been modified since the time specified",

@ -31,7 +31,7 @@ import javax.ws.rs.core.Response;
@API(name = "Application", version = "1.0.0", context = "/devicemgt_admin/applications", tags = {"devicemgt_admin"}) @API(name = "Application", version = "1.0.0", context = "/devicemgt_admin/applications", tags = {"devicemgt_admin"})
@Path("/applications") @Path("/admin/applications")
@Api(value = "Application Management Administrative Service", description = "This an API intended to be used by " + @Api(value = "Application Management Administrative Service", description = "This an API intended to be used by " +
"'internal' components to log in as an admin user and do a selected number of operations. " + "'internal' components to log in as an admin user and do a selected number of operations. " +
"Further, this is strictly restricted to admin users only ") "Further, this is strictly restricted to admin users only ")

@ -28,7 +28,7 @@ import javax.ws.rs.core.Response;
@API(name = "DeviceManagementAdmin", version = "1.0.0", context = "/devicemgt_admin/applications", @API(name = "DeviceManagementAdmin", version = "1.0.0", context = "/devicemgt_admin/applications",
tags = {"devicemgt_admin"}) tags = {"devicemgt_admin"})
@Path("/devices") @Path("/admin/devices")
@Api(value = "Device Management Administrative Service", description = "This an API intended to be used by " + @Api(value = "Device Management Administrative Service", description = "This an API intended to be used by " +
"'internal' components to log in as an admin user and do a selected number of operations. " + "'internal' components to log in as an admin user and do a selected number of operations. " +
"Further, this is strictly restricted to admin users only ") "Further, this is strictly restricted to admin users only ")

@ -27,7 +27,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date; import java.util.Date;
@Path("/groups") @Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " + @Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " +

@ -26,7 +26,7 @@ import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("/users") @Path("/admin/users")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Api(value = "User Management Administrative Service", description = "This an API intended to be used by " + @Api(value = "User Management Administrative Service", description = "This an API intended to be used by " +

@ -23,7 +23,10 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService; import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService;
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.*;
@ -44,23 +47,30 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
public Response getActivity( public Response getActivity(
@PathParam("id") String id, @PathParam("id") String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) { @HeaderParam("If-Modified-Since") String ifModifiedSince) {
Activity operation = null; Activity activity;
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
try { try {
RequestValidationUtil.validateActivityId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
operation = dmService.getOperationByActivityId(id); activity = dmService.getOperationByActivityId(id);
if (activity == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No activity can be found upon the provided " +
"activity id '" + id + "'").build();
}
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity for the supplied id."; String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
log.error(msg, e); log.error(msg, e);
Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).entity(operation).build(); return Response.status(Response.Status.OK).entity(activity).build();
} }
@GET @GET
@Override @Override
public Response getActivities( public Response getActivities(
@QueryParam("timestamp") String timestamp, @QueryParam("timestamp") long timestamp,
@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) {
@ -68,11 +78,13 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
DeviceManagementProviderService dmService; DeviceManagementProviderService dmService;
try { try {
dmService = DeviceMgtAPIUtils.getDeviceManagementService(); dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activities = dmService.getActivitiesUpdatedAfter(Long.parseLong(timestamp)); activities = dmService.getActivitiesUpdatedAfter(timestamp);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activities updated after given time stamp."; String msg = "ErrorResponse occurred while fetching the activities updated after given time stamp.";
log.error(msg, e); log.error(msg, e);
Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
return Response.status(Response.Status.OK).entity(activities).build(); return Response.status(Response.Status.OK).entity(activities).build();
} }

@ -40,7 +40,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("/applications") @Path("/admin/applications")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public class ApplicationManagementAdminServiceImpl implements ApplicationManagementAdminService { public class ApplicationManagementAdminServiceImpl implements ApplicationManagementAdminService {

@ -30,7 +30,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@Path("/devices") @Path("/admin/devices")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminService { public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminService {

@ -31,7 +31,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date; import java.util.Date;
@Path("/groups") @Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public class GroupManagementAdminServiceImpl implements GroupManagementAdminService { public class GroupManagementAdminServiceImpl implements GroupManagementAdminService {

@ -26,7 +26,7 @@ import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("/users") @Path("/admin/users")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public class UserManagementAdminServiceImpl implements UserManagementAdminService { public class UserManagementAdminServiceImpl implements UserManagementAdminService {

@ -168,4 +168,43 @@ public class RequestValidationUtil {
"cannot be null").build()); "cannot be null").build());
} }
} }
public static void validateTimestamp(String timestamp) {
if (timestamp == null || timestamp.isEmpty()) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Timestamp value " +
"cannot be null or empty").build());
}
try {
Long.parseLong(timestamp);
} catch (NumberFormatException e) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Invalid timestamp value").build());
}
}
public static void validateActivityId(String activityId) {
if (activityId == null || activityId.isEmpty()) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Activity Id " +
"cannot be null or empty. It should be in the form of " +
"'[ACTIVITY][_][any-positive-integer]' instead").build());
}
String[] splits = activityId.split("_");
if (splits == null || splits[0] == null || splits[0].isEmpty() || !"ACTIVITY".equals(splits[0]) ||
splits[1] == null || splits[0].isEmpty()) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Activity Id should be in the form of '[ACTIVITY][_][any-positive-integer]'").build());
}
try {
Long.parseLong(splits[1]);
} catch (NumberFormatException e) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Activity Id should be in the form of '[ACTIVITY][_][any-positive-integer]'").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 UnexpectedServerErrorException extends WebApplicationException {
private static final long serialVersionUID = 147943579458906890L;
public UnexpectedServerErrorException(ErrorResponse error) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
}
}

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.common.operation.mgt; package org.wso2.carbon.device.mgt.common.operation.mgt;
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;
@ -36,27 +37,36 @@ public class Activity {
name = "activityId", name = "activityId",
value = "Activity identifier", value = "Activity identifier",
required = true) required = true)
@JsonProperty("activityId")
private String activityId; private String activityId;
@ApiModelProperty( @ApiModelProperty(
name = "code", name = "code",
value = "Activity code", value = "Activity code",
required = true) required = true)
@JsonProperty("code")
private String code; private String code;
@ApiModelProperty( @ApiModelProperty(
name = "type", name = "type",
value = "Activity type", value = "Activity type",
required = true, required = true,
allowableValues = "CONFIG, MESSAGE, INFO, COMMAND, PROFILE, POLICY") allowableValues = "CONFIG, MESSAGE, INFO, COMMAND, PROFILE, POLICY")
@JsonProperty("type")
private Type type; private Type type;
@ApiModelProperty( @ApiModelProperty(
name = "createdTimeStamp", name = "createdTimeStamp",
value = "Timestamp recorded when the activity took place", value = "Timestamp recorded when the activity took place",
required = true) required = true)
@JsonProperty("createdTimestamp")
private String createdTimeStamp; private String createdTimeStamp;
@ApiModelProperty( @ApiModelProperty(
name = "activityStatuses", name = "activityStatuses",
value = "Collection of statuses corresponding to the activity", value = "Collection of statuses corresponding to the activity",
required = true) required = true)
@JsonProperty("activityStatuses")
private List<ActivityStatus> activityStatus; private List<ActivityStatus> activityStatus;
public String getActivityId() { public String getActivityId() {

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.common.operation.mgt; package org.wso2.carbon.device.mgt.common.operation.mgt;
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.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -31,25 +32,33 @@ public class ActivityStatus {
public enum Status { public enum Status {
IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED
} }
@ApiModelProperty( @ApiModelProperty(
name = "deviceIdentifier", name = "deviceIdentifier",
value = "Device identifier of the device.", value = "Device identifier of the device.",
required = true) required = true)
@JsonProperty("deviceIdentifier")
private DeviceIdentifier deviceIdentifier; private DeviceIdentifier deviceIdentifier;
@ApiModelProperty( @ApiModelProperty(
name = "status", name = "status",
value = "Status of the activity performed.", value = "Status of the activity performed.",
required = true) required = true)
@JsonProperty("status")
private Status status; private Status status;
@ApiModelProperty( @ApiModelProperty(
name = "responses", name = "responses",
value = "Responses received from devices.", value = "Responses received from devices.",
required = true) required = true)
@JsonProperty("responses")
private List<OperationResponse> responses; private List<OperationResponse> responses;
@ApiModelProperty( @ApiModelProperty(
name = "updatedTimestamp ", name = "updatedTimestamp ",
value = "Last updated time of the activity.", value = "Last updated time of the activity.",
required = true) required = true)
@JsonProperty("updatedTimestamp")
private String updatedTimestamp; private String updatedTimestamp;
public DeviceIdentifier getDeviceIdentifier() { public DeviceIdentifier getDeviceIdentifier() {

@ -757,13 +757,13 @@ public class OperationManagerImpl implements OperationManager {
// This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
int operationId = Integer.parseInt( int operationId = Integer.parseInt(
activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
if(operationId == 0){ if (operationId == 0){
throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
} }
try { try {
OperationManagementDAOFactory.openConnection(); OperationManagementDAOFactory.openConnection();
Activity act = operationDAO.getActivity(operationId); Activity act = operationDAO.getActivity(operationId);
act.setActivityId(activity); // act.setActivityId(activity);
return act; return act;
} catch (SQLException e) { } catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);

@ -52,7 +52,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
Connection connection = OperationManagementDAOFactory.getConnection(); Connection connection = OperationManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE) " + String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE) " +
"VALUES (?, ?, ?, ?)"; "VALUES (?, ?, ?, ?)";
stmt = connection.prepareStatement(sql, new String[] {"id"}); stmt = connection.prepareStatement(sql, new String[]{"id"});
stmt.setString(1, operation.getType().toString()); stmt.setString(1, operation.getType().toString());
stmt.setTimestamp(2, new Timestamp(new Date().getTime())); stmt.setTimestamp(2, new Timestamp(new Date().getTime()));
stmt.setTimestamp(3, null); stmt.setTimestamp(3, null);
@ -93,7 +93,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
throws OperationManagementDAOException { throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
long time = System.currentTimeMillis()/1000; long time = System.currentTimeMillis() / 1000;
Connection connection = OperationManagementDAOFactory.getConnection(); Connection connection = OperationManagementDAOFactory.getConnection();
stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS=?, UPDATED_TIMESTAMP=? " + stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS=?, UPDATED_TIMESTAMP=? " +
"WHERE ENROLMENT_ID=? and OPERATION_ID=?"); "WHERE ENROLMENT_ID=? and OPERATION_ID=?");
@ -128,14 +128,14 @@ public class GenericOperationDAOImpl implements OperationDAO {
// This will return only one result always. // This will return only one result always.
rs = stmt.executeQuery(); rs = stmt.executeQuery();
int id = 0; int id = 0;
while (rs.next()){ while (rs.next()) {
id = rs.getInt("ID"); id = rs.getInt("ID");
} }
if (id != 0){ if (id != 0) {
stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ?, " + stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ?, " +
"UPDATED_TIMESTAMP = ? WHERE ID = ?"); "UPDATED_TIMESTAMP = ? WHERE ID = ?");
stmt.setString(1, newStatus.toString()); stmt.setString(1, newStatus.toString());
stmt.setLong(2, System.currentTimeMillis()/1000); stmt.setLong(2, System.currentTimeMillis() / 1000);
stmt.setInt(3, id); stmt.setInt(3, id);
stmt.executeUpdate(); stmt.executeUpdate();
} }
@ -257,7 +257,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
Activity activity = new Activity(); Activity activity = null;
List<ActivityStatus> activityStatusList = new ArrayList<>(); List<ActivityStatus> activityStatusList = new ArrayList<>();
try { try {
Connection conn = OperationManagementDAOFactory.getConnection(); Connection conn = OperationManagementDAOFactory.getConnection();
@ -281,8 +281,10 @@ public class GenericOperationDAOImpl implements OperationDAO {
int enrolmentId = 0; int enrolmentId = 0;
ActivityStatus activityStatus = null; ActivityStatus activityStatus = null;
while (rs.next()) {
if (enrolmentId == 0){ if (rs.next()) {
activity = new Activity();
if (enrolmentId == 0) {
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP"))).toString()); activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP"))).toString());
activity.setCode(rs.getString("OPERATION_CODE")); activity.setCode(rs.getString("OPERATION_CODE"));
@ -306,6 +308,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
activityStatusList.add(activityStatus); activityStatusList.add(activityStatus);
enrolmentId = rs.getInt("ENROLMENT_ID"); enrolmentId = rs.getInt("ENROLMENT_ID");
activity.setActivityStatus(activityStatusList);
} else { } else {
if (rs.getInt("UPDATED_TIMESTAMP") != 0) { if (rs.getInt("UPDATED_TIMESTAMP") != 0) {
activityStatus.getResponses().add(this.getOperationResponse(rs)); activityStatus.getResponses().add(this.getOperationResponse(rs));
@ -322,7 +325,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
} finally { } finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs); OperationManagementDAOUtil.cleanupResources(stmt, rs);
} }
activity.setActivityStatus(activityStatusList);
return activity; return activity;
} }
@ -357,7 +359,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
ActivityStatus activityStatus = null; ActivityStatus activityStatus = null;
while (rs.next()) { while (rs.next()) {
if(operationId != rs.getInt("OPERATION_ID")) { if (operationId != rs.getInt("OPERATION_ID")) {
activity = new Activity(); activity = new Activity();
activities.add(activity); activities.add(activity);
List<ActivityStatus> statusList = new ArrayList<>(); List<ActivityStatus> statusList = new ArrayList<>();
@ -388,7 +390,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
} }
if(operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) { if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) {
activityStatus = new ActivityStatus(); activityStatus = new ActivityStatus();
activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE")));
@ -403,7 +405,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS")));
List<OperationResponse> operationResponses = new ArrayList<>(); List<OperationResponse> operationResponses = new ArrayList<>();
if (rs.getTimestamp("RECEIVED_TIMESTAMP") !=(null)) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
operationResponses.add(this.getOperationResponse(rs)); operationResponses.add(this.getOperationResponse(rs));
} }
activityStatus.setResponses(operationResponses); activityStatus.setResponses(operationResponses);
@ -411,7 +413,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
enrolmentId = rs.getInt("ENROLMENT_ID"); enrolmentId = rs.getInt("ENROLMENT_ID");
} else { } else {
if (rs.getTimestamp("RECEIVED_TIMESTAMP") !=(null)) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
activityStatus.getResponses().add(this.getOperationResponse(rs)); activityStatus.getResponses().add(this.getOperationResponse(rs));
} }
} }
@ -432,14 +434,14 @@ public class GenericOperationDAOImpl implements OperationDAO {
private OperationResponse getOperationResponse(ResultSet rs) throws private OperationResponse getOperationResponse(ResultSet rs) throws
ClassNotFoundException, IOException, SQLException { ClassNotFoundException, IOException, SQLException {
OperationResponse response = new OperationResponse(); OperationResponse response = new OperationResponse();
if(rs.getTimestamp("RECEIVED_TIMESTAMP") !=(null)) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) {
response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
} }
ByteArrayInputStream bais = null; ByteArrayInputStream bais = null;
ObjectInputStream ois = null; ObjectInputStream ois = null;
byte[] contentBytes; byte[] contentBytes;
try { try {
if(rs.getBytes("OPERATION_RESPONSE") != null) { if (rs.getBytes("OPERATION_RESPONSE") != null) {
contentBytes = (byte[]) rs.getBytes("OPERATION_RESPONSE"); contentBytes = (byte[]) rs.getBytes("OPERATION_RESPONSE");
bais = new ByteArrayInputStream(contentBytes); bais = new ByteArrayInputStream(contentBytes);
ois = new ObjectInputStream(bais); ois = new ObjectInputStream(bais);
@ -515,7 +517,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
} catch (SQLException e) { } catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while retrieving the operations updated " + throw new OperationManagementDAOException("Error occurred while retrieving the operations updated " +
"after a given time" , e); "after a given time", e);
} finally { } finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs); OperationManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -523,7 +525,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
} }
@Override @Override
public void deleteOperation(int id) throws OperationManagementDAOException { public void deleteOperation(int id) throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -603,7 +604,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
@ -650,7 +651,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
this.setActivityId(operation, rs.getInt("ID")); this.setActivityId(operation, rs.getInt("ID"));
@ -696,7 +697,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
operation.setStatus(status); operation.setStatus(status);
@ -714,7 +715,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
@Override @Override
public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request, public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request,
Operation.Status status) Operation.Status status)
throws OperationManagementDAOException { throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -723,10 +724,10 @@ public class GenericOperationDAOImpl implements OperationDAO {
try { try {
Connection conn = OperationManagementDAOFactory.getConnection(); Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE, " + String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE, " +
"om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
"INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " +
"WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " +
"o.CREATED_TIMESTAMP DESC LIMIT ?,?"; "o.CREATED_TIMESTAMP DESC LIMIT ?,?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId); stmt.setInt(1, enrolmentId);
stmt.setString(2, status.toString()); stmt.setString(2, status.toString());
@ -748,7 +749,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
operation.setStatus(status); operation.setStatus(status);
@ -757,7 +758,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " +
"available for the device'" + enrolmentId + "' with status '" + status.toString(), e); "available for the device'" + enrolmentId + "' with status '" + status.toString(), e);
} finally { } finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs); OperationManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -794,7 +795,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
@ -820,9 +821,9 @@ public class GenericOperationDAOImpl implements OperationDAO {
try { try {
Connection conn = OperationManagementDAOFactory.getConnection(); Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " +
"OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " +
"INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " +
"WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ?,?"; "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ?,?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId); stmt.setInt(1, enrolmentId);
stmt.setInt(2, request.getStartIndex()); stmt.setInt(2, request.getStartIndex());
@ -843,7 +844,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
@ -852,7 +853,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " +
"available for the device'" + enrolmentId + "' with status '", e); "available for the device'" + enrolmentId + "' with status '", e);
} finally { } finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs); OperationManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -876,7 +877,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment : " throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment : "
+ enrolmentId, e); + enrolmentId, e);
} finally { } finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs); OperationManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -913,7 +914,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
operation.setStatus(Operation.Status.PENDING); operation.setStatus(Operation.Status.PENDING);
@ -962,7 +963,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
operation.setReceivedTimeStamp(""); operation.setReceivedTimeStamp("");
} else { } else {
operation.setReceivedTimeStamp( operation.setReceivedTimeStamp(
new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP")*1000)).toString()); new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
} }
operation.setCode(rs.getString("OPERATION_CODE")); operation.setCode(rs.getString("OPERATION_CODE"));
this.setActivityId(operation, rs.getInt("ID")); this.setActivityId(operation, rs.getInt("ID"));
@ -986,7 +987,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
} }
private String getActivityId( int operationId) { private String getActivityId(int operationId) {
return DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId; return DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId;
} }

Loading…
Cancel
Save