0

I created a VF page to display all the files link of a google drive folder. I am storing the folder ID in a custom object. I added this page as a inline VF page on Opportunity object.

Whenever I am trying to authenticate it is giving list has no rows. The Opportunity Id is null when I checked in debug logs

Here is my code :

Class :

public class googleAuthwithSFDC 
{


    private string key = '674724564573-p2d5ndp5ifebn5017fpabntabcdl7fg48.apps.googleusercontent.com' ;
    private string secret = 'SecretKey';

    private string redirect_uri = 'https://cs19.visual.force.com/apex/GoogleAuthPage';
    private String codemeniaIdentificationToken ; 

    public Opportunity opp{get;set;}

    private String access_token; 
    private List<String> FileLst;
    public Map<String,String> FileIdAndNameMapFortheAccount{get;set;}
    //Constructor
    public googleAuthwithSFDC(ApexPages.StandardController controller)
    {

        codemeniaIdentificationToken = ApexPages.currentPage().getParameters().get('code') ;

        FileLst=new List<String>();
        FileIdAndNameMapFortheAccount=new Map<String,String>();
        if(codemeniaIdentificationToken != '' && codemeniaIdentificationToken != null)
        {
            AccessToken();
        } 
    }

    public PageReference DriveAuth()
    {
        PageReference pg = new PageReference(new cAuthURIForApiREq(key , redirect_uri).AuthenticationURI) ;
        return pg;
    }

    public void AccessToken()
    {
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        //End point for authentication
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        //Message body for Authentication
        String messageBody = 'code='+codemeniaIdentificationToken+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        HttpResponse res = h.send(req);
        //Salesforce defined JSON Parser
        JSONParser parser = JSON.createParser(res.getBody());
        while (parser.nextToken() != null) 
        {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token'))
            {
                parser.nextToken();
                access_token=parser.getText();
                break;
            }
        }
        if (access_token!='' && access_token != null)
        {
            ListFiles();
        }
    }

    public PageReference ListFiles()
    {  
        System.debug('Entered List Files');
        String opId = ApexPages.currentPage().getParameters().get('id');
        System.debug('@@@@@ op Id :' + opId);
        Opportunity op = [Select ID,Name from Opportunity Where ID =: opId];
        System.debug('@@@@@@@@@@ Op :' + op);
        DriveIntegration__c g=new DriveIntegration__c();
        g=[SELECT Folder_Id__c FROM DriveIntegration__c WHERE OpportunityLookup__r.ID =: op.Id];
        String FolderId=g.Folder_Id__c;
        System.debug('@@@@@@@@@@ Folder Id:' + FolderId);
        HttpRequest req1 = new HttpRequest();
        req1.setMethod('GET');
        //End point for List of Files in Folder
        req1.setEndpoint('https://www.googleapis.com/drive/v2/files/'+FolderId+'/children');
        req1.setHeader('content-type', 'application/x-www-form-urlencoded');
        req1.setHeader('Content-length', '0');
        //Specific Authorization Syntax
        req1.setHeader('Authorization' , 'Bearer'+' '+ access_token);
        req1.setTimeout(60*1000);
        Http h2 = new Http();
        HttpResponse resl = h2.send(req1);
        System.debug('^^^^^'+resl.getBody());
        JSONParser parserD = JSON.createParser(resl.getBody());
        while (parserD.nextToken() != null) 
        {
            if ((parserD.getCurrentToken() == JSONToken.FIELD_NAME) && (parserD.getText() == 'id'))
            {
                parserD.nextToken();
                FileLst.add(parserD.getText());
            }
        }
       Map<String,String> FileIdAndNameMap=FileProperties();
        for(String s:FileLst)
        {
            FileIdAndNameMapFortheAccount.put(s, FileIdAndNameMap.get(s));
        }
        return null;
    }
    public  Map<String,String> FileProperties()
    {
        Map<String,String> FilePropertiesDetails=new Map<String,String>();
        HttpRequest req2 = new HttpRequest();
        req2.setMethod('GET');
        //End point URL for All the files in the drive and its ID,Name value in JSON Response
        req2.setEndpoint('https://www.googleapis.com/drive/v3/files');
        req2.setHeader('content-type', 'application/x-www-form-urlencoded');
        req2.setHeader('Content-length', '0');
        req2.setHeader('Authorization' , 'Bearer'+' '+ access_token);
        req2.setTimeout(60*1000);
        Http h3 = new Http();
        HttpResponse resls = h3.send(req2);
        System.debug('^^^^^'+resls.getBody());
        JSONParser parserDr = JSON.createParser(resls.getBody());
        while (parserDr.nextToken() != null) 
        {   
            String FileName='';
            String FileId='';
            if ((parserDr.getCurrentToken() == JSONToken.FIELD_NAME))
            {
                //First TOKEN is Id
                if((parserDr.getText() == 'id'))
                {
                    parserDr.nextToken();               
                    Fileid=parserDr.getText();
                }
                //Moving to Next Parser
                parserDr.nextToken();
                //Next Token is Name
                if((parserDr.getText() == 'name'))
                {
                    parserDr.nextToken();
                    Filename=parserDr.getText();
                }
                FilePropertiesDetails.put(Fileid, Filename);
            }
        }
        return FilePropertiesDetails;
    }
}

