• iRitesh
  • NEWBIE
  • 0 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 3
    Replies

i write a visualforce page with code

{!$Api.Session_ID}

 

i copied the session Id.and used curl and run the command

 curl --header "Authorization : Bearer 00D90000000oX2G!AR8AQF4bfKL.F59U3YiDpt3WY5McM6lhzPhoQzTgkpuBUi1gbEMFXlWgCfq4QmufGh.Zw.VlGN4HCCG0S93qlcy671cQ6xcG" https://mydevorg-dev-ed--c.salesforce.com/services/data/v29.0/

and getting error bash:

!AR8AQF4bfKL.F59U3YiDpt3WY5McM6lhzPhoQzTgkpuBUi1gbEMFXlWgCfq4QmufGh.Zw.VlGN4HCCG0S93qlcy671cQ6xcG": event not found

then i used chrome extension Advanced rest client and send the request

GET https://mydevorg-dev-ed--c.salesforce.com/services/data/v29.0/

Request Header Authorization: Bearer 00D90000000oX2G!AR8AQF4bfKL.F59U3YiDpt3WY5McM6lhzPhoQzTgkpuBUi1gbEMFXlWgCfq4QmufGh.Zw.VlGN4HCCG0S93qlcy671cQ6xcG

and i am getting No response after one minute .can some body tell me why i am unable to call rest api ??

i am trying to writea home page component perhaps there is some error in html its giving me message

Please ensure that the HTML code entered below is valid, well formed HTML. Poorly written HTML in this component may cause the entire Home tab to appear incorrectly.

but in html box when i check show HTML.its not showing html.anda box which is not editable. when i upload it using Ide its uploaded successfully but not showing error.how to see html of component for debugging please guideline!!

i have a visualforce page that source code is

<apex:page sidebar="false" showHeader="false">
   <link type="text/css" href="//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.1/themes/smoothness/jquery-ui.min.css" rel="stylesheet" />

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 <script src="//cdn.jsdelivr.net/xdate/0.8/xdate.min.js"></script>

<script>
 $(function() {

    var clearChatter = function(){
        $('.feedcontainer .feeditem').each(function(idx, el){
            $(el).remove();
        });

    }
    //set date value to today
    var today = new XDate(), current = today.clone();
    $( "#slider" ).slider({
      value:30,
      min: 1,
      max: 30,
      step: 1,
      stop: function( event, ui ) {

        //calculate the date, subtract months
        current = today.clone().addDays(-30+ui.value);
        $( "#date" ).html(current.clone().addDays(-1).toString('dd MMMM yyyy'));

        //clean out all old chatter posts
        clearChatter();

        //start loading new chatter
        var dayStart = new XDate(current.getFullYear(), current.getMonth(), current.getDate());
        var dayEnd = dayStart.clone().addDays(1);
        //check on feed container
        //add her if she's not there
        if($('.cxshowmorefeeditemscontainer').length == 0){
            var container = '<div class="cxshowmorefeeditemscontainer showmorefeeditemscontainer"></div>';

            $('.feedcontainer').append(container);

        }

        chatter.getFeed().showMoreFeedItems(this, {paginationToken: dayStart.toISOString()});


      },
      orientation: 'vertical'
    });
    $( "#date" ).val( "$" + $( "#slider" ).slider( "value" ) );


  });
  </script>
  <div id="date" style="position:absolute; left:720px;">Today</div>
  <div style="height:300px; position:absolute; left:700px;" id="slider"></div>
  <chatter:newsfeed ></chatter:newsfeed>
</apex:page>

as i can see

chatter.getFeed().showMoreFeedItems(this, {paginationToken: dayStart.toISOString()});

without calling apex they are getting chatter.getFeed(). is there any link or documentation on chatter for getting feed using javascript with various filters please guideline.

i have to get some data using SOAP api from one org to another .so i generated Enterprise wsdl file of one organization . it contains some fields with specified type as type=xsd:anyType. because apex doesn't support xsd:anyType thats why i changed it to xsd:string .ok it will generate some apex classes .i want to know is it the proper way.for handling anyType or we should do some thing else .Please guideline

