Created
April 29, 2014 18:51
-
-
Save joshbirk/11408745 to your computer and use it in GitHub Desktop.
Blog Log CSV Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global class BlogLog_Services implements Messaging.InboundEmailHandler { | |
public BlogLog_Services() {} | |
public Document document { | |
get { | |
if (document == null) | |
document = new Document(); | |
return document; | |
} | |
set; | |
} | |
public PageReference upload() { | |
BlogLog_Services.uploadCSVData(document.body.toString()); | |
return null; | |
} | |
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, | |
Messaging.InboundEnvelope env){ | |
if(email.textAttachments.size() > 0) { | |
Messaging.InboundEmail.TextAttachment csvDoc = email.textAttachments[0]; | |
BlogLog_Services.uploadCSVData(csvDoc.body); | |
} | |
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); | |
result.success = true; | |
return result; | |
} | |
static void uploadCSVData(string csvData) { | |
List<String> csvDataRows = csvData.split('\n'); | |
Map<Id,String> urlCheck = new Map<Id,String>(); | |
Map<String,Integer> pageHitData = new Map<String,Integer>(); | |
Boolean startCount = false; | |
for(String row : csvDataRows) { | |
List<String> data = row.split(','); | |
if(data.size() > 0 && data[0] == '1.') { | |
startCount = true; | |
} | |
if(startCount) { | |
List<String> urlData = data[1].split(':'); | |
if(urlData.size() == 6 && !pageHitData.containsKey(urlData[5])) { pageHitData.put(urlData[5],Integer.valueOf(data[2])); } | |
} | |
} | |
List<Blog_Entry__c> updatedBlogs = new List<Blog_Entry__c>(); | |
for(String url : pageHitData.keySet()) { | |
List<Blog_Entry__c> relatedBlog = [SELECT ID, Page_Hits__c from Blog_Entry__c WHERE Link__c LIKE :'%'+url+'%']; | |
if(relatedBlog.size() == 1) { | |
if(!urlCheck.containsKey(relatedBlog[0].Id)) { | |
relatedBlog[0].Page_Hits__c = pageHitData.get(url); | |
updatedBlogs.add(relatedBlog[0]); | |
} | |
if(urlCheck.containsKey(relatedBlog[0].Id) && pageHitData.get(url) > relatedBlog[0].Page_Hits__c) { | |
for(Blog_Entry__c b : updatedBlogs) { | |
if(b.Id == relatedBlog[0].Id) { b.Page_Hits__c = pageHitData.get(url); } | |
} | |
} | |
urlCheck.put(relatedBlog[0].Id,url); | |
} | |
} | |
update updatedBlogs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment