/** Description : Ths class will Integrate Salesforce with Klout.
**/
public with sharing class KloutWithSalesforceTwitterRatingUpdate {
//Wrapper Class for First Response
public class firstResponseParsingWrapper {
//Response variables
public String id;
public String network;
//Constructor
public firstResponseParsingWrapper(String id, String network) {
this.id = id;
this.network = network;
}
}
//Wrapper for second response
public class KloutFinalResponseWrapper {
//Score from the response
public String score;
//Constructor
public KloutFinalResponseWrapper(String score) {
this.score = score;
}
}
//account
public Account account { get; set; }
public String twitterScore { get; set; }
//constructor
public KloutWithSalesforceTwitterRatingUpdate(ApexPages.StandardController stdController){
//Initiallize
twitterScore = '';
//account record
this.account = (Account)stdController.getRecord();
}
//Method for making callout and populating values retrieved from response is going to be diplayed on Visualforce Page
public void kloutTwitterRating() {
try {
//Http
Http http = new Http();
//Request
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api.klout.com/v2/identity.json/twitter?screenName='+ twitterScore +'&key=4j6pe8zamj4dmh2by9tzv5sc');
req.setMethod('GET');
//Send request
HTTPResponse firstResponse = http.send(req);
System.debug('res::::::' + firstResponse.getBody());
//Body
String body = firstResponse.getBody();
//Deserializing response
KloutWithSalesforceTwitterRatingUpdate.firstResponseParsingWrapper parsedResponse = (KloutWithSalesforceTwitterRatingUpdate.firstResponseParsingWrapper)JSON.deserialize(body, firstResponseParsingWrapper.class);
System.debug('parsedResponse:::::::' + parsedResponse);
//String for id in response
String responseId = parsedResponse.id;
System.debug('responseId:::::::' + responseId);
//Second request for score
HttpRequest finalReq = new HttpRequest();
finalReq.setEndpoint('http://api.klout.com/v2/user.json/'+ responseId +'/score?key=4j6pe8zamj4dmh2by9tzv5sc');
finalReq.setMethod('GET');
//Send request
HTTPResponse lastResponse = http.send(finalReq);
System.debug('lastResponse::::::' + lastResponse.getBody());
//Body
String finalBody = lastResponse.getBody();
//Deserializing response
KloutWithSalesforceTwitterRatingUpdate.KloutFinalResponseWrapper parseFinalResponse = (KloutWithSalesforceTwitterRatingUpdate.KloutFinalResponseWrapper)JSON.deserialize(finalBody, KloutFinalResponseWrapper.class);
System.debug('parseFinalResponse::::::' + parseFinalResponse);
//Assigning value
account.Twitter_Rating__c = parseFinalResponse.score;
account.Validate_Score_Successfully__c = true;
account.Validate_Score_Last_Attempt__c = date.today();
}catch (exception e) {
//Error messages
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'UserName Not Found, Sorry Try Again');
ApexPages.addMessage(errormsg);
System.debug('e:::::::' + e);
}
}
}
No comments:
Post a Comment