Sync with upstream master

4.x.x
lasanthaDLPDS 5 years ago
commit f6098a75af

@ -58,6 +58,10 @@
<param-name>isSharedWithAllTenants</param-name> <param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param>
<param-name>basicAuth</param-name>
<param-value>true</param-value>
</context-param>
<security-constraint> <security-constraint>
<web-resource-collection> <web-resource-collection>

@ -23,6 +23,7 @@ import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.policy.mgt.DeviceGroupWrapper; import org.wso2.carbon.device.mgt.common.policy.mgt.DeviceGroupWrapper;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.List; import java.util.List;
@ -102,6 +103,19 @@ public class PolicyWrapper {
required = true) required = true)
private List<DeviceGroupWrapper> deviceGroups; private List<DeviceGroupWrapper> deviceGroups;
@ApiModelProperty(name = "policyType", value = "Type of the corresponding policy",
required = true)
@NotNull
private String policyType;
public String getPolicyType() {
return policyType;
}
public void setPolicyType(String policyType) {
this.policyType = policyType;
}
public Profile getProfile() { public Profile getProfile() {
return profile; return profile;
} }

@ -469,17 +469,21 @@ public interface DeviceManagementService {
String id, String id,
@ApiParam( @ApiParam(
name = "owner", name = "owner",
value = "The owner of the device you want ot get details.", value = "The owner of the device you want ot get details.")
required = false)
@QueryParam("owner") @QueryParam("owner")
@Size(max = 100) @Size(max = 100)
String owner, String owner,
@ApiParam(
name = "ownership",
value = "Device ownership.")
@QueryParam("ownership")
@Size(max = 100)
String ownership,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200", "Example: Mon, 05 Jan 2014 15:10:00 +0200")
required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); String ifModifiedSince);
@ -1412,21 +1416,18 @@ public interface DeviceManagementService {
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200", "Example: Mon, 05 Jan 2014 15:10:00 +0200")
required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince, String ifModifiedSince,
@ApiParam( @ApiParam(
name = "offset", name = "offset",
value = "The starting pagination index for the complete list of qualified items.", value = "The starting pagination index for the complete list of qualified items.",
required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") @QueryParam("offset")
int offset, int offset,
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many activity details you require from the starting pagination index/offset.", value = "Provide how many activity details you require from the starting pagination index/offset.",
required = false,
defaultValue = "5") defaultValue = "5")
@QueryParam("limit") @QueryParam("limit")
int limit, int limit,
@ -1436,7 +1437,12 @@ public interface DeviceManagementService {
required = true, required = true,
defaultValue = "") defaultValue = "")
@QueryParam("owner") @QueryParam("owner")
String owner); String owner,
@ApiParam(
name = "ownership",
value = "Provides the ownership of the required device.")
@QueryParam("owner")
String ownership);
@GET @GET
@Path("/{type}/{id}/effective-policy") @Path("/{type}/{id}/effective-policy")

@ -697,4 +697,87 @@ public interface PolicyManagementService {
@PathParam("deviceId") @PathParam("deviceId")
@Size(max = 45) @Size(max = 45)
String deviceId); String deviceId);
@GET
@Path("/type/{policyType}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Policies",
responseContainer = "List",
notes = "Retrieve the details of all the policies filtered by policy type in WSO2 EMM.",
response = Policy.class,
tags = "Device Policy Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:get-details")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched policies.",
response = Policy.class,
responseContainer = "List",
responseHeaders = {
@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 was last modified.\n" +
"Used by caches, or in conditional requests."),
}
),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version " +
"of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = ("Internal Server Error. \n Server error occurred while fetching the policies."),
response = ErrorResponse.class)
})
Response getPolicies(@ApiParam(
name = "policyType",
value = "The policy type, such as general policy, Geo policy.",
required = true)
@PathParam("policyType")
String policyType,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since")
String ifModifiedSince,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items",
required = false,
defaultValue = "0")
@QueryParam("offset")
int offset,
@ApiParam(
name = "limit",
value = "Provide how many policy details you require from the starting pagination index/offset.",
required = false,
defaultValue = "5")
@QueryParam("limit")
int limit
);
} }