i write a Batch apex.i write an execute method .which is using a static variable of another class.because it is shhared.any one can use it and change it.

 

public void execute(Database.BatchableContext BC, List<sObject> scope){

     x=GMirror.x;

     ...........

     ...........

         .........

y =GMirror.x; 


}

 

i want to know each batch of 5 in my case will run in transaction or means at this time only this method is running nothing else or in other words i want to know if using another class's method execution  in between time first statement execute

     x=GMirror.x;

 

and second statement 

y =GMirror.x; 

 

its possible by another parallel execution of another class's method that  these value of GMirror.x get changed ??

 these execution  this necessary that no one changed value of GMirror.x or value of GMirror.x can be changed by another parallel execution.Please clarify .

  • September 29, 2013
  • Like
  • 0

hi i am sending only a single Http Request in Batch but still facing error System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

 

My test code is 

 

@isTest(SeeAllData=true)
static void test1(){
MirrorTestUtil.setupSettings();
User u = [Select Authorize__c From User Where Id = :UserInfo.getUserId()];
u.Authorize__c = true;
update u;
System.debug('u is '+u);

List<FeedItem> feedList= new List<FeedItem>();
for (Integer i = 0; i<5;i++)
feedList.add( new FeedItem(Body='@'+UserInfo.getName()+'Hello World'+i,ParentId = UserInfo.getUserId()));
Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl());
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl());

insert feedList;
Test.stopTest();
}

 

and My trigger code is 

trigger PostFeedsToTimeLine on FeedItem (after insert) {

BatchPublishTimeLine publishBatch = new BatchPublishTimeLine(Trigger.new,contentMap);
Database.executeBatch(publishBatch,5);
}

 

and My Batch class code is 

public class BatchPublishTimeLine implements Database.Batchable<sObject>{
sObjectIterable iterable;
Map<Id,User> userMap;
Map<String,String> contentmap;

public BatchPublishTimeLine(List<sObject> objectList,Map<String,String> contentmap){
iterable = new sObjectIterable(objectList);
this.userMap = new Map<Id,User>([Select Id,Name From User WHERE Authorize__c = true]);
this.contentmap = contentmap;
}

public Iterable<sObject> start(Database.BatchableContext BC){
return iterable;
}

public void execute(Database.BatchableContext BC, List<sObject> scope){
GMirrorUtil.createTimeLine(scope, contentMap);
}

public void finish(Database.BatchableContext BC){
System.debug('Job Has been Finished');
}
}

 

and My createTimeLine function code is 

 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){

String timelineRes = doApiCall('xyzzz','POST','https://www.googleapis.com/mirror/v1/timeline','xxxxxxxxx');

}

 

doApiCall code is 

public static String doAPICall(String postBody, String method, String endPoint, String accessToken){

HttpRequest req = new HttpRequest();
Http http = new Http();
HttpResponse res;

req.setEndpoint(endPoint);
req.setMethod(method);
req.setHeader('Content-Type','application/json');

if(method == 'POST' || method == 'PUT')
req.setBody(postBody);
req.setHeader('Authorization','Bearer ' + accessToken);
res = http.send(req);
String result = res.getBody();
System.debug('status code is '+res.getStatus());
System.debug('result is'+res.getBody());
return result;
}

 

and the Mock class code response is 

 

@isTest
global class MirrorMockTimelinePostImpl implements HTTPCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('https://www.googleapis.com/mirror/v1/timeline', req.getEndpoint());
System.assertEquals('POST', req.getMethod());
System.assert(req.getHeader('Authorization').startsWith('Bearer'));

// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"kind":"mirror#timelineItem", "id":"mockid", "created":"2013-07-31T12:07:34.882Z", "updated":"2013-07-31T12:07:34.882Z", "etag":"\\"ZECOuWdXUAqVdpmYErDm2-91GmY/NVMWuR8LJyCKttsmne9R4K8n7YI\\"", "text": "New Lead: OauthCheck EarlyAm, Google, Inc., (234) 567-8900"}');
res.setStatusCode(200);
return res;
}
}

 

and i am unable to figure it out how using only one callout its throwing an error ?? Please help

  • September 26, 2013
  • Like
  • 0

i am getting an error Authorization Required.i am using google data api toolkit for apex(http://wiki.developerforce.com/page/Google_Data_API_Toolkit).i am getting an error.i modified code a little .my AuthSubController class code is

 

public class AuthSubController {

public AuthSubController(){

 if ( ApexPages.currentPage().getParameters().get('token') != null) { 
          //  string sessToken = 
            // AuthSubUtil.exchangeForSessionToken( 
              //  ApexPages.currentPage().getParameters().get('token'));
 GoogSession__c session = new googSession__c(id=
                ApexPages.currentPage().getParameters().get('url').substring(5),
                 AuthSubSessionToken__c = null );
            
       //     update session;
}
}
        public pagereference exchangeRequestToken() {
    
        return null;
    }
    

    public boolean getRequestToken() {
        return (ApexPages.currentPage().getParameters().get('token') == null
        && ApexPages.currentPage().getParameters().get('id') != null);
    }
    
    public static testMethod void t1() {   
   
        PageReference pageRef = Page.authsub;
        Test.setCurrentPage(pageRef);
  
        AuthSubController stc = new AuthSubController( );
        ApexPages.currentPage().getParameters().put('token', 'yyyy');
        ApexPages.currentPage().getParameters().put('id', 'yyyy');
        stc.exchangeRequestToken();
        stc.getRequestToken();
    }
     public static testMethod void t2() {   
   
        PageReference pageRef = Page.authsub;
        Test.setCurrentPage(pageRef);
  
        AuthSubController stc = new AuthSubController( );
        stc.getRequestToken();
        stc.exchangeRequestToken();
        
    }
    
    public string getHello(){
    return ApexPages.currentPage().getParameters().get('url').substring(5);
    
    }
    
}

 

and my  Auth Sub Util class is

 

public class AuthSubUtil {
    static string tokenInfo = 'https://www.google.com/accounts/AuthSubTokenInfo';
    static string authRequest = 'https://www.google.com/accounts/AuthSubRequest';
    static string subSession = 'https://www.google.com/accounts/AuthSubSessionToken';
    static string revokeUrl = 'https://www.google.com/accounts/AuthSubRevokeToken';
    
    public static Map<String, String> getTokenInfo(string token) {
        Map<String, String> ret = new Map<String, String> ();

        GoogleService service = new GoogleService('auth'); 
        service.AuthSubToken = token; 
        service.getFeedMethod('GET',tokenInfo, null, null );
        
        string[] lines =  service.response.getBody().split('\n');
        
        try { 
            for (string s: lines) {
                string[] nv = s.split('='); 
                ret.put(nv[0],nv[1]);
            } 
        } catch (exception e) {
            // an error or invalid token...
            system.debug( service.response.getBody() );
        } 
        return ret;
    }
    
    //  Creates the request URL to be used to retrieve an AuthSub token.
    public static String    getRequestUrl(string proto, string host, 
                                            String nextUrl, String scope) {
        // first we need to go thru the Salesforce GoogleAuthSub callback servlet
        // and that (next destination) needs to be encoded
        string encodedNext = proto + '://' + host +     
            '/_ui/core/google/GoogleAuthSubCallback?url=' + 
            EncodingUtil.urlEncode( nextUrl, 'UTF-8' ); 
        
        // then we need to encode again to allow it to pass thru to the google authsub sevlet
        string twiceEncodedNext =  EncodingUtil.urlEncode( encodedNext, 'UTF-8' ) ; 
        
        // finaly construct the first step in the redirect process, send your users to this url
        // must be done by the end user, in a browser...
        return authRequest + '?next='+ twiceEncodedNext + '&scope='+ scope + '&session=1&secure=0'; 
    }
    
    //  Creates the pagereference to be used to retrieve an AuthSub token.
    public static pagereference    getRequestPageReference(string proto, string host, 
                                            String nextUrl, String scope) {
        // first we need to go thru the Salesforce GoogleAuthSub callback servlet
        // and that (next destination) needs to be encoded
        string encodedNext = proto + '://' + host +     
            '/_ui/core/google/GoogleAuthSubCallback?url=' + 
            EncodingUtil.urlEncode( nextUrl, 'UTF-8' ); 
        
        // then we need to encode again to allow it to pass thru to the google authsub sevlet
        //string twiceEncodedNext =  EncodingUtil.urlEncode( encodedNext, 'UTF-8' ) ; 
        
        // finaly construct the first step in the redirect process, send your users to this url
        // must be done by the end user, in a browser...
        return  new PageReference( authRequest + '?next='+ encodedNext + '&scope='+ scope + '&session=1&secure=0'); 
    }

         
    //    Exchanges the one time use token returned in the URL for a session token.
    public static String    exchangeForSessionToken(String onetimeUseToken ) { 
        GoogleService service = new GoogleService('auth'); 
        service.AuthSubToken = onetimeUseToken;
        service.getFeedMethod('GET', subSession, null, GoogleService.CONTENT_TYPE_URL);
        return getTokenFromReply( service.response.getbody());
    }     
    
    // Parses and returns the AuthSub token returned by Google on a successful AuthSub login request.
    public static String    getTokenFromReply(String bodyOrUrl) {
        string[] atoken = bodyOrUrl.split('=');
        if ( atoken.size() != 2) { 
            system.debug( 'invalid token, or response from AuthSubSessionToken, no token');
            return null;
        }
        system.debug('session token is: '+atoken[1].trim());
        return atoken[1].trim();
    }

    public  static void     revokeToken(String token) {
         // Revokes the specified token.
        GoogleService service = new GoogleService('auth'); 
        service.AuthSubToken = token; 
        service.getFeed( revokeUrl ); 
    }
    
    /*  
    static String   getPrivateKeyFromKeystore(String keystore, String keystorePass, String keyAlias, String keyPass)
              Retrieves the private key from the specified keystore.          
    */
    
    /* 
     * test methods below here 
     */
    static final string sessionAuthToken = 'CJ3pqczuBBCpgI2pBw';
    
    public static testMethod void testGetTokenInfo() { 
        system.debug ( AuthSubUtil.getTokenInfo( sessionAuthToken) );
        system.debug ( AuthSubUtil.getTokenInfo( 'badtoken' ) );
    }
    
    public static testMethod void testexchangeForSessionToken() { 
        CalendarService service = new CalendarService();  
        AuthSubUtil.exchangeForSessionToken( 'teststtoken' );
        
    }
    
    public static testMethod void testgetTokenFromReply() { 
        CalendarService service = new CalendarService();  
        AuthSubUtil.getTokenFromReply( 'url=teststtoken' );
        AuthSubUtil.getTokenFromReply( 'urlbadteststtoken' );
    }
    
    public static testMethod void testrevokeToken() { 
        CalendarService service = new CalendarService();  
        AuthSubUtil.revokeToken( 'teststtoken' );
     
    }
    
    public static testMethod void testgetRequestUrl() { 
        string expected = 'https://www.google.com/accounts/AuthSubRequest?next=https%3A%2F%2Ftapp0.salesforce.com%2F_ui%2Fcore%2Fgoogle%2FGoogleAuthSubCallback%3Furl%3D%252Fapex%252Fgsession%253Fid%253Da0AT0000000FO1QMAW&scope=http://www.google.com/calendar/feeds/&session=1&secure=0';
        CalendarService service = new CalendarService();  
        
        string checkUrl =  AuthSubUtil.getRequestUrl( 'https', 'tapp0.salesforce.com', 
            '/apex/gsession?id=a0AT0000000FO1QMAW',  // next  
            'https://www.google.com/calendar/feeds/' );   // scope 
            
        system.debug ( expected ) ; 
        system.debug ( checkUrl );   
        system.assert(  expected == checkUrl , ' mis match request url '); 
    }
    

  public static testMethod void  testgetRequestPageReference(){
    
        String strProto = 'https';
        String strHost = 'na2.salesforce.com';
        String strNextUrl = '/apex/authsub';
        String strScopeUrl = 'https://spreadsheets.google.com/feeds/';
              
         PageReference p = AuthSubUtil.getRequestPageReference( strProto, strHost, strNextUrl, strScopeUrl);
        system.debug (p); 
      
      STRING expected = 'https://www.google.com/accounts/AuthSubRequest?next=https%3A%2F%2Fna2.salesforce.com%2F_ui%2Fcore%2Fgoogle%2FGoogleAuthSubCallback%3Furl%3D%252Fapex%252Fauthsub&scope=http%3A%2F%2Fspreadsheets.google.com%2Ffeeds%2F&secure=0&session=1';
      system.assert( expected == p.getUrl() , 'page reference genreated is bad'); 
    }
        
}

 

 

my authsub page is

 

<apex:page controller="AuthSubController" showHeader="false">
<head><title>Hello World</title>
<meta name="google-site-verification" content="XCzApP9fdbR3auxPHd3-X0g7uCNbrXZDQU_jm5GHXLI" />
</head>
          <apex:outputPanel rendered="{!$CurrentPage.parameters.token != null}"> 
The one time use token is :<b>{!$CurrentPage.parameters.token}</b>
            <br />
Record to update is {!$CurrentPage.parameters.id}
<br />
URL to update is {!hello}
<apex:form >
<apex:commandbutton action="{!exchangeRequestToken}"
                oncomplete="window.close();" value="Request Session token" />
        </apex:form>
        </apex:outputPanel>
</apex:page>
in my authsub page controller class is AuthSubController
if you AuthSubController class there is a constructor and for highlighting i am pasting constructor here

public AuthSubController(){

 if ( ApexPages.currentPage().getParameters().get('token') != null) { 
          //  string sessToken = 
            // AuthSubUtil.exchangeForSessionToken( 
              //  ApexPages.currentPage().getParameters().get('token'));
 GoogSession__c session = new googSession__c(id=
                ApexPages.currentPage().getParameters().get('url').substring(5),
                 AuthSubSessionToken__c = null );
            
       //     update session;
}
}

if i make these lines commented(as shown in constructor ) then there is no (Authorization Required).if uncommented code of constructor is given below:
public AuthSubController(){

 if ( ApexPages.currentPage().getParameters().get('token') != null) { 
            string sessToken = 
             AuthSubUtil.exchangeForSessionToken( 
                ApexPages.currentPage().getParameters().get('token'));
 GoogSession__c session = new googSession__c(id=
                ApexPages.currentPage().getParameters().get('url').substring(5),
                 AuthSubSessionToken__c = null );
            
            update session;
}
}
in this case there is Authorization required error.i gave all permission to GoogSeession__c in public access settings of site for sure.probably main problem is with this line.
error come when i redirected to authsub home page
  string sessToken = 
             AuthSubUtil.exchangeForSessionToken( 
                ApexPages.currentPage().getParameters().get('token'));
can any one please help me how to remove this Authorization Required error.please dont look at above two big code segments these are only for completeness of question main is thes constructor code where i am getting error.


i am developing an app in native Force.com.first i installed Google Tookit for apex using this link.then i try to authorize my app with google following this link. when i authorize app in a visualforce page. then an error occurs:

The page you have requested cannot be displayed. Another site was requesting access to your Google Account, but sent a malformed request. Please contact the site that you were trying to use when you received this message to inform them of the error. A detailed error message follows:

The site "http://force.com" has not been registered.

then i try to register app from this link https://www.google.com/accounts/ManageDomains i didn't get any way.i cant upload there tag in force.com home page.Can any one please tell how to get rid off this error.please help!!

i am following this tutorial for setting google toolkit for salesforce org when i reach Synchronizing with your Force.com Developer Edition org and i synchronize it with my developer org suddenly a dialog error occurred with info:

Unable to synchronize resource src to server:ClassCastException:com.salesforce.ide.api.metadata.types.MetaData$JaxbAccessorF_full_Name can not be cast to com.sun.xml.Internal.bind.v2.runtime.reflect.Accessor

Reason: com.salesforce.ide.api.metadata.types.Metadata$JaxbAccessorF_full_Name cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor

How to resolve this error any one g0t through this error then please help to resolve it

Hi i am creating visualforce pages and apex classes triggers etc for last some time.i want to know what is app in salesforce and how to publish it on AppExchange? Any requirement for publishing app on app exchange i went through this tutorial link

they teach how to create an app in developer org by default there are 6 tabs Home,Chatter,File,Your Tab ,Reports,DashBoard.i basically want to know what app contains? apex class,visualforce page these components or only standard tabs and some customization tab what we see when we select an app in developer org

hi i am sending only a single Http Request in Batch but still facing error System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

 

My test code is 

 

@isTest(SeeAllData=true)
static void test1(){
MirrorTestUtil.setupSettings();
User u = [Select Authorize__c From User Where Id = :UserInfo.getUserId()];
u.Authorize__c = true;
update u;
System.debug('u is '+u);

List<FeedItem> feedList= new List<FeedItem>();
for (Integer i = 0; i<5;i++)
feedList.add( new FeedItem(Body='@'+UserInfo.getName()+'Hello World'+i,ParentId = UserInfo.getUserId()));
Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl());
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl());

