Merge branch 'support-4.1.15' into 'support-4.1.15'

Sync with master fixes

See merge request entgra-support/support-carbon-device-mgt!51
4.x.x
Inosh Perara 4 years ago
commit 14e5ceb5f2

@ -22,6 +22,7 @@ import org.wso2.carbon.device.application.mgt.common.dto.ScheduledSubscriptionDT
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.SubscriptionManagementException;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.List;
@ -127,14 +128,11 @@ public interface SubscriptionManager {
* This method used to get the app id ,device ids and pass them to DM service method.
*
* @param appUUID UUID of the application release.
* @param offsetValue offset value for get paginated request.
* @param limitValue limit value for get paginated request.
* @param status status of the devices.
* @param request paginated request object.
* @return deviceDetails - device details for given application release.
* @throws {@link ApplicationManagementException} Exception of the application management
*/
PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID,
List<String> status) throws ApplicationManagementException;
PaginationResult getAppInstalledDevices(PaginationRequest request, String appUUID) throws ApplicationManagementException;
/***
* This method used to get category details.
@ -152,14 +150,15 @@ public interface SubscriptionManager {
/**
* This method is responsible to provide application subscription data for given application release UUID.
*
* @param offsetValue offset
* @param limitValue limit
* @param request paginated request object.
* @param actionStatus status of the operation.
* @param action action related to the device.
* @param appUUID application release UUID
* @return {@link PaginationResult}
* @throws ApplicationManagementException if offset or limit contains incorrect values, if it couldn't find an
* application release for given UUID, if an error occurred while getting device details of subscribed device ids,
* if an error occurred while getting subscription details of given application release UUID.
*/
PaginationResult getAppSubscriptionDetails(int offsetValue, int limitValue, String appUUID)
PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action)
throws ApplicationManagementException;
}

@ -81,7 +81,7 @@ public interface SubscriptionDAO {
void addGroupSubscriptions(int tenantId, String subscribedBy, List<String> groups, int releaseId, String action)
throws ApplicationManagementDAOException;
List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId) throws
List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId, String actionStatus, String action) throws
ApplicationManagementDAOException;
Map<Integer, DeviceSubscriptionDTO> getDeviceSubscriptions(List<Integer> deviceIds, int appReleaseId, int tenantId)

@ -332,12 +332,15 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
@Override
public List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId) throws
public List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId, String actionStatus, String action) throws
ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId
+ " from the database");
}
boolean isActionStatusProvided = false;
boolean isActionProvided = false;
int index = 1;
String sql = "SELECT "
+ "DS.ID AS ID, "
+ "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
@ -350,11 +353,30 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.TENANT_ID=?";
if (actionStatus != null && !actionStatus.isEmpty()) {
sql += " AND DS.STATUS= ?";
isActionStatusProvided = true;
}
if (action != null && !action.isEmpty()) {
sql += " AND DS.UNSUBSCRIBED= ?";
isActionProvided = true;
}
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, appReleaseId);
stmt.setInt(2, tenantId);
stmt.setInt(index++, appReleaseId);
stmt.setInt(index++, tenantId);
if (isActionStatusProvided) {
stmt.setString(index++, actionStatus);
}
if (isActionProvided) {
if (action.equals("SUBSCRIBED")) {
stmt.setString(index, "FALSE");
} else {
stmt.setString(index, "TRUE");
}
}
try (ResultSet rs = stmt.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
@ -1037,7 +1059,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, ExecutionStatus.PENDING.toString());
stmt.setBoolean(2, false);
stmt.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime()));
stmt.setLong(3, Calendar.getInstance().getTime().getTime() / 1000);
try (ResultSet rs = stmt.executeQuery()) {
return DAOUtil.loadScheduledSubscriptions(rs);
}

