Create an API to get device details with given app installed

feature/appm-store/pbac
nipunnadeen 5 years ago committed by nipun
parent c5793bcf67
commit 4c51c0af45

@ -0,0 +1,42 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
public class BasePaginatedResult {
/**
* Number of Resources returned.
*/
@ApiModelProperty(
value = "Number of total resources.",
example = "1")
@JsonProperty("count")
private long count;
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}

@ -0,0 +1,53 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.common;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.Device;
import java.util.ArrayList;
import java.util.List;
public class DeviceList extends BasePaginatedResult {
private List<Device> devices = new ArrayList<>();
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices")
public List<Device> getList() {
return devices;
}
public void setList(List<Device> devices) {
this.devices = devices;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" devices: [").append(devices).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -19,7 +19,11 @@
package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse;
//import org.wso2.carbon.device.application.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.List;
@ -29,4 +33,17 @@ import java.util.List;
public interface SubscriptionManager {
<T> ApplicationInstallResponse performBulkAppOperation(String applicationUUID, List<T> params, String subType,
String action) throws ApplicationManagementException;
/***
* This method used to get the app id ,device ids and pass them to DM service layer method
* @param appUUID uuid
* @param offsetValue offsetValue
* @param limitValue limitValue
* @param status status
* @return deviceDetails
* @throws ApplicationManagementException Exception of the application management
*/
PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID,
String status)
throws ApplicationManagementException;
}

@ -333,6 +333,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.UNSUBSCRIBED_BY AS UNSUBSCRIBED_BY, "
+ "DS.UNSUBSCRIBED_TIMESTAMP AS UNSUBSCRIBED_AT, "
+ "DS.ACTION_TRIGGERED_FROM AS ACTION_TRIGGERED_FROM, "
+ "DS.STATUS AS STATUS,"
+ "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.TENANT_ID=?";
@ -696,4 +697,5 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -21,12 +21,7 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse;
import org.wso2.carbon.device.application.mgt.common.ApplicationType;
import org.wso2.carbon.device.application.mgt.common.DeviceTypes;
import org.wso2.carbon.device.application.mgt.common.SubAction;
import org.wso2.carbon.device.application.mgt.common.SubsciptionType;
import org.wso2.carbon.device.application.mgt.common.SubscribingDeviceIdHolder;
import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.dto.DeviceSubscriptionDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
@ -68,13 +63,10 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.util.MDMAndroidOperationUtil;
import org.wso2.carbon.device.mgt.core.util.MDMIOSOperationUtil;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.*;
import java.util.stream.Collectors;
/**
@ -559,4 +551,63 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
throw new ApplicationManagementException(msg, e);
}
}
@Override
public PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID,
String status)
throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
DeviceManagementProviderService deviceManagementProviderService = HelperUtil
.getDeviceManagementProviderService();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(appUUID, tenantId);
int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseId, tenantId);
if (deviceSubscriptionDTOS.isEmpty()) {
String msg = "Couldn't found an subscribed devices for application release id: "
+ applicationReleaseId;
log.error(msg);
}
List<Integer> deviceIdList = new ArrayList<>();
for (DeviceSubscriptionDTO deviceIds : deviceSubscriptionDTOS) {
deviceIdList.add(deviceIds.getDeviceId());
}
//pass the device id list to device manager service layer method
try {
PaginationResult deviceDetails = deviceManagementProviderService
.getAppSubscribedDevices(offsetValue ,limitValue, deviceIdList, status);
if (deviceDetails == null) {
String msg = "Couldn't found an subscribed devices details for device ids: "
+ deviceIdList;
log.error(msg);
throw new NotFoundException(msg);
}
return deviceDetails;
} catch (DeviceManagementException e) {
String msg = "service error occurred while getting data from the service";
log.error(msg);
throw new ApplicationManagementException(msg, e);
}
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred when get application release data for application" +
" release UUID: " + appUUID;
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "DB Connection error occurred while getting device details that " +
"given application id";
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -17,24 +17,19 @@
*/
package org.wso2.carbon.device.application.mgt.store.api.services;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@ -170,4 +165,67 @@ public interface SubscriptionManagementAPI {
)
@Valid List<String> subscribers
);
@GET
@Path("/{uuid}/devices")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get device details that have a given application install",
notes = "This will get the device details that have a given application install, if exists",
tags = "Subscription Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:subscription:uninstall")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved device details.",
response = List.class,
responseContainer = "List"),
@ApiResponse(
code = 404,
message = "Not Found. \n No Application found which has application release of UUID.",
response = ErrorResponse.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Found invalid payload with the request.",
response = List.class),
@ApiResponse(
code = 403,
message = "Forbidden. \n Don't have permission to get the details.",
response = List.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting data",
response = ErrorResponse.class)
})
Response getAppInstalledDevices(
@ApiParam(
name="uuid",
value="uuid of the application release.",
required = true)
@PathParam("uuid") String uuid,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.",
defaultValue = "5")
@QueryParam("limit") int limit,
@ApiParam(
name = "status",
value = "Provide the device status details, such as active or inactive.")
@QueryParam("status") String status
);
}

@ -17,10 +17,15 @@
*/
package org.wso2.carbon.device.application.mgt.store.api.services.impl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse;
import org.wso2.carbon.device.application.mgt.common.DeviceList;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.common.SubsciptionType;
import org.wso2.carbon.device.application.mgt.common.response.Application;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
@ -28,13 +33,12 @@ import org.wso2.carbon.device.application.mgt.store.api.services.SubscriptionMan
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
@ -81,6 +85,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
}
}
@Override
@POST
@Path("/{uuid}/{subType}/{action}")
@ -115,4 +120,49 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Consumes("application/json")
@Produces("application/json")
@Path("/{uuid}/devices")
public Response getAppInstalledDevices(@PathParam("uuid") String uuid,
@DefaultValue("0")
@QueryParam("offset") int offset,
@DefaultValue("5")
@QueryParam("limit") int limit,
@QueryParam("status") String status) {
try {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
PaginationResult subscribedDeviceDetails = subscriptionManager
.getAppInstalledDevices(offset, limit, uuid, status);
DeviceList devices = new DeviceList();
devices.setList((List<Device>) subscribedDeviceDetails.getData());
devices.setCount(subscribedDeviceDetails.getRecordsTotal());
return Response.status(Response.Status.OK).entity(devices).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";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
String msg = "Application release is not in the installable state."
+ "Hence you are not permitted to get the devices details.";
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting application with the application release uuid: "
+ uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -29,8 +29,8 @@
<artifactId>io.entgra.device.mgt.ui</artifactId>
<version>3.2.9-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - Device Management UI Component</name>
<url>http://wso2.org</url>
<name>Entgra - Device Management UI Component</name>
<url>https://entgra.io</url>
<description>This Component contains Device Management UI</description>
<dependencies>
</dependencies>

@ -550,4 +550,20 @@ public interface DeviceDAO {
int tenantId,
String fromDate,
String toDate) throws DeviceManagementDAOException;
/**
* this method is used to get the details of devices
* @param deviceIds device ids
* @param tenantId tenant id
* @param offsetValue offsetValue
* @param limitValue limitValue
* @param status status
* @return subscribed device details list
* @throws DeviceManagementDAOException throws {@link DeviceManagementDAOException} if connections
* establishment fails.
*/
List<Device> getSubscribedDevices(int offsetValue, int limitValue, List<Integer> deviceIds,
int tenantId, String status)
throws DeviceManagementDAOException;
}

@ -2029,4 +2029,5 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
}
return true;
}
}

@ -34,6 +34,7 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
/**
* This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax.
@ -559,6 +560,65 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, String status)
throws DeviceManagementDAOException {
Connection conn;
try {
conn = this.getConnection();
int index = 1;
boolean isStatusProvided = false;
StringJoiner joiner = new StringJoiner(",",
"SELECT " +
"f.ID AS DEVICE_ID, f.NAME AS DEVICE_NAME, f.DESCRIPTION AS DESCRIPTION, " +
"f.DEVICE_TYPE_ID, f.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, " +
"e.ID AS ENROLMENT_ID, e.OWNER, e.OWNERSHIP, e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, e.STATUS, t.NAME AS DEVICE_TYPE " +
"FROM DM_ENROLMENT AS e,DM_DEVICE AS f, DM_DEVICE_TYPE t "+
"WHERE " +
"e.DEVICE_ID=f.ID AND " +
"e.DEVICE_ID IN (", ") AND e.TENANT_ID=?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (status != null && !status.isEmpty()) {
query = query + " AND e.STATUS=?";
isStatusProvided = true;
}
query = query + " LIMIT ?,?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : deviceIds) {
ps.setObject(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (isStatusProvided) {
ps.setString(index++, status);
}
ps.setInt(index++, offsetValue);
ps.setInt(index, limitValue);
try (ResultSet rs = ps.executeQuery()) {
List<Device> devices = new ArrayList<>();
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDevice(rs));
}
return devices;
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information " +
"of all registered devices according to device ids and the limit area", e);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -567,6 +567,13 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, String status)
throws DeviceManagementDAOException {
return null;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -542,6 +542,13 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, String status)
throws DeviceManagementDAOException {
return null;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -497,6 +497,13 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices;
}
@Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue,
List<Integer> deviceIds, int tenantId, String status)
throws DeviceManagementDAOException {
return null;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -746,7 +746,6 @@ public interface DeviceManagementProviderService {
DeviceTypeVersion getDeviceTypeVersion(String deviceTypeName, String version) throws
DeviceManagementException;
/**
* Retrieves a list of configurations of a specific device
* using the device's properties
@ -769,4 +768,17 @@ public interface DeviceManagementProviderService {
* @return tru if device transferee, otherwise false
*/
List<String> transferDeviceToTenant(DeviceTransferRequest deviceTransferRequest) throws DeviceManagementException, DeviceNotFoundException;
/**
* This method retrieves a list of subscribed devices.
* @param devicesIds devices ids
* @param offsetValue offsetValue
* @param limitValue limitValue
* @param status status
* @return {@link PaginationResult}
* @throws DeviceManagementException if any service level or DAO level error occurs
*/
PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue,
List<Integer> devicesIds, String status)
throws DeviceManagementException;
}

@ -3610,4 +3610,39 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceConfiguration.setDeviceOwner(deviceOwner);
return deviceConfiguration;
}
@Override
public PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue,
List<Integer> devicesIds, String status)
throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (log.isDebugEnabled()) {
log.debug("Getting all devices details for device ids: " + devicesIds);
}
PaginationResult paginationResult = new PaginationResult();
int count;
List<Device> SubscribedDeviceDetails;
try {
DeviceManagementDAOFactory.openConnection();
SubscribedDeviceDetails = deviceDAO
.getSubscribedDevices(offsetValue, limitValue, devicesIds, tenantId, status);
count = SubscribedDeviceDetails.size();
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving device list for device ids " + devicesIds;
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, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
paginationResult.setData(getAllDeviceInfo(SubscribedDeviceDetails));
paginationResult.setRecordsFiltered(count);
paginationResult.setRecordsTotal(count);
return paginationResult;
}
}

Loading…
Cancel
Save