insert feedList;
Test.stopTest();
}

 

and My trigger code is 

trigger PostFeedsToTimeLine on FeedItem (after insert) {

BatchPublishTimeLine publishBatch = new BatchPublishTimeLine(Trigger.new,contentMap);
Database.executeBatch(publishBatch,5);
}

 

and My Batch class code is 

public class BatchPublishTimeLine implements Database.Batchable<sObject>{
sObjectIterable iterable;
Map<Id,User> userMap;
Map<String,String> contentmap;

public BatchPublishTimeLine(List<sObject> objectList,Map<String,String> contentmap){
iterable = new sObjectIterable(objectList);
this.userMap = new Map<Id,User>([Select Id,Name From User WHERE Authorize__c = true]);
this.contentmap = contentmap;
}

public Iterable<sObject> start(Database.BatchableContext BC){
return iterable;
}

public void execute(Database.BatchableContext BC, List<sObject> scope){
GMirrorUtil.createTimeLine(scope, contentMap);
}

public void finish(Database.BatchableContext BC){
System.debug('Job Has been Finished');
}
}

 

and My createTimeLine function code is 

 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){

String timelineRes = doApiCall('xyzzz','POST','https://www.googleapis.com/mirror/v1/timeline','xxxxxxxxx');

}

 

doApiCall code is 

