diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml index 77464d6aeb..343ad6d547 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml @@ -17,7 +17,8 @@ ~ under the License. --> - + device-mgt @@ -108,9 +109,10 @@ - + - + @@ -455,5 +457,15 @@ io.entgra.device.mgt.core.apimgt.analytics.extension provided + + com.google.api-client + google-api-client + 1.30.7 + + + com.google.apis + google-api-services-sheets + v4-rev539-1.25.0 + \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java index dc4e9b6e36..2bf1425a6f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -18,26 +18,31 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import com.google.api.services.sheets.v4.model.ValueRange; +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.sheets.v4.Sheets; +import com.google.api.services.sheets.v4.SheetsScopes; import com.google.gson.Gson; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; -import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; -import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; -import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; -import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; -import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; +import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; +import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; +import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; @@ -64,7 +69,6 @@ import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; import io.entgra.device.mgt.core.device.mgt.core.app.mgt.ApplicationManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; -import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.DeviceInformationManager; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; @@ -75,22 +79,19 @@ import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchManagerService import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchMgtException; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.DeviceAPIClientService; -import io.entgra.device.mgt.core.device.mgt.core.traccar.common.TraccarHandlerConstants; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; -import io.entgra.device.mgt.core.device.mgt.core.util.HttpReportingUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; @@ -98,20 +99,74 @@ import javax.validation.Valid; import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.Response; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.GeneralSecurityException; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.ExecutionException; +import java.util.*; @Path("/devices") public class DeviceManagementServiceImpl implements DeviceManagementService { - + public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class); - + + /** + * Validate group Id and group Id greater than 0 and exist. + * + * @param groupId Group ID of the group + * @param from time to start getting DeviceLocationHistorySnapshotWrapper in milliseconds + * @param to time to end getting DeviceLocationHistorySnapshotWrapper in milliseconds + */ + private static void validateGroupId(int groupId, long from, long to) throws GroupManagementException, BadRequestException { + if (from == 0 || to == 0) { + String msg = "Invalid values for from/to"; + log.error(msg); + throw new BadRequestException(msg); + } + if (groupId <= 0) { + String msg = "Invalid group ID '" + groupId + "'"; + log.error(msg); + throw new BadRequestException(msg); + } + GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); + if (service.getGroup(groupId, false) == null) { + String msg = "Invalid group ID '" + groupId + "'"; + log.error(msg); + throw new BadRequestException(msg); + } + } + + private void saveResponseTimeToSpreadsheet(long startTime, long endTime, long responseTime) throws IOException, GeneralSecurityException { + // Load credentials from JSON file + GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("/home/entgra/MyProject/device-mgt-core/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/resources/apicall-382608-48aa6a62800d.json")) + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + + // Build Google Sheets service + Sheets sheetsService = new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), + JacksonFactory.getDefaultInstance(), credential) + .setApplicationName("ApiCall") + .build(); + + // Define the spreadsheet ID and range + String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; + String range = "Sheet1!A:C"; + + // Prepare the values to be written + List rowValues = Arrays.asList(startTime, endTime, responseTime); + List> values = Collections.singletonList(rowValues); + + // Build the value range object + ValueRange body = new ValueRange().setValues(values); + + // Write the response time value to the spreadsheet + sheetsService.spreadsheets().values() + .append(spreadsheetId, range, body) + .setValueInputOption("USER_ENTERED") + .execute(); + } + @GET @Path("/{type}/{id}/status") @Override @@ -131,7 +186,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Override public Response getDevices( @@ -162,7 +217,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceList devices = new DeviceList(); - + if (name != null && !name.isEmpty()) { request.setDeviceName(name); } @@ -191,7 +246,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } // this is the user who initiates the request String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); - + if (groupId != 0) { try { boolean isPermitted = DeviceMgtAPIUtils.checkPermission(groupId, authorizedUser); @@ -234,7 +289,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { request.setOwner(authorizedUser); } } - + if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date sinceDate; SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); @@ -250,7 +305,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } else { result = dms.getAllDevices(request, false); } - + if (result == null || result.getData() == null || result.getData().size() <= 0) { return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " + "after the timestamp provided in 'If-Modified-Since' header").build(); @@ -286,7 +341,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { Response.status(Response.Status.OK).entity(devices).build(); } } - + devices.setList((List) result.getData()); devices.setCount(result.getRecordsTotal()); return Response.status(Response.Status.OK).entity(devices).build(); @@ -302,22 +357,22 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - + @GET @Override @Path("/user-devices") public Response getDeviceByUser(@QueryParam("requireDeviceInfo") boolean requireDeviceInfo, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { - + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceList devices = new DeviceList(); - + String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); request.setOwner(currentUser); - + try { if (requireDeviceInfo) { result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request); @@ -334,33 +389,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - - /** - * Validate group Id and group Id greater than 0 and exist. - * - * @param groupId Group ID of the group - * @param from time to start getting DeviceLocationHistorySnapshotWrapper in milliseconds - * @param to time to end getting DeviceLocationHistorySnapshotWrapper in milliseconds - */ - private static void validateGroupId(int groupId, long from, long to) throws GroupManagementException, BadRequestException { - if (from == 0 || to == 0) { - String msg = "Invalid values for from/to"; - log.error(msg); - throw new BadRequestException(msg); - } - if (groupId <= 0) { - String msg = "Invalid group ID '" + groupId + "'"; - log.error(msg); - throw new BadRequestException(msg); - } - GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); - if (service.getGroup(groupId, false) == null) { - String msg = "Invalid group ID '" + groupId + "'"; - log.error(msg); - throw new BadRequestException(msg); - } - } - + @GET @Override @Path("/{groupId}/location-history") @@ -375,7 +404,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); PaginationRequest request = new PaginationRequest(offset, limit); DeviceList devices = new DeviceList(); - + // this is the user who initiates the request String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); try { @@ -398,17 +427,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String msg = "Error occurred while retrieving role list of user '" + authorizedUser + "'"; log.error(msg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - }catch (BadRequestException e){ + } catch (BadRequestException e) { String msg = "Error occurred while validating the device group."; log.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } - + PaginationResult result = dms.getAllDevices(request, false); - + if (!result.getData().isEmpty()) { devices.setList((List) result.getData()); - + for (Device device : devices.getList()) { DeviceLocationHistorySnapshotWrapper snapshotWrapper = DeviceMgtAPIUtils.getDeviceHistorySnapshots( device.getType(), device.getDeviceIdentifier(), authorizedUser, from, to, type, @@ -435,7 +464,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @DELETE @Override @Path("/type/{deviceType}/id/{deviceId}") @@ -444,20 +473,30 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { + long startTime = System.currentTimeMillis(); // start measuring API call response time DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, true); if (persistedDevice == null) { return Response.status(Response.Status.NOT_FOUND).build(); } boolean response = deviceManagementProviderService.disenrollDevice(deviceIdentifier); + long endTime = System.currentTimeMillis(); //end measuring API call response time + long responseTime = endTime - startTime; + + // save the start time, end time and response time to google sheet + saveResponseTimeToSpreadsheet(startTime, endTime, responseTime); return Response.status(Response.Status.OK).entity(response).build(); } catch (DeviceManagementException e) { - String msg = "Error encountered while deleting requested device of type : " + deviceType ; + String msg = "Error encountered while deleting requested device of type : " + deviceType; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (IOException | GeneralSecurityException e) { + String msg = "Error encountered while saving response time to spreadsheet"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @POST @Override @Path("/type/{deviceType}/id/{deviceId}/rename") @@ -465,6 +504,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @PathParam("deviceId") String deviceId) { DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { + // Start measuring API call response time + long startTime = System.currentTimeMillis(); Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier (deviceId, deviceType), true); persistedDevice.setName(device.getName()); @@ -473,15 +514,26 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { boolean responseOfDeviceNameChanged = deviceManagementProviderService.sendDeviceNameChangedNotification( persistedDevice); boolean response = responseOfmodifyEnrollment && responseOfDeviceNameChanged; - + + // End measuring API call response time + long endTime = System.currentTimeMillis(); + long responseTime = endTime - startTime; + + // Save the response time, start time, and end time to Google Spreadsheet + saveResponseTimeToSpreadsheet(startTime, endTime, responseTime); + return Response.status(Response.Status.CREATED).entity(response).build(); } catch (DeviceManagementException e) { - String msg = "Error encountered while updating requested device of type : " + deviceType ; + String msg = "Error encountered while updating requested device of type : " + deviceType; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (IOException | GeneralSecurityException e) { + String msg = "Error encountered while saving response time to spreadsheet"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/{type}/{id}") @Override @@ -498,7 +550,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceAccessAuthorizationService deviceAccessAuthorizationService = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); - + // this is the user who initiates the request String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type); @@ -509,10 +561,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.UNAUTHORIZED).entity( new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_UNAUTHORIZED).setMessage(msg).build()).build(); } - + DeviceData deviceData = new DeviceData(); deviceData.setDeviceIdentifier(deviceIdentifier); - + if (!StringUtils.isBlank(ifModifiedSince)) { SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); try { @@ -524,7 +576,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } - + if (!StringUtils.isBlank(owner)) { deviceData.setDeviceOwner(owner); } @@ -553,7 +605,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).entity(device).build(); } - + @GET @Path("/{deviceType}/{deviceId}/location-history") public Response getDeviceLocationInfo( @@ -592,7 +644,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/type/any/id/{id}") @Override @@ -606,10 +658,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceAccessAuthorizationService deviceAccessAuthorizationService = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); - + // this is the user who initiates the request String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); - + Date sinceDate = null; if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); @@ -644,7 +696,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { "device id '" + id + "'"; log.error(message); return Response.status(Response.Status.UNAUTHORIZED).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(message).build()).build(); + new ErrorResponse.ErrorResponseBuilder().setCode(401L).setMessage(message).build()).build(); } } catch (DeviceManagementException e) { String message = "Error occurred while fetching the device information."; @@ -659,7 +711,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).entity(device).build(); } - + @POST @Path("/enrollment/guide") @Override @@ -684,8 +736,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - - + + @POST @Path("/type/any/list") @Override @@ -706,7 +758,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/{type}/{id}/location") @Override @@ -729,10 +781,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceLocation).build(); - + } - - + + @GET @Path("/{type}/{id}/info") @Override @@ -748,7 +800,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { deviceIdentifier.setType(type); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); - + } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device information of id : " + id + " type : " + type; log.error(msg, e); @@ -756,8 +808,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceInfo).build(); - + } + @GET @Path("/{type}/{id}/config") @Override @@ -765,11 +818,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { - + DeviceConfig deviceConfig = new DeviceConfig(); deviceConfig.setDeviceId(id); deviceConfig.setType(type); - + // find token validity time DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); @@ -784,81 +837,81 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } mqttEventTopicStructure = deviceType.getDeviceTypeMetaDefinition().getMqttEventTopicStructures(); } else { - String msg = "Device not found, device id : " + id + ", device type : " + type; + String msg = "Device not found, device id : " + id + ", device type : " + type; log.error(msg); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving device, device id : " + id + ", device type : " + type; + String msg = "Error occurred while retrieving device, device id : " + id + ", device type : " + type; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - + String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String applicationName = type.replace(" ", "").replace("_", "") + "_" + tenantDomain; - + KeyMgtService keyMgtService = new KeyMgtServiceImpl(); try { DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username, - "client_credentials", null, new String[] {"device_management"}, false, validityTime); + "client_credentials", null, new String[]{"device_management"}, false, validityTime); deviceConfig.setClientId(dcrResponse.getClientId()); deviceConfig.setClientSecret(dcrResponse.getClientSecret()); - + StringBuilder scopes = new StringBuilder("device:" + type.replace(" ", "") + ":" + id); for (String topic : mqttEventTopicStructure) { if (topic.contains("${deviceId}")) { topic = topic.replace("${deviceId}", id); } - topic = topic.replace("/",":"); + topic = topic.replace("/", ":"); // scopes.append(" perm:topic:sub:".concat(topic)); scopes.append(" perm:topic:pub:".concat(topic)); } - + // add scopes for retrieve operation topic /tenantDomain/deviceType/deviceId/operation/# scopes.append(" perm:topic:sub:" + tenantDomain + ":" + type + ":" + id + ":operation"); - + // add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation"); - + TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(), null, scopes.toString(), "client_credentials", null, - null, null, null, validityTime); + null, null, null, validityTime); TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest); deviceConfig.setAccessToken(tokenResponse.getAccessToken()); deviceConfig.setRefreshToken(tokenResponse.getRefreshToken()); - + try { deviceConfig.setPlatformConfiguration(deviceManagementProviderService.getConfiguration(type)); } catch (DeviceManagementException e) { - String msg = "Error occurred while reading platform configurations token, device id : " + id + ", device type : " + type; + String msg = "Error occurred while reading platform configurations token, device id : " + id + ", device type : " + type; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - + deviceConfig.setMqttGateway("tcp://" + System.getProperty("mqtt.broker.host") + ":" + System.getProperty("mqtt.broker.port")); deviceConfig.setHttpGateway("http://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.http.port")); deviceConfig.setHttpsGateway("https://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.https.port")); - + } catch (KeyMgtException e) { - String msg = "Error occurred while creating oauth application, device id : " + id + ", device type : " + type; + String msg = "Error occurred while creating oauth application, device id : " + id + ", device type : " + type; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException e) { - String msg = "Error occurred while generating token, device id : " + id + ", device type : " + type; + String msg = "Error occurred while generating token, device id : " + id + ", device type : " + type; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceConfig).build(); - + } - + @GET @Path("/device-type/{type}/features") @Override @@ -873,7 +926,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { try { fm = dms.getFeatureManager(type); } catch (DeviceTypeNotFoundException e) { - String msg = "No device type found with name : " + type ; + String msg = "No device type found with name : " + type; return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } if (fm != null) { @@ -887,7 +940,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).entity(features).build(); } - + @POST @Path("/search-devices") @Override @@ -909,7 +962,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { deviceList.setCount(devices.size()); return Response.status(Response.Status.OK).entity(deviceList).build(); } - + @POST @Path("/query-devices") @Override @@ -942,7 +995,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { deviceList.setCount(devices.size()); return Response.status(Response.Status.OK).entity(deviceList).build(); } - + @GET @Path("/{type}/{id}/applications") @Override @@ -974,7 +1027,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - + @POST @Path("/{type}/{id}/uninstallation") @Override @@ -1027,7 +1080,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (SubscriptionManagementException | - io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException + io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException e) { String msg = "Error occurred while getting the " + type + "application is of device " + id + "subscribed " + "at entgra store"; @@ -1050,7 +1103,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/{type}/{id}/operations") @Override @@ -1104,12 +1157,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (DeviceTypeNotFoundException e) { - String msg = "No device type found with name : " + type ; + String msg = "No device type found with name : " + type; log.error(msg, e); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } } - + @GET @Path("/{type}/{id}/effective-policy") @Override @@ -1122,7 +1175,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { .getDevice(new DeviceIdentifier(id, type), false); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); Policy policy = policyManagementService.getAppliedPolicyToDevice(device); - + return Response.status(Response.Status.OK).entity(policy).build(); } catch (PolicyManagementException e) { String msg = "Error occurred while retrieving the current policy associated with the '" + type + @@ -1137,12 +1190,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - + @GET @Path("{type}/{id}/compliance-data") public Response getComplianceDataOfDevice(@PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id) { - + RequestValidationUtil.validateDeviceIdentifier(type, id); Device device; try { @@ -1158,7 +1211,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { Policy policy; NonComplianceData complianceData; DeviceCompliance deviceCompliance = new DeviceCompliance(); - + try { policy = policyManagementService.getAppliedPolicyToDevice(device); } catch (PolicyManagementException e) { @@ -1168,7 +1221,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - + if (policy == null) { deviceCompliance.setDeviceID(id); deviceCompliance.setComplianceData(null); @@ -1188,7 +1241,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } } } - + /** * Change device status. * @@ -1214,12 +1267,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { boolean response = deviceManagementProviderService.changeDeviceStatus(deviceIdentifier, newsStatus); return Response.status(Response.Status.OK).entity(response).build(); } catch (DeviceManagementException e) { - String msg = "Error occurred while changing device status of device type : " + type ; + String msg = "Error occurred while changing device status of device type : " + type; log.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } - + /** * List device status history * @@ -1244,12 +1297,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { List deviceStatusHistory = deviceManagementProviderService.getDeviceStatusHistory(persistedDevice); return Response.status(Response.Status.OK).entity(deviceStatusHistory).build(); } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving device status history for device of type : " + type ; + String msg = "Error occurred while retrieving device status history for device of type : " + type; log.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } - + /** * List device status history for the current enrolment * @@ -1279,7 +1332,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } - + @POST @Path("/{type}/operations") public Response addOperation(@PathParam("type") String type, @Valid OperationRequest operationRequest) { @@ -1313,7 +1366,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { operation.setCode(commandOperation.getCode()); operation.setEnabled(commandOperation.isEnabled()); operation.setStatus(commandOperation.getStatus()); - + } else if (operationType == Operation.Type.CONFIG) { Operation configOperation = operationRequest.getOperation(); operation = new ConfigOperation(); @@ -1322,7 +1375,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { operation.setEnabled(configOperation.isEnabled()); operation.setPayLoad(configOperation.getPayLoad()); operation.setStatus(configOperation.getStatus()); - + } else { Operation profileOperation = operationRequest.getOperation(); operation = new ProfileOperation(); @@ -1341,7 +1394,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String message = "Only Command and Config operation is supported through this api"; return Response.status(Response.Status.NOT_ACCEPTABLE).entity(message).build(); } - + } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; log.error(errorMessage, e); @@ -1362,7 +1415,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } - + @GET @Override @Path("/type/{type}/status/{status}/count") @@ -1378,7 +1431,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); } } - + @GET @Override @Path("/type/{type}/status/{status}/ids") @@ -1394,7 +1447,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); } } - + @PUT @Override @Path("/type/{type}/status/{status}") @@ -1410,7 +1463,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } return Response.status(Response.Status.OK).build(); } - + @GET @Override @Path("/compliance/{complianceStatus}") @@ -1425,15 +1478,15 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("offset") int offset, @DefaultValue("10") @QueryParam("limit") int limit) { - + PaginationRequest request = new PaginationRequest(offset, limit); ComplianceDeviceList complianceDeviceList = new ComplianceDeviceList(); PaginationResult paginationResult; try { - + PolicyManagerService policyManagerService = DeviceMgtAPIUtils.getPolicyManagementService(); paginationResult = policyManagerService.getPolicyCompliance(request, policyId, complianceStatus, isPending, fromDate, toDate); - + if (paginationResult.getData().isEmpty()) { return Response.status(Response.Status.OK) .entity("No policy compliance or non compliance devices are available").build(); @@ -1449,7 +1502,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - + @GET @Override @Path("/{id}/features") @@ -1459,7 +1512,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { try { PolicyManagerService policyManagerService = DeviceMgtAPIUtils.getPolicyManagementService(); complianceFeatureList = policyManagerService.getNoneComplianceFeatures(id); - + if (complianceFeatureList.isEmpty()) { return Response.status(Response.Status.OK).entity("No non compliance features are available").build(); } else { @@ -1472,7 +1525,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - + @GET @Override @Consumes("application/json") @@ -1492,7 +1545,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { PaginationResult paginationResult = DeviceMgtAPIUtils .getDeviceManagementService() .getApplications(request); - + if (paginationResult.getData().isEmpty()) { return Response.status(Response.Status.OK) .entity("No applications are available under " + deviceType + " platform.").build(); @@ -1513,7 +1566,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/application/{packageName}/versions") @Override @@ -1529,7 +1582,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @PUT @Path("/{deviceType}/{id}/operation") @Override @@ -1561,7 +1614,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { operation.setId(operationStatusBean.getOperationId()); operation.setCode(operationStatusBean.getOperationCode()); DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(device, operation); - + if (MDMAppConstants.AndroidConstants.OPCODE_INSTALL_APPLICATION.equals(operation.getCode()) || MDMAppConstants.AndroidConstants.OPCODE_UNINSTALL_APPLICATION.equals(operation.getCode())) { ApplicationManager applicationManager = DeviceMgtAPIUtils.getApplicationManager(); @@ -1573,7 +1626,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (DeviceManagementException e) { - String msg = "Error occurred when fetching device " + deviceIdentifier.toString(); + String msg = "Error occurred when fetching device " + deviceIdentifier; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (OperationManagementException e) { @@ -1587,7 +1640,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/filters") @Override @@ -1619,7 +1672,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - + @GET @Path("/{clientId}/{clientSecret}/default-token") @Override diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/resources/apicall-382608-48aa6a62800d.json b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/resources/apicall-382608-48aa6a62800d.json new file mode 100644 index 0000000000..7f91b7ae24 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/resources/apicall-382608-48aa6a62800d.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "apicall-382608", + "private_key_id": "48aa6a62800d6395fec77b5c86abcc08c48556f0", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDcJPEUsPn9ouwm\nkBpSz2dgmtq3A/bwbXzvlhe1/U4W3kq+vaSBPJ54tzKLx23pR6h9fxzljfDTLhZr\nBEhZFVKKSwbtlGaVA+6mJcnV2DT5S1bDqdMOs5y9CXsqZ+Xl2apYiryyKwWneKs5\nc5gU914QnxRDRskdxVUYMsAvwTU9A1aEHzRAaSuriH/1y6P8mpCBQtn7NAIt4Don\ntyzk2B2lC8HVZsMfup0zzut7quvwiYvly0pijCa9/pRTn/6BMFsVMUvqy8qa8PhX\nBIQ1SnehF4VW0h9fgljL9Bbu3m57IwxaVIcy8b61dTVUNVB1LgQ7NtmOdFG56bOy\nUXK8javlAgMBAAECggEAAtHoUqsHsMOPAdlztN7aRKcHKTQATEkiwhDqodaqUumr\nDHFyc4NaxlIWcCrwUf4sftsLfDdKv/HFsL4/zQBUa9gVMSLnA36m5nLyeG5KE21v\nIZeB0Bzl45gE/2CQVdbpczPnweKCMoh9rQE5j/8xMcZP5KK5/csi0WoJAzOW4n6r\n24JHoc82jqJKw0s91ZkzBTD3uoi3WbuRlKFzzRmRCJEIdY8VRR4/oZ4lphX26+hn\n3F5kuqWGsYItqZwNrbgtB4oiYXz2g2rIko2tj2FOvRNtE+6HmdH+hRlXasjcjnb9\ng/MZ9SOH852kXKh8SAWo3cWfWo5cvXYYYjGeQt41awKBgQD8uB3g46YLZrsp+fvK\nGxSzyf0fzSsgj0Byd7j8E703DE2yjZ+wybWjTyC+J+S2wLHoNNB5yMoTdte4m1ry\nnZvbVZuwS8tOb4HlriBm57Akp64A8Bhgi7VA+kbzGEV8ATdr2VvrBvTaVOsFqpL5\nIUWJuRWsKvjCJNEKyQdFq0e1gwKBgQDfAJDpNv8WjqT2W5AULIdZxqz5m4a0p/MW\nJk0KErVQXxZ8RQUuBkVlRi1o32dePZ4TXpFGS+txpbkt0HJlJ3lvhUpPpyFrISC0\nomkwChkk9p4Ss2LTm/eubsOzbZynqmRj/ahJJ2rL79WqnaKqHhqF9u0lZ9amDK8y\nWkVPh8DEdwKBgQC/6HTP/S9vQwDoHGxHCo+LA90TFDMm04GmKyIvUjICpnYuG/vj\nPRmQvRrpK9Qzr1qqMckKYh6J71pbVqYWzPa49WZ31ua5VlX2+2ahnlkVTLwG/EwW\nrKDkiens2kaRpz7VyEZT0IGJdqjOMbzQMKLktccuaadjjp+rqAK8theLTwKBgE8j\nykmZpOmCcfSkBfvC2b34jgZ/NU0DlXc03H5IqWP+euJbND1jKFmKkC75qZt+To0d\nMH08EDBi2dbydMaFPclgCkE+VNPKC+tO//l2e/nsM6j7VIU4gqu6z2Tr735pL/t0\nV7aucG4zjSZhjwrEaDFGsl5l/X0sXziFZLeWu8h9AoGBAL3DH0K1JZK4oNVIEeC9\nmOlSxTysDU7irrONUqB8l+J/gpAY732Tjrly+mHBSl5XIbHqv/68a4jArmfTvDMP\n1OAZxcYIoo97g/04mCV3m/FP/Wbfq9n6pUZPkh+BP9djLAqT9MsCkafGv+/W1GY6\nsWJ+swf3TwkD4S9EcVfNduNa\n-----END PRIVATE KEY-----\n", + "client_email": "apicall@apicall-382608.iam.gserviceaccount.com", + "client_id": "102201293562575371700", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/apicall%40apicall-382608.iam.gserviceaccount.com" +}