Tuesday 25 December 2012

JSON to Apex Convesion simpler now with http://json2apex.herokuapp.com

With the REST API being lot used when integrating apps developed on force.com paltform with the mobile applications or integrating force.com with external applications communicating using JSON it becomes vital to know few of open source tool we have to make our task simpler.

When we are in technology consulting world the time becomes crucial in any project we face .

There are couple of tools that i normally use whenever an integration is using REST API and the format of data communication is in the form of JSON .

In this blog i will describe two commonly used applications that makes life simpler when dealing with the JSON data.


This application is very useful to format and Validate the JSON .All you need to do is input the JSON in the text box provided and click on Validate button to Validate the JSON .

JSON Lint is a web based validator and reformatter for JSON, a lightweight data-interchange format.


This was recently developed by salesforce evangelism (SuperFell and PattPatterson) and this is really helpful .The app is on the Heroku paltform and its really helpful of you want to construct an apex class from the JSON you have .

All you need is validated JSON (validate using jsonlint.com) is inputed and just a button click will give you the generated class and also the deserialiser method .

Lets see an example 

Say i have the JSON data as shown below 
{

    "id": "https://login.salesforce.com/id/00D90000000aRkLEAU/00590000000HI32AAG",

    "issued_at": "1355574766264",

    "instance_url": "https://ap1.salesforce.com",

    "signature": "LfOtSilg0GXb8NMO2YwcFvDTjRf8Ml0+jxI3XOozmuw=",

    "access_token": "00D90000000aRkL!ARIAQLLtJXpuyCteMrXEbkbEi6qZcgUhkeaK6_.Yqrxlz8JeOn"

}

Once i input this JSON into the app i get the following result
//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class JSON2Apex {

 public String id;
 public String issued_at;
 public String instance_url;
 public String signature;
 public String access_token;

 
 public static JSON2Apex parse(String json) {
  return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
 }
 
 static testMethod void testParse() {
  String json = '{'+
  ''+
  '    \"id\": \"https://login.salesforce.com/id/00D90000000aRkLEAU/00590000000HI32AAG\",'+
  ''+
  '    \"issued_at\": \"1355574766264\",'+
  ''+
  '    \"instance_url\": \"https://ap1.salesforce.com\",'+
  ''+
  '    \"signature\": \"LfOtSilg0GXb8NMO2YwcFvDTjRf8Ml0+jxI3XOozmuw=\",'+
  ''+
  '    \"access_token\": \"00D90000000aRkL!ARIAQLLtJXpuyCteMrXEbkbEi6qZcgUhkeaK6_.Yqrxlz8JeOn\"'+
  ''+
  '}';
  JSON2Apex obj = parse(json);
  System.assert(obj != null);
 }
}
This is really awesome .No more time consumed to draft the apex class Happy Coding!

Sunday 23 December 2012

Handling PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException exception in SFDC Callout

Recently i encountered an exception during making a Callout to the external service .Being an apex developer and unfamiliar with SSL concept much with no luck after googling i tried posting the question in stackexchange Stackexchange link.I am thankful to the Martin Peters for helping me on this .

Through this blog post i would like to document few points i learned on cause of this exception and also i will indicate the solution and resources we have that can help us to get rid of this exception

1)First way to identify this exception is if we try to open the URL we are using to  make a callout to external system in any browser we will encounter the security exception.The below image shows how our browser will behave once encountering such SSL exception.


2)This happens when the external system we make callout from the salesforce does not have valid SSL certificate 

For the JAVA client we have solution on the discussion board .http://boards.developerforce.com/t5/General-Development/PKIX-path-building-failed/td-p/128332

There are two very popular way of implementing authenticated Callouts 

1)one-way SSL/certificate security
2)Two-way SSL 

1)One-Way SSL is easiest implementation :

This blog explains the process for cast iron and i must thank the author of blogger post for such wonderful explanation

So if the external server implements this the problem gets solved straight away.

2)Two-way SSL :
Thanks to the developer.force.com of salesforce that we have an excellent article on how to configure this on salesforce end 

We have a list of SSL certifcates that are accepted by salesforce and verified .Here is the link to the document

Saturday 15 December 2012

Oauth 2.0 Salesforce Using REST Console of Chrome Browser


Earlier in one of my blog post i had demonstrated on how to use Mozilla Poster tool to verify the REST API calls of the salesforce.

Using Chrome REST console has several advantages than poster mozilla .The response can be seen in both JSON and XML and also the concept of oauth 2.0 also can be practically understood .

There are very good articles on 2.0 on the developer.force.com and here is the link Digging deeper into Oauth 2.0

The workbench.developerforce.com has an excellent REST utility which helps in quick verification of Restful Apex services or even standard REST API exposed by the salesforce .One major disadvantage of this is since the oauth happens automatically the conceptual knowledge on how oauth 2.0 works is hidden .

In this blog post we will use the REST Console of the chrome and first get the oauth token from the salesforce instance and then will invoke the REST service from the salesforce .