public static String doAPICall(String postBody, String method, String endPoint, String accessToken){

HttpRequest req = new HttpRequest();
Http http = new Http();
HttpResponse res;

req.setEndpoint(endPoint);
req.setMethod(method);
req.setHeader('Content-Type','application/json');

if(method == 'POST' || method == 'PUT')
req.setBody(postBody);
req.setHeader('Authorization','Bearer ' + accessToken);
res = http.send(req);
String result = res.getBody();
System.debug('status code is '+res.getStatus());
System.debug('result is'+res.getBody());
return result;
}

 

and the Mock class code response is 

 

@isTest
global class MirrorMockTimelinePostImpl implements HTTPCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('https://www.googleapis.com/mirror/v1/timeline', req.getEndpoint());
System.assertEquals('POST', req.getMethod());
System.assert(req.getHeader('Authorization').startsWith('Bearer'));

// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"kind":"mirror#timelineItem", "id":"mockid", "created":"2013-07-31T12:07:34.882Z", "updated":"2013-07-31T12:07:34.882Z", "etag":"\\"ZECOuWdXUAqVdpmYErDm2-91GmY/NVMWuR8LJyCKttsmne9R4K8n7YI\\"", "text": "New Lead: OauthCheck EarlyAm, Google, Inc., (234) 567-8900"}');
res.setStatusCode(200);
return res;
}
}

 

