WIP: APiTesting #2

Closed
akeela_azhar wants to merge 18 commits from APiTesting into master

@ -97,10 +97,7 @@ import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class CertificateGenerator {
@ -798,8 +795,16 @@ public class CertificateGenerator {
BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
X500Name issuerName = new X500Name(certCA.getSubjectDN().getName());
//Reversing the order of components of the subject DN due to Nginx not verifying the client certificate
//generated by Java using this subject DN.
//Ref: https://stackoverflow.com/questions/33769978 & engineering mail SCEP implementation for Android
String[] dnParts = certCA.getSubjectDN().getName().split(",");
StringJoiner joiner = new StringJoiner(",");
for (int i = (dnParts.length - 1); i >= 0; i--) {
joiner.add(dnParts[i]);
}
String subjectDn = joiner.toString();
X500Name issuerName = new X500Name(subjectDn);
String commonName = certificationRequest.getSubject().getRDNs(BCStyle.CN)[0].getFirst()
.getValue().toString();
X500Name subjectName = new X500Name("O=" + commonName + "O=AndroidDevice,CN=" +

@ -455,5 +455,35 @@
<artifactId>io.entgra.device.mgt.core.apimgt.analytics.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>v4-rev539-1.25.0</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.43.1</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-terracotta</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>v4-rev20230227-2.0.0</version>
</dependency>
<dependency>
<groupId>com.lazerycode.jmeter</groupId>
<artifactId>jmeter-maven-plugin</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
</project>

@ -54,23 +54,38 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.validation.Valid;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.*;
@Path("/device/agent")
public class DeviceAgentServiceImpl implements DeviceAgentService {
private static final Log log = LogFactory.getLog(DeviceAgentServiceImpl.class);
static final Log log = LogFactory.getLog(DeviceAgentServiceImpl.class);
private static final String POLICY_MONITOR = "POLICY_MONITOR";
private static List<ComplianceFeature> getComplianceFeatures(Object compliancePayload) throws
PolicyComplianceException {
String compliancePayloadString = new Gson().toJson(compliancePayload);
if (compliancePayload == null) {
return null;
}
// Parsing json string to get compliance features.
JsonElement jsonElement = new JsonParser().parse(compliancePayloadString);
JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson();
ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<>(jsonArray.size());
for (JsonElement element : jsonArray) {
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
complianceFeatures.add(complianceFeature);
}
return complianceFeatures;
}
@POST
@Path("/enroll")
@Override
@ -114,7 +129,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@DELETE
@Path("/enroll/{type}/{id}")
@Override
@ -127,7 +142,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NO_CONTENT).entity(type + " device that carries id '" + id +
"' has not been dis-enrolled").build();
"' has not been dis-enrolled").build();
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while enrolling the device, which carries the id '" + id + "'";
@ -135,7 +150,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
@Path("/enroll/{type}/{id}")
@Override
@ -152,7 +167,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
if (updateDevice == null) {
String errorMessage = "The payload of the device enrollment is incorrect.";
log.error(errorMessage);
@ -163,7 +178,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(errorMessage);
return Response.status(Response.Status.NOT_FOUND).entity(errorMessage).build();
}
if (device.getEnrolmentInfo().getStatus() == EnrolmentInfo.Status.ACTIVE ) {
if (device.getEnrolmentInfo().getStatus() == EnrolmentInfo.Status.ACTIVE) {
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceMgtAPIUtils.getDeviceAccessAuthorizationService();
boolean status;
@ -179,25 +194,25 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
if(updateDevice.getEnrolmentInfo() != null) {
if (updateDevice.getEnrolmentInfo() != null) {
device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis());
device.setEnrolmentInfo(device.getEnrolmentInfo());
}
device.getEnrolmentInfo().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser());
if(updateDevice.getDeviceInfo() != null) {
if (updateDevice.getDeviceInfo() != null) {
device.setDeviceInfo(updateDevice.getDeviceInfo());
}
device.setDeviceIdentifier(id);
if(updateDevice.getDescription() != null) {
if (updateDevice.getDescription() != null) {
device.setDescription(updateDevice.getDescription());
}
if(updateDevice.getName() != null) {
if (updateDevice.getName() != null) {
device.setName(updateDevice.getName());
}
if(updateDevice.getFeatures() != null) {
if (updateDevice.getFeatures() != null) {
device.setFeatures(updateDevice.getFeatures());
}
if(updateDevice.getProperties() != null) {
if (updateDevice.getProperties() != null) {
device.setProperties(updateDevice.getProperties());
}
boolean result;
@ -216,13 +231,13 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@POST
@Path("/events/publish/{type}/{deviceId}")
@Override
public Response publishEvents(@Valid Map<String, Object> payload, @PathParam("type") String type
, @PathParam("deviceId") String deviceId) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
EventStreamAdminServiceStub eventStreamAdminServiceStub = null;
try {
@ -237,7 +252,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
}
}
Object metaData[] = new Object[1];
Object[] metaData = new Object[1];
metaData[0] = deviceId;
EventAttributeList eventAttributeList = DeviceMgtAPIUtils.getDynamicEventCache().get(type);
if (eventAttributeList == null) {
@ -253,7 +268,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) {
attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName()
, AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase())));
}
if (payload.size() != attributes.size()) {
String msg = "Payload does not match with the stream definition";
@ -281,7 +296,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
// , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain())
// , Constants.DEFAULT_STREAM_VERSION, metaData
// , null, payloadData)) {
return Response.status(Response.Status.OK).build();
return Response.status(Response.Status.OK).build();
// } else {
// String msg = "Error occurred while publishing the event.";
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
@ -316,13 +331,13 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
}
}
}
@POST
@Path("/events/publish/data/{type}/{deviceId}")
@Override
public Response publishEvents(@Valid List<Object> payload, @PathParam("type") String type
, @PathParam("deviceId") String deviceId) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
EventStreamAdminServiceStub eventStreamAdminServiceStub = null;
try {
@ -337,7 +352,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
}
}
Object metaData[] = new Object[1];
Object[] metaData = new Object[1];
metaData[0] = deviceId;
EventAttributeList eventAttributeList = DeviceMgtAPIUtils.getDynamicEventCache().get(type);
if (eventAttributeList == null) {
@ -353,7 +368,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) {
attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName()
, AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase())));
}
if (payload.size() != attributes.size()) {
String msg = "Payload does not match with the stream definition";
@ -382,7 +397,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
// , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain())
// , Constants.DEFAULT_STREAM_VERSION, metaData
// , null, payloadData)) {
return Response.status(Response.Status.OK).build();
return Response.status(Response.Status.OK).build();
// } else {
// String msg = "Error occurred while publishing the event.";
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
@ -417,7 +432,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
}
}
}
@GET
@Path("/pending/operations/{type}/{id}")
public Response getPendingOperations(@PathParam("type") String type, @PathParam("id") String deviceId) {
@ -433,23 +448,26 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(msg);
return Response.status(Response.Status.NO_CONTENT).entity(msg).build();
}
long startTime = System.currentTimeMillis(); // Record the start time
List<? extends Operation> operations = DeviceMgtAPIUtils.getDeviceManagementService().getPendingOperations(
deviceIdentifier);
OperationList operationsList = new OperationList();
operationsList.setList(operations);
operationsList.setCount(operations.size());
return Response.status(Response.Status.OK).entity(operationsList).build();
} catch (OperationManagementException e) {
String errorMessage = "Issue in retrieving operation management service instance";
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} catch (DeviceManagementException e) {
String errorMessage = "Issue in retrieving deivce management service instance";
String errorMessage = "Issue in retrieving device management service instance";
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}
@GET
@Path("/next-pending/operation/{type}/{id}")
public Response getNextPendingOperation(@PathParam("type") String type, @PathParam("id") String deviceId) {
@ -478,7 +496,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}
@PUT
@Path("/operations/{type}/{id}")
public Response updateOperation(@PathParam("type") String type, @PathParam("id") String deviceId, @Valid Operation operation) {
@ -525,19 +543,19 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}
@Override
@PUT
@Path("/properties/{type}/{id}")
public Response updateDeviceProperties(@PathParam("type") String type, @PathParam("id") String deviceId,
@Valid List<Device.Property> properties) {
@Valid List<Device.Property> properties) {
try {
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
String errorMessage = "Device type is invalid";
log.error(errorMessage);
return Response.status(Response.Status.BAD_REQUEST).build();
}
if(properties == null) {
if (properties == null) {
String errorMessage = "Properties cannot be empty";
log.error(errorMessage);
return Response.status(Response.Status.BAD_REQUEST).build();
@ -548,8 +566,8 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
if (DeviceMgtAPIUtils.getDeviceManagementService().updateProperties(deviceIdentifier, properties)){
if (DeviceMgtAPIUtils.getDeviceManagementService().updateProperties(deviceIdentifier, properties)) {
return Response.status(Response.Status.ACCEPTED).entity("Device properties updated.").build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Device properties not updated.").build();
@ -560,7 +578,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}
@GET
@Path("/status/operations/{type}/{id}")
public Response getOperationsByDeviceAndStatus(@PathParam("type") String type, @PathParam("id") String deviceId,
@ -570,7 +588,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(errorMessage);
return Response.status(Response.Status.BAD_REQUEST).build();
}
try {
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
String errorMessage = "Invalid Device Type";
@ -593,25 +611,4 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
}
private static List<ComplianceFeature> getComplianceFeatures(Object compliancePayload) throws
PolicyComplianceException {
String compliancePayloadString = new Gson().toJson(compliancePayload);
if (compliancePayload == null) {
return null;
}
// Parsing json string to get compliance features.
JsonElement jsonElement = new JsonParser().parse(compliancePayloadString);
JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson();
ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<>(jsonArray.size());
for (JsonElement element : jsonArray) {
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
complianceFeatures.add(complianceFeature);
}
return complianceFeatures;
}
}

@ -36,6 +36,12 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
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.api.services.sheets.v4.model.ValueRange;
import com.google.gson.Gson;
import io.entgra.application.mgt.common.ApplicationInstallResponse;
import io.entgra.application.mgt.common.SubscriptionType;
@ -47,7 +53,6 @@ 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 org.wso2.carbon.apimgt.keymgt.extension.DCRResponse;
import org.wso2.carbon.apimgt.keymgt.extension.TokenRequest;
import org.wso2.carbon.apimgt.keymgt.extension.TokenResponse;
@ -82,7 +87,6 @@ import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@ -93,10 +97,7 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
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.traccar.api.service.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.*;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
@ -116,20 +117,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/org.wso2.carbon.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<Object> rowValues = Arrays.asList(startTime, endTime, responseTime);
List<List<Object>> 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
@ -149,7 +204,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Override
public Response getDevices(
@ -180,7 +235,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);
}
@ -209,7 +264,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);
@ -252,7 +307,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");
@ -268,7 +323,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();
@ -304,7 +359,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
Response.status(Response.Status.OK).entity(devices).build();
}
}
devices.setList((List<Device>) result.getData());
devices.setCount(result.getRecordsTotal());
return Response.status(Response.Status.OK).entity(devices).build();
@ -320,22 +375,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);
@ -352,33 +407,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")
@ -393,7 +422,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 {
@ -416,17 +445,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<Device>) result.getData());
for (Device device : devices.getList()) {
DeviceLocationHistorySnapshotWrapper snapshotWrapper = DeviceMgtAPIUtils.getDeviceHistorySnapshots(
device.getType(), device.getDeviceIdentifier(), authorizedUser, from, to, type,
@ -453,7 +482,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@DELETE
@Override
@Path("/type/{deviceType}/id/{deviceId}")
@ -462,20 +491,32 @@ 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 response time, start time, and end time to Google Spreadsheet
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")
@ -483,6 +524,9 @@ 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());
@ -491,15 +535,27 @@ 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
@ -516,7 +572,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);
@ -527,10 +583,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 {
@ -542,7 +598,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
if (!StringUtils.isBlank(owner)) {
deviceData.setDeviceOwner(owner);
}
@ -571,7 +627,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(device).build();
}
@GET
@Path("/{deviceType}/{deviceId}/location-history")
public Response getDeviceLocationInfo(
@ -610,7 +666,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/type/any/id/{id}")
@Override
@ -624,10 +680,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");
@ -662,7 +718,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.";
@ -677,7 +733,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(device).build();
}
@POST
@Path("/enrollment/guide")
@Override
@ -702,8 +758,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@POST
@Path("/type/any/list")
@Override
@ -724,7 +780,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/{type}/{id}/location")
@Override
@ -747,10 +803,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
@ -766,7 +822,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);
@ -774,8 +830,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
@ -783,11 +840,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();
@ -802,82 +859,82 @@ 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(" ", "")
.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 (org.wso2.carbon.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
@ -892,7 +949,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) {
@ -906,7 +963,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(features).build();
}
@POST
@Path("/search-devices")
@Override
@ -928,7 +985,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
deviceList.setCount(devices.size());
return Response.status(Response.Status.OK).entity(deviceList).build();
}
@POST
@Path("/query-devices")
@Override
@ -961,7 +1018,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
@ -993,7 +1050,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@POST
@Path("/{type}/{id}/uninstallation")
@Override
@ -1046,7 +1103,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (SubscriptionManagementException |
io.entgra.application.mgt.common.exception.ApplicationManagementException
io.entgra.application.mgt.common.exception.ApplicationManagementException
e) {
String msg = "Error occurred while getting the " + type + "application is of device " + id + "subscribed " +
"at entgra store";
@ -1069,7 +1126,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/{type}/{id}/operations")
@Override
@ -1123,12 +1180,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
@ -1141,7 +1198,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 +
@ -1156,12 +1213,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 {
@ -1177,7 +1234,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
Policy policy;
NonComplianceData complianceData;
DeviceCompliance deviceCompliance = new DeviceCompliance();
try {
policy = policyManagementService.getAppliedPolicyToDevice(device);
} catch (PolicyManagementException e) {
@ -1187,7 +1244,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);
@ -1207,7 +1264,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
}
}
/**
* Change device status.
*
@ -1233,12 +1290,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
*
@ -1263,12 +1320,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
List<DeviceStatus> 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
*
@ -1298,7 +1355,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) {
@ -1332,7 +1389,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();
@ -1341,7 +1398,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();
@ -1360,7 +1417,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);
@ -1381,7 +1438,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@GET
@Override
@Path("/type/{type}/status/{status}/count")
@ -1397,7 +1454,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
}
}
@GET
@Override
@Path("/type/{type}/status/{status}/ids")
@ -1413,7 +1470,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
}
}
@PUT
@Override
@Path("/type/{type}/status/{status}")
@ -1429,7 +1486,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).build();
}
@GET
@Override
@Path("/compliance/{complianceStatus}")
@ -1444,15 +1501,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();
@ -1468,7 +1525,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Override
@Path("/{id}/features")
@ -1478,7 +1535,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 {
@ -1491,7 +1548,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Override
@Consumes("application/json")
@ -1511,7 +1568,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();
@ -1532,7 +1589,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/application/{packageName}/versions")
@Override
@ -1548,7 +1605,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
@Path("/{deviceType}/{id}/operation")
@Override
@ -1580,7 +1637,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();
@ -1592,7 +1649,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) {
@ -1606,7 +1663,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/filters")
@Override
@ -1638,7 +1695,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/{clientId}/{clientSecret}/default-token")
@Override

@ -0,0 +1,102 @@
//package org.wso2.carbon.device.mgt.jaxrs.service.impl;
//
//import com.google.api.client.auth.oauth2.Credential;
//import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
//import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
//import com.google.api.client.googleapis.json.GoogleJsonResponseException;
//import com.google.api.client.http.HttpTransport;
//import com.google.api.client.json.JsonFactory;
//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.api.services.sheets.v4.model.AppendValuesResponse;
//import com.google.api.services.sheets.v4.model.ValueRange;
//
//import javax.annotation.PreDestroy;
//import javax.ws.rs.GET;
//import javax.ws.rs.Path;
//import javax.ws.rs.PathParam;
//import javax.ws.rs.Produces;
//import javax.ws.rs.client.Client;
//import javax.ws.rs.client.ClientBuilder;
//import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.Response;
//import java.io.IOException;
//import java.security.GeneralSecurityException;
//import java.util.Collections;
//
//import static org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceAgentServiceImpl.log;
//
//@Path("/pending/operations/{type}/{id}")
//public class PendingOperationsResourceResponseTime {
//
// private final Client client;
// private final Sheets sheetsService;
// private final String spreadsheetId;
// private final String sheetName;
//
// public PendingOperationsResourceResponseTime() throws IOException, GeneralSecurityException {
// this.client = ClientBuilder.newClient();
//
// // Build the credentials object using Google OAuth 2.0 authentication
// Credential credential = GoogleCredential.getApplicationDefault().createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS));
// HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
//
// // Create a Sheets service object to interact with the Google Sheets API
// this.sheetsService = new Sheets.Builder(httpTransport, jsonFactory, credential)
// .setApplicationName("ApiCall")
// .build();
//
// // Set the spreadsheet ID and sheet name to write the results to
// this.spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw";
// this.sheetName = "Sheet1";
// }
//
// @GET
// @Produces(MediaType.APPLICATION_JSON)
// public Response getPendingOperations(@PathParam("type") String type, @PathParam("id") String deviceId) {
// long startTime = System.currentTimeMillis();
// Response apiResponse = client.target("http://example.com/api/pending-operations")
// .queryParam("type", type)
// .queryParam("deviceId", deviceId)
// .request(MediaType.APPLICATION_JSON)
// .get();
// long endTime = System.currentTimeMillis();
// long responseTime = endTime - startTime;
//
// // log the response time
// log.info("API response time: {} ms");
//
// // write the results to Google Sheets
// try {
// writeResultsToSheet(startTime, endTime, responseTime);
// } catch (IOException e) {
// log.error("Error writing results to Google Sheets", e);
// }
//
// return apiResponse;
// }
//
// @PreDestroy
// public void cleanup() {
// client.close();
// }
//
// private void writeResultsToSheet(long startTime, long endTime, long responseTime) throws IOException {
// // create a ValueRange object with the data to write
// ValueRange valueRange = new ValueRange().setValues(Collections.singletonList(
// Collections.singletonList(startTime + "," + endTime + "," + responseTime)));
//
// // append the data to the Google Sheet
// try {
// AppendValuesResponse response = sheetsService.spreadsheets().values()
// .append(spreadsheetId, sheetName, valueRange)
// .setValueInputOption("RAW")
// .execute();
// log.info("Data written to Google Sheets: {}");
// } catch (GoogleJsonResponseException e) {
// log.error("Error writing data to Google Sheets: {}");
// }
// }
//}

@ -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"
}
Loading…
Cancel
Save