@ -1445,7 +1445,7 @@ ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new ForbiddenException(msg);
}
if (!subscriptionDAO.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId).isEmpty()) {
if (!subscriptionDAO.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null).isEmpty()) {
String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid()
+ " either subscribed to device/s or it had subscribed to device/s. Therefore you are not "
+ "permitted to delete the application release.";
@ -1580,7 +1580,7 @@ ApplicationManagerImpl implements ApplicationManager {
try {
ConnectionManagerUtil.beginDBTransaction();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId);
.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null);
if (!deviceSubscriptionDTOS.isEmpty()) {
String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid()
+ " either subscribed to device/s or it had subscribed to device/s. Therefore you "

@ -65,10 +65,7 @@ import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.application.mgt.core.util.OAuthUtils;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.MDMAppConstants;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.App;
import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes;
import org.wso2.carbon.device.mgt.common.app.mgt.android.CustomApplication;
@ -88,7 +85,6 @@ import org.wso2.carbon.device.mgt.core.util.MDMIOSOperationUtil;
import org.wso2.carbon.device.mgt.core.util.MDMWindowsOperationUtil;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
@ -381,7 +377,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
if (applicationDTO != null) {
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = this.subscriptionDAO
.getDeviceSubscriptions(applicationDTO.getApplicationReleaseDTOs().get(0).getId(),
tenantId);
tenantId, null, null);
AtomicBoolean isAppSubscribable = new AtomicBoolean(true);
for (DeviceSubscriptionDTO deviceSubscriptionDTO : deviceSubscriptionDTOS) {
@ -1223,7 +1219,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
}
@Override
public PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, List<String> status)
public PaginationResult getAppInstalledDevices(PaginationRequest request, String appUUID)
throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
DeviceManagementProviderService deviceManagementProviderService = HelperUtil
@ -1235,7 +1231,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseId, tenantId);
.getDeviceSubscriptions(applicationReleaseId, tenantId, null, null);
if (deviceSubscriptionDTOS.isEmpty()) {
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(new ArrayList<>());
@ -1262,8 +1258,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
}
//pass the device id list to device manager service method
try {
PaginationResult deviceDetails = deviceManagementProviderService
.getAppSubscribedDevices(offsetValue, limitValue, deviceIdList, status);
PaginationResult deviceDetails = deviceManagementProviderService.getAppSubscribedDevices
(request, deviceIdList);
if (deviceDetails == null) {
String msg = "Couldn't found an subscribed devices details for device ids: " + deviceIdList;
@ -1342,8 +1338,10 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
}
@Override
public PaginationResult getAppSubscriptionDetails(int offsetValue, int limitValue, String appUUID)
throws ApplicationManagementException {
public PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus,
String action) throws ApplicationManagementException {
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
DeviceManagementProviderService deviceManagementProviderService = HelperUtil
.getDeviceManagementProviderService();
@ -1365,7 +1363,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseId, tenantId);
.getDeviceSubscriptions(applicationReleaseId, tenantId, actionStatus, action);
if (deviceSubscriptionDTOS.isEmpty()) {
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(new ArrayList<>());
@ -1377,8 +1375,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
.collect(Collectors.toList());
try {
//pass the device id list to device manager service method
PaginationResult paginationResult = deviceManagementProviderService
.getAppSubscribedDevices(offsetValue, limitValue, deviceIdList, null);
PaginationResult paginationResult = deviceManagementProviderService.getAppSubscribedDevices
(request, deviceIdList);
List<DeviceSubscriptionData> deviceSubscriptionDataList = new ArrayList<>();
if (!paginationResult.getData().isEmpty()) {

@ -32,6 +32,7 @@ import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
@ -337,6 +338,28 @@ public interface SubscriptionManagementAPI {
response = ErrorResponse.class)
})
Response getAppInstalledDevices(
@ApiParam(
name = "name",
value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.",
required = false)
@Size(max = 45)
String name,
@ApiParam(
name = "user",
value = "The username of the owner of the device.",
required = false)
@QueryParam("user")
String user,
@ApiParam(
name = "ownership",
allowableValues = "BYOD, COPE",
value = "Provide the ownership status of the device. The following values can be assigned:\n" +
"- BYOD: Bring Your Own Device\n" +
"- COPE: Corporate-Owned, Personally-Enabled",
required = false)
@QueryParam("ownership")
@Size(max = 45)
String ownership,
@ApiParam(
name="uuid",
value="uuid of the application release.",

@ -31,6 +31,7 @@ import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@ -111,6 +112,32 @@ public interface SubscriptionManagementAdminAPI {
response = ErrorResponse.class)
})
Response getAppInstalledDevices(
@ApiParam(
name = "name",
value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.",
required = false)
@Size(max = 45)
String name,
@ApiParam(
name = "user",
value = "The username of the owner of the device.",
required = false)
@QueryParam("user")
String user,
@ApiParam(
name = "action",
value = "The action, subscribed or unsubscribed.",
required = false)
@Size(max = 45)
@QueryParam("action") String action,
@ApiParam(
name = "actionStatus",
value = "Provide the action status details")
@QueryParam("actionStatus") String actionStatus,
@ApiParam(
name = "status",
value = "Provide the device status details, such as active or inactive.")
@QueryParam("status") List<String> status,
@ApiParam(
name = "uuid",
value = "uuid of the application release.",

@ -33,6 +33,8 @@ import org.wso2.carbon.device.application.mgt.common.BasicUserInfo;
import org.wso2.carbon.device.application.mgt.common.BasicUserInfoList;
import org.wso2.carbon.device.application.mgt.common.RoleList;
import org.wso2.carbon.device.application.mgt.common.DeviceGroupList;
import org.wso2.carbon.device.application.mgt.store.api.services.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
@ -273,6 +275,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@Produces("application/json")
@Path("/{uuid}/devices")
public Response getAppInstalledDevices(
@QueryParam("name") String name,
@QueryParam("user") String user,
@QueryParam("ownership") String ownership,
@PathParam("uuid") String uuid,
@DefaultValue("0")
@QueryParam("offset") int offset,
@ -281,8 +286,31 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@QueryParam("status") List<String> status) {
try {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
PaginationResult subscribedDeviceDetails = subscriptionManager
.getAppInstalledDevices(offset, limit, uuid, status);
PaginationRequest request = new PaginationRequest(offset, limit);
if (name != null && !name.isEmpty()) {
request.setDeviceName(name);
}
if (user != null && !user.isEmpty()) {
request.setOwner(user);
}
if (ownership != null && !ownership.isEmpty()) {
RequestValidationUtil.validateOwnershipType(ownership);
request.setOwnership(ownership);
}
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status) {
if (StringUtils.isNotBlank(statusString)) {
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status);
}
}
PaginationResult subscribedDeviceDetails = subscriptionManager.getAppInstalledDevices(request, uuid);
DeviceList devices = new DeviceList();
devices.setList((List<Device>) subscribedDeviceDetails.getData());
devices.setCount(subscribedDeviceDetails.getRecordsTotal());
@ -292,8 +320,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload for getting application which has UUID: " + uuid
+ ". Hence verify the payload";
String msg = "User requested details are not valid";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {

@ -18,6 +18,7 @@
package org.wso2.carbon.device.application.mgt.store.api.services.impl.admin;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
@ -26,6 +27,8 @@ import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.store.api.services.admin.SubscriptionManagementAdminAPI;
import org.wso2.carbon.device.application.mgt.store.api.services.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import javax.ws.rs.Consumes;
@ -36,6 +39,7 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Implementation of Subscription Management related APIs.
@ -51,6 +55,11 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen
@Produces("application/json")
@Path("/{uuid}")
public Response getAppInstalledDevices(
@QueryParam("name") String name,
@QueryParam("user") String user,
@QueryParam("action") String action,
@QueryParam("actionStatus") String actionStatus,
@QueryParam("status") List<String> status,
@PathParam("uuid") String uuid,
@DefaultValue("0")
@QueryParam("offset") int offset,
@ -58,17 +67,44 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen
@QueryParam("limit") int limit) {
try {
PaginationRequest request = new PaginationRequest(offset, limit);
if (name != null && !name.isEmpty()) {
request.setDeviceName(name);
}
if (user != null && !user.isEmpty()) {
request.setOwner(user);
}
if (action != null && !action.isEmpty()) {
RequestValidationUtil.validateAction(action);
}
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status) {
if (StringUtils.isNotBlank(statusString)) {
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status);
}
}
if (actionStatus != null && !actionStatus.isEmpty()) {
if (StringUtils.isNotBlank(actionStatus)) {
RequestValidationUtil.validateStatusFiltering(actionStatus);
}
}
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
PaginationResult subscriptionData = subscriptionManager
.getAppSubscriptionDetails(offset, limit, uuid);
PaginationResult subscriptionData = subscriptionManager.getAppSubscriptionDetails
(request, uuid, actionStatus, action);
return Response.status(Response.Status.OK).entity(subscriptionData).build();
} catch (NotFoundException e) {
String msg = "Application with application release UUID: " + uuid + " is not found";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload for getting application which has UUID: " + uuid
+ ". Hence verify the payload";
String msg = "User requested details are not valid";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {

@ -0,0 +1,116 @@
/*
* Copyright (c) 2021, 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.application.mgt.store.api.services.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.store.api.util.Constants;
import java.util.List;
public class RequestValidationUtil {
private static final Log log = LogFactory.getLog(RequestValidationUtil.class);
/**
* Checks if user requested status codes are valid.
*
* @param statusList status codes upon to filter operation logs using status
*/
public static void validateStatus(List<String> statusList) throws BadRequestException {
for (String status : statusList) {
switch (status) {
case "ACTIVE":
case "INACTIVE":
case "UNCLAIMED":
case "UNREACHABLE":
case "SUSPENDED":
case "DISENROLLMENT_REQUESTED":
case "REMOVED":
case "BLOCKED":
case "CREATED":
break;
default:
String msg = "Invalid enrollment status type: " + status + ". \nValid status types " +
"are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE | SUSPENDED | " +
"DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED";
log.error(msg);
throw new BadRequestException(msg);
}
}
}
/**
* Checks if user requested action is valid.
*
* @param action action upon to filter devices using action
*/
public static void validateAction(String action) throws BadRequestException {
if (action.equals("SUBSCRIBED") || action.equals("UNSUBSCRIBED")) {
} else {
String msg = "Invalid action type received.Valid action types are SUBSCRIBED | UNSUBSCRIBED";
log.error(msg);
throw new BadRequestException(msg);
}
}
/**
* Checks if user requested ownerships are valid.
*
* @param ownership ownerships upon to filter devices using ownership
*/
public static void validateOwnershipType(String ownership) throws BadRequestException {
switch (ownership) {
case "BYOD":
case "COPE":
case "WORK_PROFILE":
case "GOOGLE_ENTERPRISE":
case "COSU":
case "FULLY_MANAGED":
case "DEDICATED_DEVICE":
break;
default:
String msg = "Invalid ownership type received.Valid ownership types are BYOD | COPE | WORK_PROFILE |" +
"GOOGLE_ENTERPRISE | COSU | FULLY_MANAGED | DEDICATED_DEVICE";
log.error(msg);
throw new BadRequestException(msg);
}
}
/**
* Checks if user requested Action status codes are valid.
*
* @param status status codes upon to filter operation logs using status
*/
public static void validateStatusFiltering(String status) throws BadRequestException {
if (Constants.OperationStatus.COMPLETED.toUpperCase().equals(status)
|| Constants.OperationStatus.ERROR.toUpperCase().equals(status)
|| Constants.OperationStatus.NOTNOW.toUpperCase().equals(status)
|| Constants.OperationStatus.REPEATED.toUpperCase().equals(status)
|| Constants.OperationStatus.PENDING.toUpperCase().equals(status)
|| Constants.OperationStatus.IN_PROGRESS.toUpperCase().equals(status)) {
} else {
String msg = "Invalid status type: " + status + ". \nValid status types are COMPLETED | ERROR | " +
"IN_PROGRESS | NOTNOW | PENDING | REPEATED";
log.error(msg);
throw new BadRequestException(msg);
}
}
}

@ -0,0 +1,101 @@
/*
* 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.
*
*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://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.application.mgt.store.api.util;
/**
* Holds the constants used by DeviceImpl Management Admin web application.
*/
public class Constants {
public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress";
public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname";
public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname";
public static final String USER_CLAIM_CREATED = "http://wso2.org/claims/created";
public static final String USER_CLAIM_MODIFIED = "http://wso2.org/claims/modified";
public static final String USER_CLAIM_DEVICES = "http://wso2.org/claims/devices";
public static final String PRIMARY_USER_STORE = "PRIMARY";
public static final String DEFAULT_STREAM_VERSION = "1.0.0";
public static final String SCOPE = "scope";
public static final String JDBC_USERSTOREMANAGER = "org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager";
public static final String DEFAULT_SIMPLE_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
public static final int DEFAULT_PAGE_LIMIT = 50;
public static final String FORWARD_SLASH = "/";
public static final String ANDROID = "android";
public static final String ANDROID_POLICY_VALIDATOR = "io.entgra.proprietary.platform.android." +
"core.polcy.AndroidPolicyPayloadValidator";
public static final String IOS = "ios";
public static final String WINDOWS = "windows";
public final class OperationStatus {
private OperationStatus () { throw new AssertionError(); }
public static final String COMPLETED = "completed";
public static final String ERROR = "error";
public static final String IN_PROGRESS = "in_progress";
public static final String PENDING = "pending";
public static final String NOTNOW = "notnow";
public static final String REPEATED = "repeated";
}
public static final String DEVICES = "devices";
public static final String ATTRIBUTE_DISPLAY_NAME = "DisplayName";
public static final String ATTRIBUTE_DESCRIPTION = "Description";
public static final String EXTERNAL_DEVICE_CLAIM_DISPLAY_NAME = "Devices";
public static final String EXTERNAL_DEVICE_CLAIM_DESCRIPTION = "Device list";
public final class ErrorMessages {
private ErrorMessages () { throw new AssertionError(); }
public static final String STATUS_BAD_REQUEST_MESSAGE_DEFAULT = "Bad Request";
}
public final class DeviceConstants {
private DeviceConstants () { throw new AssertionError(); }
public static final String APPLICATION_JSON = "application/json";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
}
public final class Permission {
private Permission() { throw new AssertionError(); }
public static final String ADMIN = "/permission/admin";
public static final String LOGIN = "/permission/admin/login";
public static final String DEVICE_MGT = "/permission/admin/device-mgt";
public static final String APP_MGT = "/permission/admin/app-mgt";
}
}

@ -269,6 +269,12 @@ public interface DeviceManagementService {
@QueryParam("ownership")
@Size(max = 45)
String ownership,
@ApiParam(
name = "serialNumber",
value = "The serial number of the device.",
required = false)
@QueryParam("serialNumber")
String serialNumber,
@ApiParam(
name = "status",
value = "Provide the device status details, such as active or inactive.",

@ -172,6 +172,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("userPattern") String userPattern,
@QueryParam("role") String role,
@QueryParam("ownership") String ownership,
@QueryParam("serialNumber") String serialNumber,
@QueryParam("status") List<String> status,
@QueryParam("groupId") int groupId,
@QueryParam("since") String since,
@ -205,6 +206,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
RequestValidationUtil.validateOwnershipType(ownership);
request.setOwnership(ownership);
}
if (StringUtils.isNotBlank(serialNumber)) {
request.setSerialNumber(serialNumber);
}
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status){

@ -175,7 +175,8 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceAccessAuthorizationService);
Response response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
@ -194,19 +195,23 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, true, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
@ -319,7 +324,7 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceManagementProviderService);
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null,
DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS_LIST, 1,
DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, DEFAULT_STATUS_LIST, 1,
null, null, false, 10, 5);
}
@ -339,11 +344,11 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
@ -365,7 +370,8 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService);
}
@ -386,15 +392,18 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, 10, 5);
null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, 10, 5);
null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", false, 10, 5);
null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince",
false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
@ -414,15 +423,18 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, since, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 0, since, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, since, null, true, 10, 5);
null, DEFAULT_STATUS_LIST, 0, since, null, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
@ -444,7 +456,8 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceManagementProviderService);
}
@ -466,7 +479,8 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService);
}