Page :

<apex:page standardController="Opportunity" extensions="googleAuthwithSFDC ">
    <apex:form >
        <apex:pageBlock >
            <apex:commandButton value="Authenticate" action="{!DriveAuth}"/>
            <apex:dataTable value="{!FileIdAndNameMapFortheAccount}" var="f">
                <apex:column headerValue="Drive Files" >
                    <apex:outputLink value="https://drive.google.com/open?id={!f}" target="_blank">{!f}</apex:outputLink>
                </apex:column>
            </apex:dataTable>
             </apex:pageBlock>
    </apex:form>
</apex:page>
  • It would be nice if you could point out where the error is occurring.... – Eric Jun 20 '16 at 17:10
  • @Eric Thanks for your response I am getting the error @ Opportunity op = [Select ID,Name from Opportunity Where ID =: opId]; The opId is null when I checked in logs – Learner Jun 20 '16 at 17:21
  • what does this debug say? System.debug('@@@@@ op Id :' + opId); – EricSSH Jun 20 '16 at 17:38
  • @EricSSH Its giving null – Learner Jun 20 '16 at 17:43
  • Follow it up from there then, what's wrong here? String opId = ApexPages.currentPage().getParameters().get('id');` – EricSSH Jun 20 '16 at 17:44
0

The problem is most likely this line (Scroll to end of answer for the most likely cause):

g=[SELECT Folder_Id__c FROM DriveIntegration__c WHERE OpportunityLookup__r.ID =: op.Id];

But since you did not state which it was when asked I had to review all of that code to find it. It appears to be the only SOQL so....

The reason is that the op.id is most likely null.

Which means that this is returning null:

ApexPages.currentPage().getParameters().get('id');

Which is either due to a case issue in the id, should it be Id? Since you are using a standard controller it should be populating.

Since you are using a standard controller you could be getting the record in the constructor:

opp = (Opportunity)con.getRecord();

and change your query to

g=[SELECT Folder_Id__c FROM DriveIntegration__c WHERE OpportunityLookup__r.ID =: opp.Id];

Or you are performing these actions on a new opportunity where there is no id in which case you should be catching that and producing an appropriate notification

In your DriveAuth method you are creating a new page reference and returning it thus the current page reference does not have an ID parameter and that return null in the list files method. Try changing the PageReference to this

PageReference pg = new PageReference(new cAuthURIForApiREq(key , redirect_uri).AuthenticationURI) ;
pg.getParameters().put('id',opp.id);
return pg;

but then again, the final page may be redirected so it would loose the ID parameter.

Best bet, get the opp in the constructor as I have shown above and change the query to use opp.id as the filter

|improve this answer|||||
  • Thanks for your response I tried the both options you provided still I am facing the same issue. When I click on Authenticate the url is not taking the Opportunity ID. The url is returning VFPage?state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&code=4/wmrPAp5z6B6UzyeRI-LmGkdkRAZeo_uNBocpOxLnTrI# – Learner Jun 22 '16 at 19:52
  • Did you set the opp in the constructor – Eric Jun 22 '16 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.