From a668d3e364a61f275e756b417ea23907d0cf61b6 Mon Sep 17 00:00:00 2001 From: Pahansith Gunathilake Date: Wed, 19 Apr 2023 06:46:09 +0000 Subject: [PATCH 1/7] Fix issue with Nginx not recognizing the SCEP client certificate (#105) Co-authored-by: Pahansith Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/105 Co-authored-by: Pahansith Gunathilake Co-committed-by: Pahansith Gunathilake --- .../mgt/core/impl/CertificateGenerator.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index 20b4833d56..d686ff5115 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -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=" + -- 2.36.3 From 37bef26862a632632bbfe5088ca87378e6a72947 Mon Sep 17 00:00:00 2001 From: akeela_azhar Date: Wed, 10 May 2023 13:17:22 +0530 Subject: [PATCH 2/7] Add Google sheet response time files --- .../org.wso2.carbon.device.mgt.api/pom.xml | 10 ++ .../jaxrs/service/impl/ApiResponseTime.java | 108 ++++++++++++++++++ .../mgt/jaxrs/service/impl/GoogleSheet.java | 34 ++++++ 3 files changed, 152 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index 7077d97672..fe2e75c0da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -455,5 +455,15 @@ io.entgra.device.mgt.core.apimgt.analytics.extension provided + + com.google.api-client + google-api-client + 2.2.0 + + + com.google.apis + google-api-services-sheets + v4-rev539-1.25.0 + \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java new file mode 100644 index 0000000000..021bbaf559 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java @@ -0,0 +1,108 @@ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.services.sheets.v4.Sheets; +import com.google.api.services.sheets.v4.model.AppendValuesResponse; +import com.google.api.services.sheets.v4.model.ValueRange; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.osgi.service.application.ApplicationDescriptor.APPLICATION_NAME; +import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.JSON_FACTORY; +import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.getCredentials; + +@SuppressWarnings("ALL") +@RestController +public class ApiResponseTime { + + public static Object getstartTime() { + return null; + } + + public static Object getendTime() { + return null; + } + + public static Object getelapsedTime() { + return null; + } + + public static void appendDetails(long startTime, long endTime, long elapsedTime) + throws GeneralSecurityException, IOException, URISyntaxException { + final String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + + Sheets service = + new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); + + // Create a list of values to append to the sheet + List newList1 = new ArrayList<>(Arrays.asList(startTime, endTime, elapsedTime)); + List> values = new ArrayList<>(Arrays.asList(newList1)); + + // Append the values to the sheet + AppendValuesResponse result = null; + try { + ValueRange valueRange = new ValueRange().setValues(values); + result = service.spreadsheets().values().append(spreadsheetId, "A2", valueRange) + .setValueInputOption("RAW").execute(); + System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells()); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (((GoogleJsonError) error).getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } + } + } + + @GetMapping("/my-api") + public String myApi() { + // Set the URL for the API call + String url = "/next-pending/operation/{type}/{id}"; + + try { + // Record the start time + long startTime = System.currentTimeMillis(); + + // Make the API call using the RestTemplate + RestTemplate restTemplate = new RestTemplate(); + String response = restTemplate.getForObject(url, String.class); + + // Record the end time + long endTime = System.currentTimeMillis(); + + // Calculate the elapsed time + long elapsedTime = endTime - startTime; + + // Print the elapsed time in milliseconds + System.out.println("Start Time: " + startTime + " ms"); + System.out.println("End Time: " + endTime + " ms"); + System.out.println("Elapsed time: " + elapsedTime + " ms"); + + // Append the API call details to a Google Sheet + appendDetails(startTime, endTime, elapsedTime); + + return response; + + } catch (Exception e) { + e.printStackTrace(); + return "Error occurred: " + e.getMessage(); + } + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java new file mode 100644 index 0000000000..ce70894d11 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java @@ -0,0 +1,34 @@ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.sheets.v4.SheetsScopes; + +import java.io.File; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class GoogleSheet { + + private static final String APPLICATION_NAME = "ApiCall"; + static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String TOKENS_DIRECTORY_PATH = "tokens/path"; + private static final List SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE); + + static GoogleCredential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException, GeneralSecurityException { + GoogleCredential credential = new GoogleCredential.Builder() + .setTransport(HTTP_TRANSPORT) + .setJsonFactory(JSON_FACTORY) + .setServiceAccountId("apicall@apicall-382608.iam.gserviceaccount.com") + .setServiceAccountPrivateKeyFromP12File(new File("/home/entgra/MyProject/device-mgt-core/components/device-mgt/org.wso2.carbon.device.mgt.api/target/credentials.p12")).setServiceAccountScopes(Collections.singleton(SheetsScopes.SPREADSHEETS)).build(); + credential.refreshToken(); + return credential; + } + +} -- 2.36.3 From be786e1a78f36f4a7b338abcd2777d4e7e98ff8b Mon Sep 17 00:00:00 2001 From: akeela_azhar Date: Fri, 12 May 2023 11:54:18 +0530 Subject: [PATCH 3/7] Update Google sheet response time files --- .../org.wso2.carbon.device.mgt.api/pom.xml | 5 + .../jaxrs/service/impl/ApiResponseTime.java | 216 +++++++++--------- .../service/impl/DeviceAgentServiceImpl.java | 2 +- .../mgt/jaxrs/service/impl/GoogleSheet.java | 68 +++--- ...PendingOperationsResourceResponseTime.java | 102 +++++++++ 5 files changed, 250 insertions(+), 143 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index fe2e75c0da..b859b99db7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -465,5 +465,10 @@ google-api-services-sheets v4-rev539-1.25.0 + + com.google.http-client + google-http-client-jackson2 + 1.43.1 + \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java index 021bbaf559..65d9a46bb2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java @@ -1,108 +1,108 @@ -package org.wso2.carbon.device.mgt.jaxrs.service.impl; - - -import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.javanet.NetHttpTransport; -import com.google.api.services.sheets.v4.Sheets; -import com.google.api.services.sheets.v4.model.AppendValuesResponse; -import com.google.api.services.sheets.v4.model.ValueRange; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.osgi.service.application.ApplicationDescriptor.APPLICATION_NAME; -import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.JSON_FACTORY; -import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.getCredentials; - -@SuppressWarnings("ALL") -@RestController -public class ApiResponseTime { - - public static Object getstartTime() { - return null; - } - - public static Object getendTime() { - return null; - } - - public static Object getelapsedTime() { - return null; - } - - public static void appendDetails(long startTime, long endTime, long elapsedTime) - throws GeneralSecurityException, IOException, URISyntaxException { - final String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - - Sheets service = - new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); - - // Create a list of values to append to the sheet - List newList1 = new ArrayList<>(Arrays.asList(startTime, endTime, elapsedTime)); - List> values = new ArrayList<>(Arrays.asList(newList1)); - - // Append the values to the sheet - AppendValuesResponse result = null; - try { - ValueRange valueRange = new ValueRange().setValues(values); - result = service.spreadsheets().values().append(spreadsheetId, "A2", valueRange) - .setValueInputOption("RAW").execute(); - System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells()); - } catch (GoogleJsonResponseException e) { - GoogleJsonError error = e.getDetails(); - if (((GoogleJsonError) error).getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); - } else { - throw e; - } - } - } - - @GetMapping("/my-api") - public String myApi() { - // Set the URL for the API call - String url = "/next-pending/operation/{type}/{id}"; - - try { - // Record the start time - long startTime = System.currentTimeMillis(); - - // Make the API call using the RestTemplate - RestTemplate restTemplate = new RestTemplate(); - String response = restTemplate.getForObject(url, String.class); - - // Record the end time - long endTime = System.currentTimeMillis(); - - // Calculate the elapsed time - long elapsedTime = endTime - startTime; - - // Print the elapsed time in milliseconds - System.out.println("Start Time: " + startTime + " ms"); - System.out.println("End Time: " + endTime + " ms"); - System.out.println("Elapsed time: " + elapsedTime + " ms"); - - // Append the API call details to a Google Sheet - appendDetails(startTime, endTime, elapsedTime); - - return response; - - } catch (Exception e) { - e.printStackTrace(); - return "Error occurred: " + e.getMessage(); - } - } -} - +//package org.wso2.carbon.device.mgt.jaxrs.service.impl; +// +// +//import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +//import com.google.api.client.googleapis.json.GoogleJsonError; +//import com.google.api.client.googleapis.json.GoogleJsonResponseException; +//import com.google.api.client.http.javanet.NetHttpTransport; +//import com.google.api.services.sheets.v4.Sheets; +//import com.google.api.services.sheets.v4.model.AppendValuesResponse; +//import com.google.api.services.sheets.v4.model.ValueRange; +//import org.springframework.web.bind.annotation.GetMapping; +//import org.springframework.web.bind.annotation.RestController; +//import org.springframework.web.client.RestTemplate; +// +//import java.io.IOException; +//import java.net.URISyntaxException; +//import java.security.GeneralSecurityException; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.List; +// +//import static org.osgi.service.application.ApplicationDescriptor.APPLICATION_NAME; +//import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.JSON_FACTORY; +//import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.getCredentials; +// +//@SuppressWarnings("ALL") +//@RestController +//public class ApiResponseTime { +// +// public static Object getstartTime() { +// return null; +// } +// +// public static Object getendTime() { +// return null; +// } +// +// public static Object getelapsedTime() { +// return null; +// } +// +// public static void appendDetails(long startTime, long endTime, long elapsedTime) +// throws GeneralSecurityException, IOException, URISyntaxException { +// final String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; +// final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); +// +// Sheets service = +// new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) +// .setApplicationName(APPLICATION_NAME) +// .build(); +// +// // Create a list of values to append to the sheet +// List newList1 = new ArrayList<>(Arrays.asList(startTime, endTime, elapsedTime)); +// List> values = new ArrayList<>(Arrays.asList(newList1)); +// +// // Append the values to the sheet +// AppendValuesResponse result = null; +// try { +// ValueRange valueRange = new ValueRange().setValues(values); +// result = service.spreadsheets().values().append(spreadsheetId, "A2", valueRange) +// .setValueInputOption("RAW").execute(); +// System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells()); +// } catch (GoogleJsonResponseException e) { +// GoogleJsonError error = e.getDetails(); +// if (((GoogleJsonError) error).getCode() == 404) { +// System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); +// } else { +// throw e; +// } +// } +// } +// +// @GetMapping("/my-api") +// public String myApi() { +// // Set the URL for the API call +// String url = "/next-pending/operation/{type}/{id}"; +// +// try { +// // Record the start time +// long startTime = System.currentTimeMillis(); +// +// // Make the API call using the RestTemplate +// RestTemplate restTemplate = new RestTemplate(); +// String response = restTemplate.getForObject(url, String.class); +// +// // Record the end time +// long endTime = System.currentTimeMillis(); +// +// // Calculate the elapsed time +// long elapsedTime = endTime - startTime; +// +// // Print the elapsed time in milliseconds +// System.out.println("Start Time: " + startTime + " ms"); +// System.out.println("End Time: " + endTime + " ms"); +// System.out.println("Elapsed time: " + elapsedTime + " ms"); +// +// // Append the API call details to a Google Sheet +// appendDetails(startTime, endTime, elapsedTime); +// +// return response; +// +// } catch (Exception e) { +// e.printStackTrace(); +// return "Error occurred: " + e.getMessage(); +// } +// } +//} +// diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java index ed57498164..774316c0d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -69,7 +69,7 @@ import java.util.Map; @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"; @POST @Path("/enroll") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java index ce70894d11..c3bb8bb306 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java @@ -1,34 +1,34 @@ -package org.wso2.carbon.device.mgt.jaxrs.service.impl; - -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.http.javanet.NetHttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.gson.GsonFactory; -import com.google.api.services.sheets.v4.SheetsScopes; - -import java.io.File; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class GoogleSheet { - - private static final String APPLICATION_NAME = "ApiCall"; - static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - private static final String TOKENS_DIRECTORY_PATH = "tokens/path"; - private static final List SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE); - - static GoogleCredential getCredentials(final NetHttpTransport HTTP_TRANSPORT) - throws IOException, GeneralSecurityException { - GoogleCredential credential = new GoogleCredential.Builder() - .setTransport(HTTP_TRANSPORT) - .setJsonFactory(JSON_FACTORY) - .setServiceAccountId("apicall@apicall-382608.iam.gserviceaccount.com") - .setServiceAccountPrivateKeyFromP12File(new File("/home/entgra/MyProject/device-mgt-core/components/device-mgt/org.wso2.carbon.device.mgt.api/target/credentials.p12")).setServiceAccountScopes(Collections.singleton(SheetsScopes.SPREADSHEETS)).build(); - credential.refreshToken(); - return credential; - } - -} +//package org.wso2.carbon.device.mgt.jaxrs.service.impl; +// +//import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +//import com.google.api.client.http.javanet.NetHttpTransport; +//import com.google.api.client.json.JsonFactory; +//import com.google.api.client.json.gson.GsonFactory; +//import com.google.api.services.sheets.v4.SheetsScopes; +// +//import java.io.File; +//import java.io.IOException; +//import java.security.GeneralSecurityException; +//import java.util.Arrays; +//import java.util.Collections; +//import java.util.List; +// +//public class GoogleSheet { +// +// private static final String APPLICATION_NAME = "ApiCall"; +// static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); +// private static final String TOKENS_DIRECTORY_PATH = "tokens/path"; +// private static final List SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE); +// +// static GoogleCredential getCredentials(final NetHttpTransport HTTP_TRANSPORT) +// throws IOException, GeneralSecurityException { +// GoogleCredential credential = new GoogleCredential.Builder() +// .setTransport(HTTP_TRANSPORT) +// .setJsonFactory(JSON_FACTORY) +// .setServiceAccountId("apicall@apicall-382608.iam.gserviceaccount.com") +// .setServiceAccountPrivateKeyFromP12File(new File("/home/entgra/MyProject/device-mgt-core/components/device-mgt/org.wso2.carbon.device.mgt.api/target/credentials.p12")).setServiceAccountScopes(Collections.singleton(SheetsScopes.SPREADSHEETS)).build(); +// credential.refreshToken(); +// return credential; +// } +// +//} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java new file mode 100644 index 0000000000..516efe6ed2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java @@ -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: {}"); + } + } +} \ No newline at end of file -- 2.36.3 From d0dbceebd36e0e799e75b7adfd1d049803862e8b Mon Sep 17 00:00:00 2001 From: akeela_azhar Date: Tue, 23 May 2023 12:07:28 +0530 Subject: [PATCH 4/7] Update Google sheet response time files --- .../jaxrs/service/impl/ApiResponseTime.java | 108 ------------------ .../mgt/jaxrs/service/impl/GoogleSheet.java | 34 ------ 2 files changed, 142 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java deleted file mode 100644 index 65d9a46bb2..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ApiResponseTime.java +++ /dev/null @@ -1,108 +0,0 @@ -//package org.wso2.carbon.device.mgt.jaxrs.service.impl; -// -// -//import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; -//import com.google.api.client.googleapis.json.GoogleJsonError; -//import com.google.api.client.googleapis.json.GoogleJsonResponseException; -//import com.google.api.client.http.javanet.NetHttpTransport; -//import com.google.api.services.sheets.v4.Sheets; -//import com.google.api.services.sheets.v4.model.AppendValuesResponse; -//import com.google.api.services.sheets.v4.model.ValueRange; -//import org.springframework.web.bind.annotation.GetMapping; -//import org.springframework.web.bind.annotation.RestController; -//import org.springframework.web.client.RestTemplate; -// -//import java.io.IOException; -//import java.net.URISyntaxException; -//import java.security.GeneralSecurityException; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.List; -// -//import static org.osgi.service.application.ApplicationDescriptor.APPLICATION_NAME; -//import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.JSON_FACTORY; -//import static org.wso2.carbon.device.mgt.jaxrs.service.impl.GoogleSheet.getCredentials; -// -//@SuppressWarnings("ALL") -//@RestController -//public class ApiResponseTime { -// -// public static Object getstartTime() { -// return null; -// } -// -// public static Object getendTime() { -// return null; -// } -// -// public static Object getelapsedTime() { -// return null; -// } -// -// public static void appendDetails(long startTime, long endTime, long elapsedTime) -// throws GeneralSecurityException, IOException, URISyntaxException { -// final String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; -// final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); -// -// Sheets service = -// new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) -// .setApplicationName(APPLICATION_NAME) -// .build(); -// -// // Create a list of values to append to the sheet -// List newList1 = new ArrayList<>(Arrays.asList(startTime, endTime, elapsedTime)); -// List> values = new ArrayList<>(Arrays.asList(newList1)); -// -// // Append the values to the sheet -// AppendValuesResponse result = null; -// try { -// ValueRange valueRange = new ValueRange().setValues(values); -// result = service.spreadsheets().values().append(spreadsheetId, "A2", valueRange) -// .setValueInputOption("RAW").execute(); -// System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells()); -// } catch (GoogleJsonResponseException e) { -// GoogleJsonError error = e.getDetails(); -// if (((GoogleJsonError) error).getCode() == 404) { -// System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); -// } else { -// throw e; -// } -// } -// } -// -// @GetMapping("/my-api") -// public String myApi() { -// // Set the URL for the API call -// String url = "/next-pending/operation/{type}/{id}"; -// -// try { -// // Record the start time -// long startTime = System.currentTimeMillis(); -// -// // Make the API call using the RestTemplate -// RestTemplate restTemplate = new RestTemplate(); -// String response = restTemplate.getForObject(url, String.class); -// -// // Record the end time -// long endTime = System.currentTimeMillis(); -// -// // Calculate the elapsed time -// long elapsedTime = endTime - startTime; -// -// // Print the elapsed time in milliseconds -// System.out.println("Start Time: " + startTime + " ms"); -// System.out.println("End Time: " + endTime + " ms"); -// System.out.println("Elapsed time: " + elapsedTime + " ms"); -// -// // Append the API call details to a Google Sheet -// appendDetails(startTime, endTime, elapsedTime); -// -// return response; -// -// } catch (Exception e) { -// e.printStackTrace(); -// return "Error occurred: " + e.getMessage(); -// } -// } -//} -// diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java deleted file mode 100644 index c3bb8bb306..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GoogleSheet.java +++ /dev/null @@ -1,34 +0,0 @@ -//package org.wso2.carbon.device.mgt.jaxrs.service.impl; -// -//import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -//import com.google.api.client.http.javanet.NetHttpTransport; -//import com.google.api.client.json.JsonFactory; -//import com.google.api.client.json.gson.GsonFactory; -//import com.google.api.services.sheets.v4.SheetsScopes; -// -//import java.io.File; -//import java.io.IOException; -//import java.security.GeneralSecurityException; -//import java.util.Arrays; -//import java.util.Collections; -//import java.util.List; -// -//public class GoogleSheet { -// -// private static final String APPLICATION_NAME = "ApiCall"; -// static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); -// private static final String TOKENS_DIRECTORY_PATH = "tokens/path"; -// private static final List SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE); -// -// static GoogleCredential getCredentials(final NetHttpTransport HTTP_TRANSPORT) -// throws IOException, GeneralSecurityException { -// GoogleCredential credential = new GoogleCredential.Builder() -// .setTransport(HTTP_TRANSPORT) -// .setJsonFactory(JSON_FACTORY) -// .setServiceAccountId("apicall@apicall-382608.iam.gserviceaccount.com") -// .setServiceAccountPrivateKeyFromP12File(new File("/home/entgra/MyProject/device-mgt-core/components/device-mgt/org.wso2.carbon.device.mgt.api/target/credentials.p12")).setServiceAccountScopes(Collections.singleton(SheetsScopes.SPREADSHEETS)).build(); -// credential.refreshToken(); -// return credential; -// } -// -//} -- 2.36.3 From c083fc7b114774414111a9cfaa8df818d732ba9f Mon Sep 17 00:00:00 2001 From: akeela_azhar Date: Wed, 24 May 2023 13:17:58 +0530 Subject: [PATCH 5/7] Update DeviceAgentServiceImpl file with response time --- .../org.wso2.carbon.device.mgt.api/pom.xml | 5 + .../service/impl/DeviceAgentServiceImpl.java | 55 ++++- ...PendingOperationsResourceResponseTime.java | 204 +++++++++--------- 3 files changed, 159 insertions(+), 105 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index b859b99db7..8e36f72c2f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -470,5 +470,10 @@ google-http-client-jackson2 1.43.1 + + net.sf.ehcache + ehcache-terracotta + 2.1.1 + \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java index 774316c0d7..d53d7f54c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -18,6 +18,18 @@ */ 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.JsonArray; import com.google.gson.JsonElement; @@ -63,9 +75,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import java.rmi.RemoteException; -import java.util.ArrayList; import java.util.List; -import java.util.Map; @Path("/device/agent") public class DeviceAgentServiceImpl implements DeviceAgentService { @@ -433,22 +443,61 @@ 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 operations = DeviceMgtAPIUtils.getDeviceManagementService().getPendingOperations( deviceIdentifier); OperationList operationsList = new OperationList(); operationsList.setList(operations); 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> 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(); } 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(); + }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); 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 @Path("/next-pending/operation/{type}/{id}") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java index 516efe6ed2..1b8a7d2a53 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PendingOperationsResourceResponseTime.java @@ -1,102 +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: {}"); - } - } -} \ No newline at end of file +//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: {}"); +// } +// } +//} \ No newline at end of file -- 2.36.3 From 1334a3eae967d37c02f79bbfcc91fddd4acca8fe Mon Sep 17 00:00:00 2001 From: akeela_azhar Date: Wed, 24 May 2023 13:19:11 +0530 Subject: [PATCH 6/7] Update DeviceAgentServiceImpl file with response time --- .../service/impl/DeviceAgentServiceImpl.java | 59 ++++++++----------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java index d53d7f54c9..82c407082a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -23,13 +23,7 @@ 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.api.services.sheets.v4.model.ValueRange; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -66,21 +60,19 @@ 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.io.FileInputStream; +import java.io.IOException; import java.rmi.RemoteException; -import java.util.List; +import java.security.GeneralSecurityException; +import java.util.*; @Path("/device/agent") public class DeviceAgentServiceImpl implements DeviceAgentService { static final Log log = LogFactory.getLog(DeviceAgentServiceImpl.class); private static final String POLICY_MONITOR = "POLICY_MONITOR"; + @POST @Path("/enroll") @Override @@ -137,7 +129,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 + "'"; @@ -173,7 +165,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; @@ -189,25 +181,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; @@ -247,7 +239,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) { @@ -291,7 +283,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(); @@ -347,7 +339,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) { @@ -392,7 +384,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(); @@ -459,7 +451,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; // Replace with the actual spreadsheet ID // Create the values to be written - List> values = Arrays.asList( + List> values = Collections.singletonList( Arrays.asList(deviceId, String.valueOf(responseTime)) ); @@ -480,13 +472,14 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { 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) { + } 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); 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)); @@ -579,14 +572,14 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { @PUT @Path("/properties/{type}/{id}") public Response updateDeviceProperties(@PathParam("type") String type, @PathParam("id") String deviceId, - @Valid List properties) { + @Valid List 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(); @@ -598,7 +591,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { 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(); @@ -644,7 +637,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { } private static List getComplianceFeatures(Object compliancePayload) throws - PolicyComplianceException { + PolicyComplianceException { String compliancePayloadString = new Gson().toJson(compliancePayload); if (compliancePayload == null) { return null; -- 2.36.3 From f4a954b147fb0d26b978b0b8fc7297b3ee4b3869 Mon Sep 17 00:00:00 2001 From: akeela_azhar Date: Wed, 24 May 2023 13:23:48 +0530 Subject: [PATCH 7/7] Update DeviceAgentServiceImpl file with response time --- .../device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java index 82c407082a..34b4f3bc83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -448,7 +448,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { // 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 + String spreadsheetId = "1OZCS5NRwwSum9ai3ra4lABtU0UGW-9yLYgZk-aQfxpw"; // Create the values to be written List> values = Collections.singletonList( -- 2.36.3