@ -40,6 +40,7 @@ public class PaginationRequest {
private String ownerRole;
private Date since;
private String filter;
private String serialNumber;
private Map<String, Object> property = new HashMap<>();
private List<String> statusList = new ArrayList<>();
private OperationLogFilters operationLogFilters = new OperationLogFilters();
@ -153,6 +154,10 @@ public class PaginationRequest {
return this.property.get(key);
}
public String getSerialNumber() { return serialNumber; }
public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; }
public Map<String, Object> getProperties() {
Map<String, Object> temp = new HashMap<>();
temp.putAll(property);

@ -653,14 +653,12 @@ public interface DeviceDAO {
*
* @param deviceIds device ids of the subscribed devices.
* @param tenantId Id of the current tenant.
* @param offsetValue offset value for get paginated request.
* @param limitValue limit value for get paginated request.
* @param status status of the devices.
* @param request paginated request object.
* @return devices - subscribed device details list
* @throws DeviceManagementDAOException if connections establishment fails.
*/
List<Device> getSubscribedDevices(int offsetValue, int limitValue, List<Integer> deviceIds,
int tenantId, List<String> status) throws DeviceManagementDAOException;
List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException;
/**
* @param deviceIds device ids of the subscribed devices.

@ -67,6 +67,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false;
Date since = request.getSince();
boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try {
Connection conn = getConnection();
@ -87,10 +90,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
"t.NAME AS DEVICE_TYPE ";
if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add query for last updated timestamp
if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
@ -128,6 +140,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
@ -877,11 +892,15 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, List<String> status)
public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
@ -891,6 +910,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
@ -918,6 +941,18 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status);
isStatusProvided = true;
@ -930,8 +965,16 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
for (Integer deviceId : deviceIds) {
ps.setObject(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) {
for (String deviceStatus : status) {
ps.setString(index++, deviceStatus);

@ -68,6 +68,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false;
Date since = request.getSince();
boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try {
conn = getConnection();
@ -88,9 +90,19 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
"t.NAME AS DEVICE_TYPE ";
if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add query for last updated timestamp
if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
@ -128,6 +140,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
@ -847,11 +862,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, List<String> status)
public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
@ -861,6 +880,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
@ -888,6 +910,18 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status);
isStatusProvided = true;
@ -902,6 +936,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) {
for (String deviceStatus : status) {
ps.setString(index++, deviceStatus);

@ -67,6 +67,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false;
Date since = request.getSince();
boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try {
conn = getConnection();
@ -87,11 +89,19 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"t.NAME AS DEVICE_TYPE ";
if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ?";
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?";
@ -124,6 +134,9 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId);
if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType);
@ -827,11 +840,15 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, List<String> status)
public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
@ -841,6 +858,9 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
@ -868,6 +888,18 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status);
isStatusProvided = true;
@ -882,6 +914,15 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) {
for (String deviceStatus : status) {
ps.setString(index++, deviceStatus);

@ -69,6 +69,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false;
Date since = request.getSince();
boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try {
conn = getConnection();
@ -89,8 +91,19 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
"t.NAME AS DEVICE_TYPE ";
if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add query for last updated timestamp
if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
@ -128,6 +141,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
@ -693,11 +709,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, List<String> status)
public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
@ -707,6 +727,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1;
boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
@ -734,6 +757,18 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status);
isStatusProvided = true;
@ -748,6 +783,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) {
for (String deviceStatus : status) {
ps.setString(index++, deviceStatus);

@ -905,14 +905,12 @@ public interface DeviceManagementProviderService {
* This method retrieves a list of subscribed devices.
*
* @param devicesIds devices ids of the subscribed devices.
* @param offsetValue offset value for get paginated request.
* @param limitValue limit value for get paginated request.
* @param status status of the devices.
* @param request paginated request object.
* @return {@link PaginationResult}
* @throws DeviceManagementException if any service level or DAO level error occurs.
*/
PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue,
List<Integer> devicesIds, List<String> status) throws DeviceManagementException;
PaginationResult getAppSubscribedDevices(PaginationRequest request, List<Integer> devicesIds)
throws DeviceManagementException;
/**
* This method is used to get a list of applications installed in all enrolled devices

@ -4156,9 +4156,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
@Override
public PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue, List<Integer> devicesIds,
List<String> status) throws DeviceManagementException {
public PaginationResult getAppSubscribedDevices(PaginationRequest request, List<Integer> devicesIds) throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (log.isDebugEnabled()) {
log.debug("Getting all devices details for device ids: " + devicesIds);
@ -4167,15 +4165,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
List<Device> subscribedDeviceDetails;
try {
DeviceManagementDAOFactory.openConnection();
subscribedDeviceDetails = deviceDAO
.getSubscribedDevices(offsetValue, limitValue, devicesIds, tenantId, status);
subscribedDeviceDetails = deviceDAO.getSubscribedDevices(request, devicesIds, tenantId);
if (subscribedDeviceDetails.isEmpty()) {
paginationResult.setData(new ArrayList<>());
paginationResult.setRecordsFiltered(0);
paginationResult.setRecordsTotal(0);
return paginationResult;
}
int count = deviceDAO.getSubscribedDeviceCount(devicesIds, tenantId, status);
int count = deviceDAO.getSubscribedDeviceCount(devicesIds, tenantId, request.getStatusList());
paginationResult.setRecordsFiltered(count);
paginationResult.setRecordsTotal(count);
} catch (DeviceManagementDAOException e) {

Loading…
Cancel
Save