@ -36,6 +36,7 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -51,6 +52,7 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
@ -106,6 +108,7 @@ import javax.ws.rs.core.Response;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -383,8 +386,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@PathParam("type") @Size(max = 45) String type, @PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id, @PathParam("id") @Size(max = 45) String id,
@QueryParam("owner") @Size(max = 100) String owner, @QueryParam("owner") @Size(max = 100) String owner,
@QueryParam("ownership") @Size(max = 100) String ownership,
@HeaderParam("If-Modified-Since") String ifModifiedSince) { @HeaderParam("If-Modified-Since") String ifModifiedSince) {
Device device = null; Device device;
Date sinceDate = null;
try { try {
RequestValidationUtil.validateDeviceIdentifier(type, id); RequestValidationUtil.validateDeviceIdentifier(type, id);
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
@ -399,61 +404,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id + "'"; String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id + "'";
log.error(msg); log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity( return Response.status(Response.Status.UNAUTHORIZED).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_UNAUTHORIZED).setMessage(msg).build()).build();
} }
Date sinceDate = null; DeviceData deviceData = new DeviceData();
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { deviceData.setDeviceIdentifier(deviceIdentifier);
if (!StringUtils.isBlank(ifModifiedSince)){
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
try { try {
sinceDate = format.parse(ifModifiedSince); sinceDate = format.parse(ifModifiedSince);
deviceData.setLastModifiedDate(sinceDate);
} catch (ParseException e) { } catch (ParseException e) {
String msg = "Invalid date string is provided in 'If-Modified-Since' header";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity( return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
"string is provided in 'If-Modified-Since' header").build()).build();
} }
} }
if (!StringUtils.isEmpty(owner)) { if (!StringUtils.isBlank(owner)){
if (authorizedUser.equalsIgnoreCase(owner) || deviceAccessAuthorizationService.isDeviceAdminUser()) { deviceData.setDeviceOwner(owner);
if (sinceDate != null) {
device = dms.getDevice(new DeviceIdentifier(id, type), owner, sinceDate, true);
if (device == null) {
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
}
} else {
device = dms.getDevice(new DeviceIdentifier(id, type), owner, true);
}
} else {
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id +
"' which belongs to user '" + owner + "'";
log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build();
}
} else if (deviceAccessAuthorizationService.isDeviceAdminUser()) {
if (sinceDate != null) {
device = dms.getDevice(new DeviceIdentifier(id, type), sinceDate);
if (device == null) {
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
}
} else {
device = dms.getDevice(new DeviceIdentifier(id, type));
}
} else {
owner = authorizedUser;
if (sinceDate != null) {
device = dms.getDevice(new DeviceIdentifier(id, type), owner, sinceDate, true);
if (device == null) {
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
}
} else {
device = dms.getDevice(new DeviceIdentifier(id, type), owner, true);
} }
if (!StringUtils.isBlank(ownership)){
deviceData.setDeviceOwnership(ownership);
} }
device = dms.getDevice(deviceData, true);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the device information."; String msg = "Error occurred while fetching the device information.";
log.error(msg, e); log.error(msg, e);
@ -466,8 +442,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} }
if (device == null) { if (device == null) {
if (sinceDate != null) {
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
}
return Response.status(Response.Status.NOT_FOUND).entity( return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Requested device of type '" + new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_NOT_FOUND).setMessage("Requested device of type '" +
type + "', which carries id '" + id + "' does not exist").build()).build(); type + "', which carries id '" + id + "' does not exist").build()).build();
} }
return Response.status(Response.Status.OK).entity(device).build(); return Response.status(Response.Status.OK).entity(device).build();
@ -782,7 +762,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@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,
@QueryParam("owner") String owner) { @QueryParam("owner") String owner,
@QueryParam("ownership") String ownership) {
OperationList operationsList = new OperationList(); OperationList operationsList = new OperationList();
RequestValidationUtil.validateOwnerParameter(owner); RequestValidationUtil.validateOwnerParameter(owner);
RequestValidationUtil.validatePaginationParameters(offset, limit); RequestValidationUtil.validatePaginationParameters(offset, limit);
@ -793,6 +774,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try { try {
RequestValidationUtil.validateDeviceIdentifier(type, id); RequestValidationUtil.validateDeviceIdentifier(type, id);
dms = DeviceMgtAPIUtils.getDeviceManagementService(); dms = DeviceMgtAPIUtils.getDeviceManagementService();
if (!StringUtils.isBlank(ownership)) {
request.setOwnership(ownership);
}
result = dms.getOperations(new DeviceIdentifier(id, type), request); result = dms.getOperations(new DeviceIdentifier(id, type), request);
operationsList.setList((List<? extends Operation>) result.getData()); operationsList.setList((List<? extends Operation>) result.getData());
operationsList.setCount(result.getRecordsTotal()); operationsList.setCount(result.getRecordsTotal());

@ -123,6 +123,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
policy.setUsers(policyWrapper.getUsers()); policy.setUsers(policyWrapper.getUsers());
policy.setCompliance(policyWrapper.getCompliance()); policy.setCompliance(policyWrapper.getCompliance());
policy.setDeviceGroups(policyWrapper.getDeviceGroups()); policy.setDeviceGroups(policyWrapper.getDeviceGroups());
policy.setPolicyType(policyWrapper.getPolicyType());
//TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here. //TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here.
List<Device> devices = new ArrayList<Device>(); List<Device> devices = new ArrayList<Device>();
List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers(); List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers();
@ -398,4 +399,33 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
return Response.status(Response.Status.OK).entity(policy).build(); return Response.status(Response.Status.OK).entity(policy).build();
} }
@GET
@Path("/type/{policyType}")
@Override
public Response getPolicies(
@PathParam("policyType") String policyType,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
RequestValidationUtil.validatePaginationParameters(offset, limit);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<Policy> policies;
List<Policy> filteredPolicies;
PolicyList targetPolicies = new PolicyList();
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicies(policyType);
targetPolicies.setCount(policies.size());
filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit);
targetPolicies.setList(filteredPolicies);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving all available policies";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(targetPolicies).build();
}
} }

@ -628,7 +628,8 @@ public class DeviceManagementServiceImplTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME); .getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME,
DEFAULT_OWNERSHIP);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"Expects to return HTTP 200 when the operation is retrieved successfully."); "Expects to return HTTP 200 when the operation is retrieved successfully.");
} }
@ -640,7 +641,8 @@ public class DeviceManagementServiceImplTest {
Mockito.when(this.deviceManagementProviderService.getOperations(Mockito.any(DeviceIdentifier.class), Mockito.when(this.deviceManagementProviderService.getOperations(Mockito.any(DeviceIdentifier.class),
Mockito.any(PaginationRequest.class))).thenThrow(new OperationManagementException()); Mockito.any(PaginationRequest.class))).thenThrow(new OperationManagementException());
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME); .getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME,
DEFAULT_OWNERSHIP);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Expects to return HTTP 500 when an exception occurred while retrieving operation list of the device"); "Expects to return HTTP 500 when an exception occurred while retrieving operation list of the device");
} }