Step 1-Getting oauth token from salesforce instance 

First step is to set up the remote access settings so that we can obtain the Client secret as well as the clientId

Click On image to View on ful

Step-2-Using the POST call to access the Oauth token from the salesforce 

The payload will be in XML and here is the format of the payload

grant_type=password&client_id=<your_client_id>&client_secret=<your_client_secret>&username=<your_username>&password=<your_password>

where client id,client secret you will get from your remote access settings and please append security token if you are making from unautorized IP range .Please use appropriate User Name and Password

The target URL to obtain token from the salesforce is as follows 



Use this first as a request URL to get access token .Please use test.salesforce.com for sandbox







Step-3:Making a POST request will yield the JSON with token and here is the snapshot of the issued token from salesforce 












JSON Response Obtained From Server:

{
    "id": "https://login.salesforce.com/id/00D90000000aRkLEAU/00590000000HI32AAG",
    "issued_at": "1355574766264",
    "instance_url": "https://ap1.salesforce.com",
    "signature": "LfOtSilg0GXb8NMO2YwcFvDTjRf8Ml0+jxI3XOozmuw=",
    "access_token": "00D90000000aRkL!ARIAQLLtJXpuyCteMrXEbkbEi6qZcgUhkeaK6_.Yqrxlz8JeOn"
}
The access_token parameter contains the access token can be used in header to access the services

Step 4-The access token is used along with bearer word in the authorisation header to access any rest service.the snapshot shows where the access token needs to be entered in REST console

Click on image to View Full Screen


The response obtained can be changed to XML or JSON using the REST console.
Click on image to View Full Screen





Sunday 2 December 2012

Writing Test Classes For Apex Rest Service

I came across a question in a developer community on how to write Unit Test Classes for the Rest API service for POST HTTP calls

Unit Test Classes for REST API following link is very useful and inspired by this jeff had an article on his blog on how to write the test method for same .

Here is the Jeff Blog Link Test Class for REST API(Good reference for GET Rest Services)


In one of my previous blog post i demonstrated how to use native parsing technique for Rest api for User Defined Type
I wrote the Test class for the same and this post is helpful for all those searching for how to write test classes for apex rest service annotated with POST Call
Here is the Rest Service Class for which i attempted the test class
@RestResource(urlMapping='/DemoUrl/*')
global with sharing class MyRestResourcedemo {

    global class RequestWrapper{
       public  Account acct;
        public Contact[] cons;
    }
  
   global class ResponseWrapper {           
        public String StatusCode;
        public String StatusMessage;
        public Account acct;
        public Contact[] cons;    
    }

@HttpPost
    global static ResponseWrapper doPost(RequestWrapper reqst) {
    
        ResponseWrapper resp = new ResponseWrapper();     
        try{
        insert reqst.acct;
        for(Contact c:reqst.cons){
        c.AccountId = reqst.acct.Id;
        }
        Upsert reqst.cons;
        }
        catch( Exception e ) {
                resp.statusCode = 'Error';
                resp.statusMessage = 'Exception : ' + e.getMessage();
           }
            resp.statusCode = 'Done';
            resp.statusMessage = 'Test success message';
            resp.acct = reqst.acct;
            resp.cons = reqst.cons;

        return resp;
    }
  }

Here is how i wrote my Test class and it ensured my class is covered and i aserted the response
@istest
public class SFA_TestRestPostService {
 
   static testMethod void  testPostRestService(){
   
   Account acc=new Account();
   acc.name='Test';
   acc.AccountNumber='1232332';
   acc.Site='site';
   acc.Website='cloudyworlds.blogspot.in';
   
   List lstcon=new List();

   integer i;
   for(i=0;i<=10;i++){
   Contact c=new Contact();
   c.lastname='Test+i';
   lstcon.add(c);
   }
   
   MyRestResourcedemo.RequestWrapper reqst=new MyRestResourcedemo.RequestWrapper();
   reqst.acct=acc;
   reqst.cons=lstcon;
   
   String JsonMsg=JSON.serialize(reqst);
   
   Test.startTest();
   
   //As Per Best Practice it is important to instantiate the Rest Context 
   
   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();
         
   req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
   req.httpMethod = 'POST';//HTTP Request Type
   req.requestBody = Blob.valueof(JsonMsg);
   RestContext.request = req;
   RestContext.response= res;



   MyRestResourcedemo.ResponseWrapper resp =new  
   MyRestResourcedemo.ResponseWrapper(); 
   resp=MyRestResourcedemo.doPost(reqst); //Call the Method of the Class with Proper       Constructor 
   System.assert(resp.statusMessage.contains('Test success message'));//Assert the response has message as expected 
   System.assert(resp.statusCode.contains('Done'));
   System.assert(resp.acct.Id!=null);//Assert that the Account is inserted and has Id
   Test.stopTest();
   
   }
 }

Some thoughts on best practice can be found on this link of stackexchange

http://salesforce.stackexchange.com/questions/4988/writing-test-classes-for-apex-restservice

Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...