and i am unable to figure it out how using only one callout its throwing an error ?? Please help

  • September 26, 2013
  • Like
  • 0

My CreateTimeLine code is

 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){
Map<Id,User> userMap = new Map<Id,User>([Select id,Name From User where Authorize__c = true]);
Map<Id,GlassUserApiSettings__c> userSettingsMap = new Map<Id,GlassUserApiSettings__c>();

for(Id user_id : userMap.keySet()){
GlassUserApiSettings__c userSettings = GlassUserApiSettings__c.getValues(user_id);
if(userSettings == null)
{ User u =userMap.get(user_id);
u.Authorize__c = false;
update u;
}
else userSettingsMap.put(user_id,userSettings);

}
for(sObject obj : objList)
for(Id userId: userSettingsMap.keySet() ){
String type = '';
if(contentMap.get('Object').equals('FeedItem'))
type='Post';
if(contentMap.get('Object').equals('FeedComment'))
type= 'Comment';
GlassUserApiSettings__c userSettings = userSettingsMap.get(userId);
if(((String)obj.get(contentMap.get('Content'))).contains('@'+userMap.get(userId).Name)){
Datetime tokenExpiredTime = userSettings.LastModifiedDate;
tokenExpiredTime.addSeconds(Integer.valueOf(userSettings.ExpireDuration__c));
String body='{"html":"<article><section><div class="text-auto-size">'+type+':'+
'<p class="yellow">"'+obj.getSObject('CreatedBy')+'&nbsp;'+obj.getSObject('CreatedBy')+'</p><p>'+obj.get(contentMap.get('Content'))+'</p>'+
'</div></section> </article>"}';
System.debug('Body is '+body);
/* if(tokenExpiredTime >= System.now()){
GMirror.TokenResponse res = GMirrorUtil.refreshToken(userSettings.RefreshToken__c);
userSettings.RefreshToken__c = res.refresh_token;
userSettings.AccessToken__c = res.access_token;
userSettings.ExpireDuration__c = Integer.valueOf(res.expires_in) ;
update userSettings;
}*/
String timelineRes = doApiCall(body,'POST','https://www.googleapis.com/mirror/v1/timeline',userSettings.AccessToken__c);
GMirror.TimelineResponse createdTimeCard = (GMirror.TimelineResponse) JSON.deserialize(timelineRes,GMirror.TimelineResponse.class);
if(createdTimeCard.id != null)
System.debug('created timeline card :'+createdTimeCard);
else { try{
throw new GMirror.TimelineException(null,timelineRes);
}
catch(Gmirror.TimelineException e){
System.debug(e.getMessage());
}
}
}
}
}

 

