0% found this document useful (0 votes)
2 views

importDataFromCSVController

The document outlines a Salesforce Apex class designed to import data from CSV files stored in Google Drive. It includes methods for fetching files, processing CSV data into Account objects, and handling authentication with Google APIs. The class uses a future method for asynchronous processing and manages access tokens dynamically for secure API calls.

Uploaded by

bikram115566
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

importDataFromCSVController

The document outlines a Salesforce Apex class designed to import data from CSV files stored in Google Drive. It includes methods for fetching files, processing CSV data into Account objects, and handling authentication with Google APIs. The class uses a future method for asynchronous processing and manages access tokens dynamically for secure API calls.

Uploaded by

bikram115566
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

public class importDataFromCSVController {

private String clientId = '93701334664-


soqqm4cojb4rfn915hakjhjal8k697rd.apps.googleusercontent.com';
private String clientSecret = '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';
private String redirectUrl =
'https://drive.google.com/drive/u/0/folders/155Spx4tNEnRfziX6F2Whx11EzAwA-gjX';
public String accessToken { get; set; }
public Blob csvFileBody { get; set; }
public String csvAsString { get; set; }
public String[] csvFileLines { get; set; }
public List<Account> accountList { get; set; }

@future(callout=true)
public static void fetchAndProcessFilesFromGoogleDrive() {
try {
importDataFromCSVController controllerInstance = new
importDataFromCSVController();
controllerInstance.getFilesFromGoogleDrive();
} catch (Exception e) {
System.debug('Exception in fetchAndProcessFilesFromGoogleDrive: ' +
e.getMessage());
}
}
public importDataFromCSVController() {
csvFileLines = new String[]{};
accountList = new List<Account>();
refreshToken(); // Fetch the access token dynamically
}
private void refreshToken() {
accessToken = GoogleAuthService.refreshAccessToken(); // Fetch access token
dynamically
}
public void importCSVFile() {
try {
csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');

for (Integer i = 1; i < csvFileLines.size(); i++) {


String[] csvRecordData = csvFileLines[i].split(',');
if (csvRecordData.size() >= 5) {
Account accObj = new Account();
accObj.Name = csvRecordData[0].trim();
accObj.AccountNumber = csvRecordData[1].trim();
accObj.Type = csvRecordData[2].trim();
accObj.AccountSource = csvRecordData[3].trim();
accObj.Industry = csvRecordData[4].trim();
accountList.add(accObj);
} else {
System.debug('Skipping CSV line due to incomplete data: ' +
csvFileLines[i]);
}
}

if (!accountList.isEmpty()) {
insert accountList;
}
} catch (Exception e) {
ApexPages.Message errorMessage = new
ApexPages.Message(ApexPages.Severity.ERROR, 'An error occurred while importing
data. Please check the CSV file and try again.');
ApexPages.addMessage(errorMessage);
System.debug('Error importing CSV file: ' + e.getMessage());
}
}

// Define the set outside of the method, possibly in your class


Set<String> processedFiles = new Set<String>();

public void getFilesFromGoogleDrive() {


try {
String accessToken = GoogleAuthService.refreshAccessToken();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://www.googleapis.com/drive/v3/files');
req.setHeader('Authorization', 'Bearer ' + accessToken); // Use the
dynamically fetched access token
Http http = new Http();
HttpResponse res = http.send(req);

if (res.getStatusCode() == 200) {
String responseBody = res.getBody();
Map<String, Object> responseMap = (Map<String, Object>)
JSON.deserializeUntyped(responseBody);
List<Object> files = (List<Object>) responseMap.get('files');

if (files != null && !files.isEmpty()) {


for (Object fileObj : files) {
Map<String, Object> file = (Map<String, Object>) fileObj;
String fileId = (String) file.get('id');
String fileName = (String) file.get('name');
String mimeType = (String) file.get('mimeType');

// Now you can use the fileId to fetch the content of the file
if needed
System.debug('File ID: ' + fileId + ', File Name: ' + fileName
+ ', Mime Type: ' + mimeType);

if (mimeType == 'text/csv') {
System.debug('### File ID: ' + fileId);
System.debug('### File Name: ' + fileName);
if (!processedFiles.contains(fileId)) {
processCSVFile(fileId);
processedFiles.add(fileId);
} else {
System.debug('File ID ' + fileId + ' has already been
processed.');
}
}
}

if (processedFiles.isEmpty()) {
// throw new CustomException('No unprocessed CSV files found.');
}
} else {
System.debug('No files found in Google Drive.');
}
} else {
System.debug('Error fetching files from Google Drive');
}
} catch (Exception e) {
System.debug('Exception in getFilesFromGoogleDrive: ' + e.getMessage());
}
}

// Method to process a CSV file


private void processCSVFile(String fileId) {
CSVImportController controller = new CSVImportController();
controller.googleDriveFileId = fileId;
controller.importCSVFromGoogleDrive();
}

public void getFiles(string fileId) {


CSVImportController controller = new CSVImportController();
controller.googleDriveFileId = fileId;
controller.importCSVFromGoogleDrive();
}
}

You might also like