@ -0,0 +1,77 @@
/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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.device.details;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.Date;
public class DeviceData {
/***
* Identifier of the device, which contains identifier and device ype.
*/
private DeviceIdentifier deviceIdentifier;
/***
* User who is enrolled the device.
*/
private String deviceOwner;
/***
* Last modified date.
*/
private Date lastModifiedDate;
/***
* Current status of the device, e.g ACTIVE, INACTIVE, REMOVED etc.
*/
private String deviceOwnership;
public DeviceIdentifier getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public String getDeviceOwner() {
return deviceOwner;
}
public void setDeviceOwner(String deviceOwner) {
this.deviceOwner = deviceOwner;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public String getDeviceOwnership() {
return deviceOwnership;
}
public void setDeviceOwnership(String deviceOwnership) {
this.deviceOwnership = deviceOwnership;
}
}

@ -177,6 +177,12 @@ public class Policy implements Comparable<Policy>, Serializable {
example = "[]") example = "[]")
private List<DeviceGroupWrapper> deviceGroups; private List<DeviceGroupWrapper> deviceGroups;
@ApiModelProperty(
name = "policyType",
value = "Type of the corresponding policy",
required = true,
example = "GENERAL")
private String policyType;
@XmlElement @XmlElement
public int getId() { public int getId() {
@ -341,6 +347,14 @@ public class Policy implements Comparable<Policy>, Serializable {
this.deviceGroups = deviceGroups; this.deviceGroups = deviceGroups;
} }
public String getPolicyType() {
return policyType;
}
public void setPolicyType(String policyType) {
this.policyType = policyType;
}
@Override @Override
public int compareTo(Policy o) { public int compareTo(Policy o) {
if (this.priorityId == o.priorityId) if (this.priorityId == o.priorityId)

@ -42,6 +42,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo; import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.core.geo.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate;
@ -139,6 +140,9 @@ public interface DeviceDAO {
*/ */
boolean updateDevice(Device device, int tenantId) throws DeviceManagementDAOException; boolean updateDevice(Device device, int tenantId) throws DeviceManagementDAOException;
Device getDevice(DeviceData deviceData, int tenantId) throws DeviceManagementDAOException;
/** /**
* This method is used to retrieve a device of a given device-identifier and tenant-id. * This method is used to retrieve a device of a given device-identifier and tenant-id.
* *
@ -446,13 +450,13 @@ public interface DeviceDAO {
* This method is used to retrieve current enrollment of a given device and user. * This method is used to retrieve current enrollment of a given device and user.
* *
* @param deviceId device id. * @param deviceId device id.
* @param currentUser user name. * @param request {@link PaginationRequest}
* @param tenantId tenant id. * @param tenantId tenant id.
* @return returns EnrolmentInfo object. * @return returns EnrolmentInfo object.
* @throws DeviceManagementDAOException * @throws DeviceManagementDAOException if SQL error occurred while processing the query.
*/ */
EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser, EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, PaginationRequest request, int tenantId)
int tenantId) throws DeviceManagementDAOException; throws DeviceManagementDAOException;
/** /**
* This method is used to retrieve current active enrollment of a given device and tenant id. * This method is used to retrieve current active enrollment of a given device and tenant id.

@ -36,6 +36,7 @@
package org.wso2.carbon.device.mgt.core.dao.impl; package org.wso2.carbon.device.mgt.core.dao.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -44,6 +45,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo; import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
@ -138,6 +140,84 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} }
@Override
public Device getDevice(DeviceData deviceData, int tenantId) throws DeviceManagementDAOException {
Device device = null;
try {
Connection conn = this.getConnection();
String sql = "SELECT "
+ "d1.ID AS DEVICE_ID, "
+ "d1.DESCRIPTION, "
+ "d1.NAME AS DEVICE_NAME, "
+ "d1.DEVICE_TYPE, "
+ "d1.DEVICE_IDENTIFICATION, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.STATUS, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.ID AS ENROLMENT_ID "
+ "FROM DM_ENROLMENT e, "
+ "(SELECT "
+ "d.ID, "
+ "d.DESCRIPTION, "
+ "d.NAME, "
+ "t.NAME AS DEVICE_TYPE, "
+ "d.DEVICE_IDENTIFICATION "
+ "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt "
+ "WHERE "
+ "t.NAME = ? AND "
+ "t.ID = d.DEVICE_TYPE_ID AND "
+ "d.DEVICE_IDENTIFICATION = ? AND "
+ "d.TENANT_ID = ? AND "
+ "dt.DEVICE_ID = d.ID";
if (deviceData.getLastModifiedDate() != null) {
sql += " AND dt.UPDATE_TIMESTAMP > ?";
}
sql += ") d1 WHERE d1.ID = e.DEVICE_ID AND ";
if (!StringUtils.isBlank(deviceData.getDeviceOwner())) {
sql += "e.OWNER = ? AND ";
}
if (!StringUtils.isBlank(deviceData.getDeviceOwnership())) {
sql += "e.OWNERSHIP = ? AND ";
}
sql += "TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIndx = 1;
stmt.setString(paramIndx++, deviceData.getDeviceIdentifier().getType());
stmt.setString(paramIndx++, deviceData.getDeviceIdentifier().getId());
stmt.setInt(paramIndx++, tenantId);
if (deviceData.getLastModifiedDate() != null) {
stmt.setLong(paramIndx++, deviceData.getLastModifiedDate().getTime());
}
if (!StringUtils.isBlank(deviceData.getDeviceOwner())) {
stmt.setString(paramIndx++, deviceData.getDeviceOwner());
}
if (!StringUtils.isBlank(deviceData.getDeviceOwnership())) {
stmt.setString(paramIndx++, deviceData.getDeviceOwnership());
}
stmt.setInt(paramIndx, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
device = DeviceManagementDAOUtil.loadMatchingDevice(rs, false);
}
}
}
} catch (SQLException e) {
String msg = "Error occurred while getting device data for device identifier "
+ deviceData.getDeviceIdentifier().getId() + " and device type "
+ deviceData.getDeviceIdentifier().getType();
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
return device;
}
@Override @Override
public Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException { public Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
@ -238,7 +318,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " +
"t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
"AND TENANT_ID = ? AND e.OWNER = ?"; "AND TENANT_ID = ? AND e.OWNER = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getType()); stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceIdentifier.getId()); stmt.setString(2, deviceIdentifier.getId());
@ -507,7 +587,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " +
"WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " +
"AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?"; "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getType()); stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceIdentifier.getId()); stmt.setString(2, deviceIdentifier.getId());
@ -1292,36 +1372,54 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
@Override @Override
public EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentOwner, public EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, PaginationRequest request, int tenantId)
int tenantId) throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo enrolmentInfo = null; EnrolmentInfo enrolmentInfo = null;
try { try {
conn = this.getConnection(); Connection conn = this.getConnection();
String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + String sql = "SELECT "
"DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + + "ID AS ENROLMENT_ID, "
+ "DEVICE_ID, "
+ "OWNER, "
+ "OWNERSHIP, "
+ "STATUS, "
+ "DATE_OF_ENROLMENT, "
+ "DATE_OF_LAST_UPDATE, "
+ "TENANT_ID "
+ "FROM DM_ENROLMENT "
+ "WHERE "
+ "DEVICE_ID = (SELECT d.ID " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " +
"AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) "
"AND OWNER = ? AND TENANT_ID = ?"; + "AND OWNER = ? ";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId()); if (!StringUtils.isBlank(request.getOwnership())) {
stmt.setString(2, deviceId.getType()); sql += "AND OWNERSHIP = ? ";
stmt.setInt(3, tenantId); }
stmt.setString(4, currentOwner); sql += "AND TENANT_ID = ?";
stmt.setInt(5, tenantId); int paramIdx = 1;
rs = stmt.executeQuery(); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(paramIdx++, deviceId.getId());
stmt.setString(paramIdx++, deviceId.getType());
stmt.setInt(paramIdx++, tenantId);
stmt.setString(paramIdx++, request.getOwner());
if (!StringUtils.isBlank(request.getOwnership())) {
stmt.setString(paramIdx++, request.getOwnership());
}
stmt.setInt(paramIdx, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { if (rs.next()) {
enrolmentInfo = DeviceManagementDAOUtil.loadMatchingEnrolment(rs); enrolmentInfo = DeviceManagementDAOUtil.loadMatchingEnrolment(rs);
} }
return enrolmentInfo; }
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + String msg = "Error occurred while retrieving the enrolment " +
"information of user '" + currentOwner + "' upon device '" + deviceId + "'", e); "information of user '" + request.getOwner() + "' upon device '" + deviceId + "'";
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return enrolmentInfo;
} }
@Override @Override

@ -458,7 +458,12 @@ public class OperationManagerImpl implements OperationManager {
deviceId.getType() + "' device, which carries the identifier '" + deviceId.getType() + "' device, which carries the identifier '" +
deviceId.getId() + "' of owner '" + owner + "'"); deviceId.getId() + "' of owner '" + owner + "'");
} }
EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, owner); EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, request);
if (enrolmentInfo == null){
throw new OperationManagementException("Enrollment info not found for given device which has device "
+ "Identifier:" + deviceId.getId() + " and device type: " + deviceId.getType() + "Further, device "
+ "is own to: " + owner);
}
int enrolmentId = enrolmentInfo.getId(); int enrolmentId = enrolmentInfo.getId();
try { try {
OperationManagementDAOFactory.openConnection(); OperationManagementDAOFactory.openConnection();
@ -1072,33 +1077,34 @@ public class OperationManagerImpl implements OperationManager {
return isUserAuthorized; return isUserAuthorized;
} }
private EnrolmentInfo getEnrolmentInfo(DeviceIdentifier deviceId, String owner) throws OperationManagementException { private EnrolmentInfo getEnrolmentInfo(DeviceIdentifier deviceId, PaginationRequest request)
throws OperationManagementException {
EnrolmentInfo enrolmentInfo = null; EnrolmentInfo enrolmentInfo = null;
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
String user = this.getUser(); String user = this.getUser();
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
if (this.isSameUser(user, owner)) { if (this.isSameUser(user, request.getOwner())) {
enrolmentInfo = deviceDAO.getEnrolment(deviceId, owner, tenantId); enrolmentInfo = deviceDAO.getEnrolment(deviceId, request, tenantId);
} else { } else {
boolean isAdminUser = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). boolean isAdminUser = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
isDeviceAdminUser(); isDeviceAdminUser();
if (isAdminUser) { if (isAdminUser) {
enrolmentInfo = deviceDAO.getEnrolment(deviceId, owner, tenantId); enrolmentInfo = deviceDAO.getEnrolment(deviceId, request, tenantId);
} }
//TODO : Add a check for group admin if this fails //TODO : Add a check for group admin if this fails
} }
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving enrollment data of '" + throw new OperationManagementException("Error occurred while retrieving enrollment data of '" +
deviceId.getType() + "' device carrying the identifier '" + deviceId.getType() + "' device carrying the identifier '" +
deviceId.getId() + "' of owner '" + owner + "'", e); deviceId.getId() + "' of owner '" + request.getOwner() + "'", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new OperationManagementException( throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e); "Error occurred while opening a connection to the data source", e);
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while checking the device access permissions for '" + throw new OperationManagementException("Error occurred while checking the device access permissions for '" +
deviceId.getType() + "' device carrying the identifier '" + deviceId.getType() + "' device carrying the identifier '" +
deviceId.getId() + "' of owner '" + owner + "'", e); deviceId.getId() + "' of owner '" + request.getOwner() + "'", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }

@ -56,6 +56,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManageme
import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
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.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -262,6 +263,17 @@ public interface DeviceManagementProviderService {
*/ */
Device getDevice(DeviceIdentifier deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException; Device getDevice(DeviceIdentifier deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException;
/***
*
* @param deviceData Device data,
* @param requireDeviceInfo A boolean indicating whether the device-info (location, app-info etc) is also required
* along with the device data.
* @return {@link Device}, null when device is not available.
* @throws {@link DeviceManagementException}
*/
Device getDevice(DeviceData deviceData, boolean requireDeviceInfo) throws DeviceManagementException;
/** /**
* Retrieves a list of devices based on a given criteria of properties * Retrieves a list of devices based on a given criteria of properties
* *

@ -77,6 +77,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManageme
import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo; import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
@ -1242,6 +1243,54 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return device; return device;
} }
@Override
public Device getDevice(DeviceData deviceData, boolean requireDeviceInfo)
throws DeviceManagementException {
if (deviceData.getDeviceIdentifier() == null) {
String msg = "Received null device identifier for method getDevice";
log.error(msg);
throw new DeviceManagementException(msg);
}
if (log.isDebugEnabled()) {
log.debug("Get device by device identifier :" + deviceData.getDeviceIdentifier().getId() + " of type '"
+ deviceData.getDeviceIdentifier().getType() + "' and requiredDeviceInfo: " + requireDeviceInfo);
}
Device device = null;
int tenantId = this.getTenantId();
try {
DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceData, tenantId);
if (device == null) {
String msg =
"No device is found upon the type '" + deviceData.getDeviceIdentifier().getType() + "' and id '"
+ deviceData.getDeviceIdentifier().getId() + "'";
if (log.isDebugEnabled()) {
log.debug(msg);
}
return null;
}
} catch (DeviceManagementDAOException e) {
String msg =
"Error occurred while obtaining the device for '" + deviceData.getDeviceIdentifier().getId() + "'";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg);
throw new DeviceManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getDevice: " + deviceData.getDeviceIdentifier().getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
if (requireDeviceInfo) {
return this.getAllDeviceInfo(device);
}
return device;
}
@Override @Override
public List<Device> getDevicesBasedOnProperties(Map deviceProps) throws DeviceManagementException { public List<Device> getDevicesBasedOnProperties(Map deviceProps) throws DeviceManagementException {
@ -1718,9 +1767,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
@Override @Override
public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request)
throws OperationManagementException { throws OperationManagementException {
request = DeviceManagerUtil.validateOperationListPageSize(request);
return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()) return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId())
.getOperations(deviceId, request); .getOperations(deviceId, DeviceManagerUtil.validateOperationListPageSize(request));
} }
@Override @Override

@ -55,6 +55,7 @@ public class OperationManagementNegativeDBOperationTest extends BaseDeviceManage
private static final String DEVICE_ID_PREFIX = "NEGDB_OP-TEST-DEVICE-ID-"; private static final String DEVICE_ID_PREFIX = "NEGDB_OP-TEST-DEVICE-ID-";
private static final int NO_OF_DEVICES = 5; private static final int NO_OF_DEVICES = 5;
private static final String ADMIN_USER = "admin"; private static final String ADMIN_USER = "admin";
private static final String OWNSERSHIP = "BYOD";
private List<DeviceIdentifier> deviceIds = new ArrayList<>(); private List<DeviceIdentifier> deviceIds = new ArrayList<>();
private OperationManager operationMgtService; private OperationManager operationMgtService;
@ -111,6 +112,7 @@ public class OperationManagementNegativeDBOperationTest extends BaseDeviceManage
PaginationRequest request = new PaginationRequest(1, 2); PaginationRequest request = new PaginationRequest(1, 2);
request.setDeviceType(DEVICE_TYPE); request.setDeviceType(DEVICE_TYPE);
request.setOwner(ADMIN_USER); request.setOwner(ADMIN_USER);
request.setOwnership(OWNSERSHIP);
this.dataSource.setThrowException(true); this.dataSource.setThrowException(true);
try { try {
this.operationMgtService.getOperations(this.deviceIds.get(0), request); this.operationMgtService.getOperations(this.deviceIds.get(0), request);

@ -57,6 +57,7 @@ public class OperationManagementNoDBSchemaTests extends BaseDeviceManagementTest
private static final String COMMAND_OPERATON_CODE = "COMMAND-TEST"; private static final String COMMAND_OPERATON_CODE = "COMMAND-TEST";
private static final int NO_OF_DEVICES = 5; private static final int NO_OF_DEVICES = 5;
private static final String ADMIN_USER = "admin"; private static final String ADMIN_USER = "admin";
private static final String OWNERSHIP = "BYOD";
private List<DeviceIdentifier> deviceIds = new ArrayList<>(); private List<DeviceIdentifier> deviceIds = new ArrayList<>();
private OperationManager operationMgtService; private OperationManager operationMgtService;
@ -124,6 +125,7 @@ public class OperationManagementNoDBSchemaTests extends BaseDeviceManagementTest
PaginationRequest request = new PaginationRequest(1, 2); PaginationRequest request = new PaginationRequest(1, 2);
request.setDeviceType(DEVICE_TYPE); request.setDeviceType(DEVICE_TYPE);
request.setOwner(ADMIN_USER); request.setOwner(ADMIN_USER);
request.setOwnership(OWNERSHIP);
for (DeviceIdentifier deviceIdentifier : deviceIds) { for (DeviceIdentifier deviceIdentifier : deviceIds) {
this.operationMgtService.getOperations(deviceIdentifier, request); this.operationMgtService.getOperations(deviceIdentifier, request);
} }

@ -75,6 +75,7 @@ public class OperationManagementTests extends BaseDeviceManagementTest {
private static final String ADMIN_USER = "admin"; private static final String ADMIN_USER = "admin";
private static final String NON_ADMIN_USER = "test"; private static final String NON_ADMIN_USER = "test";
private static final String INVALID_DEVICE = "ThisIsInvalid"; private static final String INVALID_DEVICE = "ThisIsInvalid";
private static final String OWNERSHIP = "BYOD";
private List<DeviceIdentifier> deviceIds = new ArrayList<>(); private List<DeviceIdentifier> deviceIds = new ArrayList<>();
private OperationManager operationMgtService; private OperationManager operationMgtService;
@ -286,6 +287,7 @@ public class OperationManagementTests extends BaseDeviceManagementTest {
PaginationRequest request = new PaginationRequest(1, 2); PaginationRequest request = new PaginationRequest(1, 2);
request.setDeviceType(DEVICE_TYPE); request.setDeviceType(DEVICE_TYPE);
request.setOwner(ADMIN_USER); request.setOwner(ADMIN_USER);
request.setOwnership(OWNERSHIP);
for (DeviceIdentifier deviceIdentifier : deviceIds) { for (DeviceIdentifier deviceIdentifier : deviceIds) {
PaginationResult result = this.operationMgtService.getOperations(deviceIdentifier, request); PaginationResult result = this.operationMgtService.getOperations(deviceIdentifier, request);
Assert.assertEquals(result.getRecordsFiltered(), 4); Assert.assertEquals(result.getRecordsFiltered(), 4);
@ -302,6 +304,7 @@ public class OperationManagementTests extends BaseDeviceManagementTest {
PaginationRequest request = new PaginationRequest(1, 2); PaginationRequest request = new PaginationRequest(1, 2);
request.setDeviceType(DEVICE_TYPE); request.setDeviceType(DEVICE_TYPE);
request.setOwner(ADMIN_USER); request.setOwner(ADMIN_USER);
request.setOwnership(OWNERSHIP);
for (DeviceIdentifier deviceIdentifier : deviceIds) { for (DeviceIdentifier deviceIdentifier : deviceIds) {
try { try {
this.operationMgtService.getOperations(deviceIdentifier, request); this.operationMgtService.getOperations(deviceIdentifier, request);
@ -540,6 +543,7 @@ public class OperationManagementTests extends BaseDeviceManagementTest {
PaginationRequest request = new PaginationRequest(1, 2); PaginationRequest request = new PaginationRequest(1, 2);
request.setDeviceType(DEVICE_TYPE); request.setDeviceType(DEVICE_TYPE);
request.setOwner(ADMIN_USER); request.setOwner(ADMIN_USER);
request.setOwnership(OWNERSHIP);
PaginationResult result = this.operationMgtService.getOperations PaginationResult result = this.operationMgtService.getOperations
(new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE), request); (new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE), request);
Assert.assertEquals(result.getRecordsFiltered(), 4); Assert.assertEquals(result.getRecordsFiltered(), 4);

@ -29,12 +29,14 @@ if (uriMatcher.match("/{context}/api/operation/paginate")) {
var deviceType = request.getParameter("deviceType"); var deviceType = request.getParameter("deviceType");
var deviceId = request.getParameter("deviceId"); var deviceId = request.getParameter("deviceId");
var owner = request.getParameter("owner"); var owner = request.getParameter("owner");
var ownership = request.getParameter("ownership");
var index = request.getParameter("start"); var index = request.getParameter("start");
var length = request.getParameter("length"); var length = request.getParameter("length");
var search = request.getParameter("search[value]"); var search = request.getParameter("search[value]");
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/devices/" + deviceType + "/" + deviceId + "/operations?owner=" + owner + "&offset=" + index + "&limit=" + length; "/devices/" + deviceType + "/" + deviceId + "/operations?owner=" + owner + "&ownership=" + ownership +
"&offset=" + index + "&limit=" + length;
serviceInvokers.XMLHttp.get( serviceInvokers.XMLHttp.get(
restAPIEndpoint, restAPIEndpoint,

@ -63,7 +63,7 @@ deviceModule = function () {
/* /*
@Updated @Updated
*/ */
publicMethods.viewDevice = function (deviceType, deviceId, owner) { publicMethods.viewDevice = function (deviceType, deviceId, owner, ownership) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
@ -115,6 +115,11 @@ deviceModule = function () {
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId; var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId;
if (owner) { if (owner) {
url = url + "?owner=" + owner; url = url + "?owner=" + owner;
if (ownership){
url = url + "&ownership=" + ownership;
}
} else if (ownership){
url = url + "?ownership=" + ownership;
} }
return serviceInvokers.XMLHttp.get( return serviceInvokers.XMLHttp.get(
url, url,

@ -342,7 +342,8 @@ function loadDevices(searchType, searchParam) {
data: 'ownership', data: 'ownership',
class: 'remove-padding-top viewEnabledIcon', class: 'remove-padding-top viewEnabledIcon',
render: function (status, type, row, meta) { render: function (status, type, row, meta) {
if (getDeviceTypeCategory(row.deviceType) == 'mobile') { if (getDeviceTypeCategory(row.deviceType) === 'mobile'
|| getDeviceTypeCategory(row.deviceType) === 'hybrid') {
return row.ownership; return row.ownership;
} else { } else {
return null; return null;
@ -422,17 +423,6 @@ function loadDevices(searchType, searchParam) {
]; ];
var fnCreatedRow = function (row, data, dataIndex) { var fnCreatedRow = function (row, data, dataIndex) {
if(data.status != "REMOVED"){
$(row).attr('data-type', 'selectable');
}else{
$(row).attr('data-type', 'non-selectable');
}
$(row).attr('data-deviceid', htmlspecialchars(data.deviceIdentifier));
$(row).attr('data-devicetype', htmlspecialchars(data.deviceType));
$(row).attr('data-url', context + '/device/' + htmlspecialchars(data.deviceType) + '?id='
+ htmlspecialchars(data.deviceIdentifier) + '&owner=' + htmlspecialchars(data.userPattern)) ;
var model = htmlspecialchars(getPropertyValue(data.properties, 'DEVICE_MODEL')); var model = htmlspecialchars(getPropertyValue(data.properties, 'DEVICE_MODEL'));
var vendor = htmlspecialchars(getPropertyValue(data.properties, 'VENDOR')); var vendor = htmlspecialchars(getPropertyValue(data.properties, 'VENDOR'));
var owner = htmlspecialchars(data.userPattern); var owner = htmlspecialchars(data.userPattern);
@ -440,6 +430,10 @@ function loadDevices(searchType, searchParam) {
var ownership = htmlspecialchars(data.ownership); var ownership = htmlspecialchars(data.ownership);
var deviceType = htmlspecialchars(data.deviceType); var deviceType = htmlspecialchars(data.deviceType);
var category = getDeviceTypeCategory(deviceType); var category = getDeviceTypeCategory(deviceType);
$(row).attr('data-deviceid', htmlspecialchars(data.deviceIdentifier));
$(row).attr('data-devicetype', deviceType);
$(row).attr('data-url', context + '/device/' + htmlspecialchars(data.deviceType) + '?id='
+ htmlspecialchars(data.deviceIdentifier) + '&owner=' + owner + '&ownership=' + ownership) ;
$.each($('td', row), function (colIndex) { $.each($('td', row), function (colIndex) {
switch (colIndex) { switch (colIndex) {
case 1: case 1:
@ -462,7 +456,7 @@ function loadDevices(searchType, searchParam) {
$(this).attr('data-display', getDeviceTypeLabel(deviceType)); $(this).attr('data-display', getDeviceTypeLabel(deviceType));
break; break;
case 5: case 5:
if (category == 'mobile') { if (category === 'mobile' || category === 'hybrid') {
$(this).attr('data-grid-label', "Ownership"); $(this).attr('data-grid-label', "Ownership");
$(this).attr('data-search', ownership); $(this).attr('data-search', ownership);
$(this).attr('data-display', ownership); $(this).attr('data-display', ownership);

@ -24,6 +24,7 @@ function onRequest(context) {
var deviceType = context.uriParams.deviceType; var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id"); var deviceId = request.getParameter("id");
var owner = request.getParameter("owner"); var owner = request.getParameter("owner");
var ownership = request.getParameter("ownership");
var attributes = []; var attributes = [];
var featureList = []; var featureList = [];
var user = userModule.getCarbonUser(); var user = userModule.getCarbonUser();
@ -130,10 +131,10 @@ function onRequest(context) {
displayData.tenantDomain = tenantDomain; displayData.tenantDomain = tenantDomain;
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType && deviceId) {
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId, owner); var device = deviceModule.viewDevice(deviceType, deviceId, owner, ownership);
if (device && device.status != "error") { if (device && device.status !== "error") {
displayData.device = device.content; displayData.device = device.content;
displayData.autoCompleteParams = autoCompleteParams; displayData.autoCompleteParams = autoCompleteParams;
displayData.encodedFeaturePayloads = ""; displayData.encodedFeaturePayloads = "";

@ -20,6 +20,7 @@ var deviceId = $(".device-id");
var deviceIdentifier = deviceId.data("deviceid"); var deviceIdentifier = deviceId.data("deviceid");
var deviceType = deviceId.data("type"); var deviceType = deviceId.data("type");
var deviceOwner = deviceId.data("owner"); var deviceOwner = deviceId.data("owner");
var deviceOwnership = deviceId.data("ownership");
$(document).ready(function() { $(document).ready(function() {
$(".panel-body").removeClass("hidden"); $(".panel-body").removeClass("hidden");
@ -86,7 +87,8 @@ function loadOperationsLog(update) {
data: { data: {
deviceId: deviceIdentifier, deviceId: deviceIdentifier,
deviceType: deviceType, deviceType: deviceType,
owner: deviceOwner owner: deviceOwner,
ownership: deviceOwnership
}, },
dataSrc: function(json) { dataSrc: function(json) {
$("#operations-spinner").addClass("hidden"); $("#operations-spinner").addClass("hidden");

@ -21,10 +21,11 @@ function onRequest(context) {
var deviceType = context["uriParams"]["deviceType"]; var deviceType = context["uriParams"]["deviceType"];
var deviceId = request.getParameter("id"); var deviceId = request.getParameter("id");
var owner = request.getParameter("owner"); var owner = request.getParameter("owner");
var ownership = request.getParameter("ownership");
var deviceViewData = {}; var deviceViewData = {};
if (deviceType && deviceId) { if (deviceType && deviceId) {
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var response = deviceModule.viewDevice(deviceType, deviceId, owner); var response = deviceModule.viewDevice(deviceType, deviceId, owner, ownership);
if (response["status"] == "success") { if (response["status"] == "success") {
deviceViewData["deviceFound"] = true; deviceViewData["deviceFound"] = true;
deviceViewData["isAuthorized"] = true; deviceViewData["isAuthorized"] = true;

@ -458,6 +458,8 @@ var savePolicy = function (policy, isActive, serviceURL) {
payload["deviceGroups"] = policy["selectedGroups"]; payload["deviceGroups"] = policy["selectedGroups"];
} }
payload["policyType"] = "GENERAL";
invokerUtil.post( invokerUtil.post(
serviceURL, serviceURL,
payload, payload,

@ -155,4 +155,11 @@ public interface PolicyAdministratorPoint {
List<Profile> getProfiles() throws PolicyManagementException; List<Profile> getProfiles() throws PolicyManagementException;
int getPolicyCount() throws PolicyManagementException; int getPolicyCount() throws PolicyManagementException;
/**
* @param policyType type of the policy
* @return policy list of the specific type
* @throws PolicyManagementException
*/
List<Policy> getPolicies(String policyType) throws PolicyManagementException;
} }

@ -113,4 +113,13 @@ public interface PolicyCacheManager {
* @return - Id of the policy. * @return - Id of the policy.
*/ */
int getPolicyIdOfDevice(int deviceId); int getPolicyIdOfDevice(int deviceId);
/**
* This method will return the all policies belongs to the specific type.
*
* @param policyType - type of the policy
* @return - list of policies
* @throws PolicyManagementException
*/
List<Policy> getAllPolicies(String policyType) throws PolicyManagementException;
} }

@ -30,6 +30,7 @@ import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import javax.cache.Cache; import javax.cache.Cache;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -74,31 +75,13 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
@Override @Override
public List<Policy> getAllPolicies() throws PolicyManagementException { public List<Policy> getAllPolicies() throws PolicyManagementException {
Cache<Integer, List<Policy>> lCache = getPolicyListCache(); Cache<Integer, List<Policy>> lCache = getPolicyListCache();
if (!lCache.containsKey(1)) { updateCache(lCache);
PolicyManager policyManager = new PolicyManagerImpl();
this.addAllPolicies(policyManager.getPolicies());
}
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
List<Policy> cachedPolicy = lCache.get(1); showDebugLog(lCache);
for (Policy policy : cachedPolicy) {
log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy.
getPolicyName() + " Activated : " + policy.isActive());
List<String> users = policy.getUsers();
for (String user : users) {
log.debug("Users in cached policy : " + user);
}
List<String> roles = policy.getRoles();
for (String role : roles) {
log.debug("Roles in cached policy : " + role);
}
}
} }
lCache = getPolicyListCache();
return lCache.get(1); return lCache.get(1);
} }
@Override @Override
@ -218,4 +201,47 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
return 0; return 0;
} }
@Override
public List<Policy> getAllPolicies(String policyType) throws PolicyManagementException {
Cache<Integer, List<Policy>> lCache = getPolicyListCache();
updateCache(lCache);
if (log.isDebugEnabled()) {
showDebugLog(lCache);
}
lCache = getPolicyListCache();
List<Policy> policyListByType = new ArrayList<>();
List<Policy> cachedPolicyList = lCache.get(1);
Iterator<Policy> iterator = cachedPolicyList.iterator();
while (iterator.hasNext()) {
Policy policy = iterator.next();
if (policy.getPolicyType().equals(policyType)) {
policyListByType.add(policy);
}
}
return policyListByType;
}
private void updateCache(Cache<Integer, List<Policy>> lCache) throws PolicyManagementException {
if (!lCache.containsKey(1)) {
PolicyManager policyManager = new PolicyManagerImpl();
this.addAllPolicies(policyManager.getPolicies());
}
}
private void showDebugLog(Cache<Integer, List<Policy>> lCache) {
List<Policy> cachedPolicy = lCache.get(1);
for (Policy policy : cachedPolicy) {
log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy.
getPolicyName() + " Activated : " + policy.isActive());
List<String> users = policy.getUsers();
for (String user : users) {
log.debug("Users in cached policy : " + user);
}
List<String> roles = policy.getRoles();
for (String role : roles) {
log.debug("Roles in cached policy : " + role);
}
}
}
} }

@ -150,4 +150,6 @@ public interface PolicyDAO {
HashMap<Integer, Integer> getAppliedPolicyIds() throws PolicyManagerDAOException; HashMap<Integer, Integer> getAppliedPolicyIds() throws PolicyManagerDAOException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException; HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException;
List<Policy> getAllPolicies(String policyType) throws PolicyManagerDAOException;
} }

@ -979,21 +979,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
while (resultSet.next()) { return this.extractPolicyListFromDbResult(resultSet, tenantId);
Policy policy = new Policy();
policy.setId(resultSet.getInt("ID"));
policy.setProfileId(resultSet.getInt("PROFILE_ID"));
policy.setPolicyName(resultSet.getString("NAME"));
policy.setTenantId(tenantId);
policy.setPriorityId(resultSet.getInt("PRIORITY"));
policy.setCompliance(resultSet.getString("COMPLIANCE"));
policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policies.add(policy);
}
return policies;
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while reading the policies from the database", e); throw new PolicyManagerDAOException("Error occurred while reading the policies from the database", e);
} finally { } finally {
@ -1437,7 +1423,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," + String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," +
"UPDATED, ACTIVE, DESCRIPTION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; "UPDATED, ACTIVE, DESCRIPTION, POLICY_TYPE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, new String[]{"id"}); stmt = conn.prepareStatement(query, new String[]{"id"});
stmt.setString(1, policy.getPolicyName()); stmt.setString(1, policy.getPolicyName());
@ -1449,6 +1435,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(7, 0); stmt.setInt(7, 0);
stmt.setInt(8, 0); stmt.setInt(8, 0);
stmt.setString(9, policy.getDescription()); stmt.setString(9, policy.getDescription());
stmt.setString(10, policy.getPolicyType());
int affectedRows = stmt.executeUpdate(); int affectedRows = stmt.executeUpdate();
@ -1704,4 +1691,57 @@ public class PolicyDAOImpl implements PolicyDAO {
return devicePolicyIds; return devicePolicyIds;
} }
@Override
public List<Policy> getAllPolicies(String policyType) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT ID, " +
"PROFILE_ID, " +
"NAME, " +
"PRIORITY, " +
"COMPLIANCE, " +
"OWNERSHIP_TYPE, " +
"UPDATED, " +
"ACTIVE, " +
"DESCRIPTION, " +
"POLICY_TYPE "+
"FROM DM_POLICY WHERE TENANT_ID = ? AND POLICY_TYPE = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
stmt.setString(2, policyType);
resultSet = stmt.executeQuery();
return this.extractPolicyListFromDbResult(resultSet, tenantId);
} catch (SQLException e) {
String msg = "Error occurred while reading the policies from the database ";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
private List<Policy> extractPolicyListFromDbResult(ResultSet resultSet, int tenantId) throws SQLException {
List<Policy> policies = new ArrayList<>();
while (resultSet.next()) {
Policy policy = new Policy();
policy.setId(resultSet.getInt("ID"));
policy.setProfileId(resultSet.getInt("PROFILE_ID"));
policy.setPolicyName(resultSet.getString("NAME"));
policy.setTenantId(tenantId);
policy.setPriorityId(resultSet.getInt("PRIORITY"));
policy.setCompliance(resultSet.getString("COMPLIANCE"));
policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policy.setPolicyType(resultSet.getString("POLICY_TYPE"));
policies.add(policy);
}
return policies;
}
} }

@ -377,4 +377,12 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
} }
} }
@Override
public List<Policy> getPolicies(String policyType) throws PolicyManagementException {
if (policyConfiguration.getCacheEnable()) {
return PolicyCacheManagerImpl.getInstance().getAllPolicies(policyType);
} else {
return policyManager.getPolicies(policyType);
}
}
} }

@ -83,4 +83,6 @@ public interface PolicyManager {
Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException; HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException;
List<Policy> getPolicies(String type) throws PolicyManagementException;
} }

@ -626,25 +626,7 @@ public class PolicyManagerImpl implements PolicyManager {
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
policyList = policyDAO.getAllPolicies(); policyList = policyDAO.getAllPolicies();
this.buildPolicyList(policyList, profileList);
for (Policy policy : policyList) {
for (Profile profile : profileList) {
if (policy.getProfileId() == profile.getProfileId()) {
policy.setProfile(profile);
}
}
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId()));
List<DeviceGroupWrapper> deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId());
if (!deviceGroupWrappers.isEmpty()) {
deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers);
}
policy.setDeviceGroups(deviceGroupWrappers);
}
Collections.sort(policyList);
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting all the policies.", e); throw new PolicyManagementException("Error occurred while getting all the policies.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -1144,4 +1126,60 @@ public class PolicyManagerImpl implements PolicyManager {
return policyRevokeOperation; return policyRevokeOperation;
} }
@Override
public List<Policy> getPolicies(String type) throws PolicyManagementException {
List<Policy> policyList;
List<Profile> profileList;
try {
profileList = profileManager.getAllProfiles();
} catch (ProfileManagementException e) {
throw new PolicyManagementException("Error occurred while getting all the profiles.", e);
}
try {
PolicyManagementDAOFactory.openConnection();
policyList = policyDAO.getAllPolicies(type);
this.buildPolicyList(policyList, profileList);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while getting all the policies. ";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source ";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (GroupManagementException e) {
String msg = "Error occurred while getting device groups. ";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
for (Policy policy : policyList) {
policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId()));
}
return policyList;
}
private void buildPolicyList(List<Policy> policyList, List<Profile> profileList)
throws PolicyManagerDAOException, GroupManagementException {
for (Policy policy : policyList) {
for (Profile profile : profileList) {
if (policy.getProfileId() == profile.getProfileId()) {
policy.setProfile(profile);
}
}
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId()));
List<DeviceGroupWrapper> deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId());
if (!deviceGroupWrappers.isEmpty()) {
deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers);
}
policy.setDeviceGroups(deviceGroupWrappers);
}
Collections.sort(policyList);
}
} }

@ -132,6 +132,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest {
policy1.setDeviceGroups(deviceGroupWrappers); policy1.setDeviceGroups(deviceGroupWrappers);
List<Device> devices = new ArrayList<Device>(); List<Device> devices = new ArrayList<Device>();
policy1.setDevices(devices); policy1.setDevices(devices);
policy1.setPolicyType("GENERAL");
policy1.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); policy1.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
policy1 = policyManagerService.addPolicy(policy1); policy1 = policyManagerService.addPolicy(policy1);

@ -40,6 +40,7 @@ public class PolicyCreator {
policy.setCompliance("NOTIFY"); policy.setCompliance("NOTIFY");
policy.setOwnershipType("COPE"); policy.setOwnershipType("COPE");
policy.setDescription("This is the first policy."); policy.setDescription("This is the first policy.");
policy.setPolicyType("GENERAL");
return policy; return policy;
} }
@ -51,6 +52,7 @@ public class PolicyCreator {
policy.setPolicyName("Test_Policy_02"); policy.setPolicyName("Test_Policy_02");
policy.setGeneric(true); policy.setGeneric(true);
policy.setProfile(profile); policy.setProfile(profile);
policy.setPolicyType("GENERAL");
policy.setDevices(DeviceCreator.getDeviceList2(DeviceTypeCreator.getDeviceType())); policy.setDevices(DeviceCreator.getDeviceList2(DeviceTypeCreator.getDeviceType()));
policy.setCompliance("ENFORCE"); policy.setCompliance("ENFORCE");
@ -110,7 +112,7 @@ public class PolicyCreator {
policy.setRoles(roles); policy.setRoles(roles);
policy.setCompliance("ENFORCE"); policy.setCompliance("ENFORCE");
policy.setOwnershipType("BYOD"); policy.setOwnershipType("BYOD");
policy.setPolicyType("GENERAL");
PolicyCriterion criterion = new PolicyCriterion(); PolicyCriterion criterion = new PolicyCriterion();
@ -144,7 +146,7 @@ public class PolicyCreator {
policy.setCompliance("MONITOR"); policy.setCompliance("MONITOR");
policy.setOwnershipType("BYOD"); policy.setOwnershipType("BYOD");
policy.setPolicyType("GENERAL");
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
roles.add("Role_04"); roles.add("Role_04");
roles.add("Role_05"); roles.add("Role_05");

@ -200,6 +200,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INT NOT NULL, PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL, ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL, UPDATED INT(1) NULL,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )

@ -193,6 +193,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INT NOT NULL, PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL, ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL, UPDATED INT(1) NULL,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )

@ -246,6 +246,7 @@ CREATE TABLE DM_POLICY (
PRIORITY INTEGER NOT NULL, PRIORITY INTEGER NOT NULL,
ACTIVE BIT NOT NULL DEFAULT 0, ACTIVE BIT NOT NULL DEFAULT 0,
UPDATED BIT NULL DEFAULT 0, UPDATED BIT NULL DEFAULT 0,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID) REFERENCES DM_PROFILE (ID) CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID) REFERENCES DM_PROFILE (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION ON DELETE NO ACTION ON UPDATE NO ACTION

@ -224,6 +224,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INT NOT NULL, PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL, ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL, UPDATED INT(1) NULL,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )

@ -357,6 +357,7 @@ CREATE TABLE DM_POLICY (
PRIORITY NUMBER(10) NOT NULL, PRIORITY NUMBER(10) NOT NULL,
ACTIVE NUMBER(10) NOT NULL, ACTIVE NUMBER(10) NOT NULL,
UPDATED NUMBER(10) NULL, UPDATED NUMBER(10) NULL,
POLICY_TYPE VARCHAR2(45) NULL,
CONSTRAINT PK_DM_PROFILE_DM_POLICY PRIMARY KEY (ID) , CONSTRAINT PK_DM_PROFILE_DM_POLICY PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )

@ -194,6 +194,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INTEGER NOT NULL, PRIORITY INTEGER NOT NULL,
ACTIVE INTEGER NOT NULL, ACTIVE INTEGER NOT NULL,
UPDATED INTEGER NULL, UPDATED INTEGER NULL,
POLICY_TYPE VARCHAR(45) NULL,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )
REFERENCES DM_PROFILE (ID ) REFERENCES DM_PROFILE (ID )

Loading…
Cancel
Save