and My Batch apex code is 

 

public class BatchPublishTimeLine implements Database.Batchable<sObject>{
sObjectIterable iterable;
Map<Id,User> userMap;
Map<String,String> contentmap;

public BatchPublishTimeLine(List<sObject> objectList,Map<String,String> contentmap){
iterable = new sObjectIterable(objectList);
this.userMap = new Map<Id,User>([Select Id,Name From User WHERE Authorize__c = true]);
this.contentmap = contentmap;
}

public Iterable<sObject> start(Database.BatchableContext BC){
return iterable;
}

public void execute(Database.BatchableContext BC, List<sObject> scope){
GMirrorUtil.createTimeLine(scope, contentMap);
}

public void finish(Database.BatchableContext BC){
System.debug('Job Has been Finished');
}
}

 

public static String doAPICall(String postBody, String method, String endPoint, String accessToken){

HttpRequest req = new HttpRequest();
Http http = new Http();
HttpResponse res;

req.setEndpoint(endPoint);
req.setMethod(method);
req.setHeader('Content-Type','application/json');

if(method == 'POST' || method == 'PUT')
req.setBody(postBody);
req.setHeader('Authorization','Bearer ' + accessToken);
res = http.send(req);
String result = res.getBody();
System.debug('status code is '+res.getStatus());
System.debug('result is'+res.getBody());
return result;
}

