Update DeviceAgentServiceImpl file with response time

pull/1/head
Akeela Azhar 2 years ago
parent d0dbceebd3
commit c083fc7b11

@ -470,5 +470,10 @@
<artifactId>google-http-client-jackson2</artifactId> <artifactId>google-http-client-jackson2</artifactId>
<version>1.43.1</version> <version>1.43.1</version>
</dependency> </dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-terracotta</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -18,6 +18,18 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl; 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.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.*;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -63,9 +75,7 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
@Path("/device/agent") @Path("/device/agent")
public class DeviceAgentServiceImpl implements DeviceAgentService { public class DeviceAgentServiceImpl implements DeviceAgentService {
@ -433,22 +443,61 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(msg); log.error(msg);
return Response.status(Response.Status.NO_CONTENT).entity(msg).build(); 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( List<? extends Operation> operations = DeviceMgtAPIUtils.getDeviceManagementService().getPendingOperations(
deviceIdentifier); deviceIdentifier);
OperationList operationsList = new OperationList(); OperationList operationsList = new OperationList();
operationsList.setList(operations); operationsList.setList(operations);
operationsList.setCount(operations.size()); operationsList.setCount(operations.size());
long endTime = System.currentTimeMillis(); // Record the end time
long responseTime = endTime - startTime; // Calculate the response time
// Save the response time to Google Spreadsheet
Sheets sheetsService = createSheetsService(); // Create Sheets service using loaded credentials
String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; // Replace with the actual spreadsheet ID
// Create the values to be written
List<List<Object>> values = Arrays.asList(
Arrays.asList(deviceId, String.valueOf(responseTime))
);
// Create the value range
ValueRange body = new ValueRange().setValues(values);
// Write the values to the spreadsheet
sheetsService.spreadsheets().values()
.append(spreadsheetId, "Sheet1", body)
.setValueInputOption("USER_ENTERED")
.execute();
return Response.status(Response.Status.OK).entity(operationsList).build(); return Response.status(Response.Status.OK).entity(operationsList).build();
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String errorMessage = "Issue in retrieving operation management service instance"; String errorMessage = "Issue in retrieving operation management service instance";
log.error(errorMessage, e); log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} catch (DeviceManagementException e) { } 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();
}catch (IOException e) {
// Handle any errors occurred while writing to the spreadsheet
String errorMessage = "Error writing response time to Google Spreadsheet";
log.error(errorMessage, e); log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} }
} }
private Sheets createSheetsService() throws IOException {
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("components/device-mgt/org.wso2.carbon.device.mgt.api/target/apicall-382608-48aa6a62800d.json"))
.createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS));
try {
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential)
.setApplicationName("ApiCall")
.build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
@GET @GET
@Path("/next-pending/operation/{type}/{id}") @Path("/next-pending/operation/{type}/{id}")

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