public class CSVImportController {
public String googleDriveFileId { get; set; }
public void importCSVFromGoogleDrive() {
try {
String accessToken = GoogleAuthService.refreshAccessToken();
if (String.isNotBlank(accessToken)) {
System.debug('Fetching CSV data from Google Drive...');
GoogleDriveIntegration googleDrive = new GoogleDriveIntegration();
String csvData = googleDrive.fetchCSVData(googleDriveFileId,
accessToken);
if (String.isNotBlank(csvData)) {
List<Account> recordsToInsert = new List<Account>();
List<String> csvLines = csvData.split('\n');
List<String> goodCsvLines = new List<String>();
List<String> badCsvLines = new List<String>();
for (Integer i = 1; i < csvLines.size(); i++) {
String[] csvValues = csvLines[i].split(',');
if (csvValues.size() >= 5) {
Account record = new Account();
record.Name = csvValues[0].trim();
record.Customer_Name__c = csvValues[1].trim();
// Process and populate other fields...
recordsToInsert.add(record);
goodCsvLines.add(csvLines[i]); // Collect good data
} else {
badCsvLines.add(csvLines[i]); // Collect bad data
}
}
// Create a new CSV content with the good data
String goodCsvContent = String.join(goodCsvLines, '\n');
String badCsvContent = String.join(badCsvLines, '\n');
// Create an instance of GoogleDriveIntegration
//GoogleDriveIntegration googleDrive = new
GoogleDriveIntegration();
// Upload the bad data CSV to a different folder
googleDrive.uploadBadDataToFolder('1p1ND3kn9cVaBzR1c-1L_r-
Ugj1CLEEsp', 'bad_data.csv', badCsvContent, accessToken);
// Upload the good data CSV to a different folder
googleDrive.uploadDataToFolder(googleDriveFileId,
'1zqZqMnvBszZsCyLwCWjDue1p0HCZyRu3', 'good_data.csv', goodCsvContent, accessToken);
// Create a copy of the original CSV file and move the copy to
the new folder
String copiedFileId =
googleDrive.copyFileAndMove(googleDriveFileId, '1fTFS5sGYzdsT3r0V53A__ywY8fK3AWNS',
accessToken);
if (copiedFileId != null) {
System.debug('Created a copy of the original CSV file and
moved it to the new folder.');
} else {
//System.debug('Failed to create a copy of the original CSV
file or move it to the new folder.');
}
// Insert the records into the custom object
if (!recordsToInsert.isEmpty()) {
insert recordsToInsert;
System.debug('Inserted ' + recordsToInsert.size() + '
records.');
} else {
System.debug('No valid records to insert.');
}
} else {
System.debug('CSV data is blank.');
}
} else {
// Handle the case where access token couldn't be fetched
}
} catch (Exception e) {
// Handle the exception, log error messages, etc.
System.debug('Error importing CSV file: ' + e.getMessage());
}
}
public class GoogleDriveIntegration {
public String fetchCSVData(String fileId, String accessToken) {
try {
HttpRequest req = new HttpRequest();
req.setMethod('GET');
String endpoint = 'https://www.googleapis.com/drive/v3/files/' +
fileId + '?alt=media';
req.setEndpoint(endpoint);
req.setHeader('Authorization', 'Bearer ' + accessToken);
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
return res.getBody();
} else {
// Handle the error response
System.debug('Error fetching CSV data from Google Drive');
System.debug('Response: ' + res.getBody());
return null;
}
} catch (Exception e) {
// Handle the exception
System.debug('Exception while fetching CSV data from Google Drive:
' + e.getMessage());
return null;
}
}
public void uploadDataToFolder(String fileId, String folderId, String
fileName, String content, String accessToken) {
try {
HttpRequest req = new HttpRequest();
req.setMethod('POST'); // Use POST to create a new file
String endpoint =
'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
req.setEndpoint(endpoint);
req.setHeader('Authorization', 'Bearer ' + accessToken);
req.setHeader('Content-Type', 'text/plain');
req.setBody(content);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> responseMap = (Map<String, Object>)
JSON.deserializeUntyped(res.getBody());
String newFileId = (String) responseMap.get('id');
System.debug('Created ' + fileName + ' with ID ' + newFileId);
// Move the new file to the specified folder
String moveEndpoint =
'https://www.googleapis.com/drive/v3/files/' + newFileId + '?addParents=' +
folderId;
HttpRequest moveReq = new HttpRequest();
moveReq.setMethod('PATCH');
moveReq.setEndpoint(moveEndpoint);
moveReq.setHeader('Authorization', 'Bearer ' + accessToken);
HttpResponse moveRes = new Http().send(moveReq);
if (moveRes.getStatusCode() == 200) {
System.debug('Moved ' + fileName + ' to folder ' +
folderId);
// Move the main CSV file to the new folder
String mainFileMoveResult = moveFileToFolder(fileId,
'1fTFS5sGYzdsT3r0V53A__ywY8fK3AWNS', accessToken);
if (mainFileMoveResult.equals('success')) {
System.debug('Moved the main CSV file to the new
folder.');
} else {
System.debug('Failed to move the main CSV file to the
new folder.');
}
} else {
System.debug('Error moving ' + fileName + ' to folder ' +
folderId);
System.debug('Response: ' + moveRes.getBody());
}
} else {
// Handle the error response
System.debug('Error creating ' + fileName + ' in Google
Drive');
System.debug('Response: ' + res.getBody());
}
} catch (Exception e) {
// Handle the exception
System.debug('Exception while creating ' + fileName + ' in Google
Drive: ' + e.getMessage());
}
}
// Fetch parent folders of a file
public String getParentFolders(String fileId, String accessToken) {
try {
HttpRequest req = new HttpRequest();
req.setMethod('GET');
String endpoint = 'https://www.googleapis.com/drive/v3/files/' +
fileId + '?fields=parents';
req.setEndpoint(endpoint);
req.setHeader('Authorization', 'Bearer ' + accessToken);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> responseMap = (Map<String, Object>)
JSON.deserializeUntyped(res.getBody());
List<String> parentFolders = (List<String>)
responseMap.get('parents');
return String.join(parentFolders, ',');
} else {
// Handle the error response
System.debug('Error fetching parent folders for file: ' +
fileId);
System.debug('Response: ' + res.getBody());
return '';
}
} catch (Exception e) {
// Handle the exception
System.debug('Exception while fetching parent folders: ' +
e.getMessage());
return '';
}
}
public String moveFileToFolder(String fileId, String newFolderId, String
accessToken) {
try {
HttpRequest req = new HttpRequest();
req.setMethod('PATCH');
String endpoint = 'https://www.googleapis.com/drive/v3/files/' +
fileId + '?addParents=' + newFolderId + '&removeParents=root';
req.setEndpoint(endpoint);
req.setHeader('Authorization', 'Bearer ' + accessToken);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
System.debug('Moved file ' + fileId + ' to folder ' +
newFolderId);
return 'success';
} else {
System.debug('Error moving file ' + fileId + ' to folder ' +
newFolderId);
System.debug('Response: ' + res.getBody());
return 'error';
}
} catch (Exception e) {
// Handle the exception
System.debug('Exception while moving file ' + fileId + ' to folder
' + newFolderId + ': ' + e.getMessage());
return 'error';
}
}
// Inside the GoogleDriveIntegration class
public String copyFileAndMove(String fileId, String newFolderId, String
accessToken) {
try {
HttpRequest req = new HttpRequest();
req.setMethod('POST');
String endpoint = 'https://www.googleapis.com/drive/v3/files/' +
fileId + '/copy';
req.setEndpoint(endpoint);
req.setHeader('Authorization', 'Bearer ' + accessToken);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> responseMap = (Map<String, Object>)
JSON.deserializeUntyped(res.getBody());
String copiedFileId = (String) responseMap.get('id');
// Move the copied file to the specified folder
String moveResult = moveFileToFolder(copiedFileId, newFolderId,
accessToken);
if (moveResult == 'success') {
System.debug('Copied and moved the file ' + fileId + ' to
folder ' + newFolderId);
return copiedFileId;
} else {
System.debug('Failed to move the copied file to folder ' +
newFolderId);
return null;
}
} else {
System.debug('Error copying file ' + fileId);
//System.debug('Response: ' + res.getBody());
return null;
}
} catch (Exception e) {
// Handle the exception
System.debug('Exception while copying and moving file ' + fileId +
' to folder ' + newFolderId + ': ' + e.getMessage());
return null;
}
}
public void uploadBadDataToFolder(String folderId, String fileName, String
content, String accessToken) {
try {
HttpRequest req = new HttpRequest();
req.setMethod('POST'); // Use POST to create a new file
String endpoint =
'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
req.setEndpoint(endpoint);
req.setHeader('Authorization', 'Bearer ' + accessToken);
req.setHeader('Content-Type', 'text/plain');
req.setBody(content);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> responseMap = (Map<String, Object>)
JSON.deserializeUntyped(res.getBody());
String newFileId = (String) responseMap.get('id');
System.debug('Created ' + fileName + ' with ID ' + newFileId);
// Move the new file to the specified folder
String moveEndpoint =
'https://www.googleapis.com/drive/v3/files/' + newFileId + '?addParents=' +
folderId;
HttpRequest moveReq = new HttpRequest();
moveReq.setMethod('PATCH');
moveReq.setEndpoint(moveEndpoint);
moveReq.setHeader('Authorization', 'Bearer ' + accessToken);
HttpResponse moveRes = new Http().send(moveReq);
if (moveRes.getStatusCode() == 200) {
System.debug('Moved ' + fileName + ' to folder ' +
folderId);
} else {
System.debug('Error moving ' + fileName + ' to folder ' +
folderId);
System.debug('Response: ' + moveRes.getBody());
}
} else {
// Handle the error response
System.debug('Error creating ' + fileName + ' in Google
Drive');
System.debug('Response: ' + res.getBody());
}
} catch (Exception e) {
// Handle the exception
System.debug('Exception while creating ' + fileName + ' in Google
Drive: ' + e.getMessage());
}
}
}
}