i am calling batch apex from a trigger after in sert function i am getting this error from line 

 

String timelineRes = doApiCall(body,'POST','https://www.googleapis.com/mirror/v1/timeline',userSettings.AccessToken__c);

i am not using any DML statement after doApiCall function as you can see . but why i am facing trhis error ??Please guideline to resolve it.

  • September 25, 2013
  • Like
  • 0

riggeri am testing a trigger.i am calling this method

  GMirrorUtil.createTimeLine(Trigger.new, contentMap);

My create timeline function is 

public static void createTimeLine(List<sObject> objList,Map<String,String> contentMap){ 
      Map<Id,User> userMap = new Map<Id,User>([Select id,Name From User where Authorize__c = true]);
      Map<Id,GlassUserApiSettings__c> userSettingsMap = new Map<Id,GlassUserApiSettings__c>();

       for(Id user_id : userMap.keySet()){
         GlassUserApiSettings__c userSettings = GlassUserApiSettings__c.getValues(user_id);
        if(userSettings == null)
         { User u =userMap.get(user_id);
            u.Authorize__c = false;
           update u;  
         }
          else userSettingsMap.put(user_id,userSettings); 

       }
       for(sObject obj : objList)
         for(Id userId: userSettingsMap.keySet() ){
           String type = '';
           if(contentMap.get('Object').equals('FeedItem'))
             type='Post';
           if(contentMap.get('Object').equals('FeedComment'))
             type= 'Comment';
           GlassUserApiSettings__c userSettings = userSettingsMap.get(userId);
           if(((String)obj.get(contentMap.get('Content'))).contains('@'+userMap.get(userId).Name)){
             Datetime tokenExpiredTime = userSettings.LastModifiedDate;
             tokenExpiredTime.addSeconds(Integer.valueOf(userSettings.ExpireDuration__c)); 
             String body='{"html":"<article><section><div class="text-auto-size">'+type+':'+
                         '<p class="yellow">"'+obj.getSObject('CreatedBy')+'&nbsp;'+obj.getSObject('CreatedBy')+'</p><p>'+obj.get(contentMap.get('Content'))+'</p>'+
                         '</div></section> </article>"}';
                         System.debug('Body is '+body);
             if(tokenExpiredTime >= System.now()){
               GMirror.TokenResponse res  =  GMirrorUtil.refreshToken(userSettings.RefreshToken__c);                 
               userSettings.RefreshToken__c = res.refresh_token;
               userSettings.AccessToken__c  = res.access_token;    
               userSettings.ExpireDuration__c = Integer.valueOf(res.expires_in) ;
               update userSettings;
             }
             String timelineRes = doApiCall(body,'POST','https://www.googleapis.com/mirror/v1/timeline',userSettings.AccessToken__c);
             GMirror.TimelineResponse createdTimeCard  = (GMirror.TimelineResponse) JSON.deserialize(timelineRes,GMirror.TimelineResponse.class);   
             if(createdTimeCard.id != null)
               System.debug('created timeline card :'+createdTimeCard);
             else { try{
                        throw new GMirror.TimelineException(null,timelineRes);
                       }
                    catch(Gmirror.TimelineException e){
                      System.debug(e.getMessage());
                    }
                  }
           }
         }          
    }

but when i initialize prepare String body='{"html":"'+type+':'+ '"'+obj.getSObject('CreatedBy')+' '+obj.getSObject('CreatedBy')+'

'+obj.get(contentMap.get('Content'))+'

'+ ' "}'; i check it in debug logs its giving me null for getSObject('CreatedBy'); i inserted it in my test class thats why trigger invoked and i am using afterinsert event in trigger . can any one please tell why its giving me null ??

 

 

  • September 25, 2013
  • Like
  • 0