+ Start a Discussion
rajesh k 10rajesh k 10 

How to move one org data to another org data using apex in salesforce?

hitesh90hitesh90
Hello Rajesh,

There is one option for this requirement is REST webservice.
See below code for fetching Account records from one salesforce org to another salesforce org using APEX.


Apex Class: Create REST web service in source Org (In Source Org)
@RestResource(urlMapping='/accountrecords/*')  
global class extractAccountRESTService{
    @HttpGet
    global static Account[] extractAccountData() {  
        //Returns the RestRequest object for our Apex REST method.  
        RestRequest request = RestContext.request;  
        //Returns the RestResponse for our Apex REST method.  
        RestResponse response = RestContext.response;  
        //query the Box Folder  
        List<Account> lstAccount = new List<Account>();
        try{
            lstAccount = [SELECT Id, Name FROM Account];  
        }catch(Exception e){
            system.debug('@@@@@ Error ' + e.getMessage());
        }
        return lstAccount;  
    }
}



Apex Class: Login using web service and get Session id. (In Destination Org)

public class loginsalesforce{
    private static final String NS_SOAP = 'http://schemas.xmlsoap.org/soap/envelope/';
    private static final String NS_SF = 'urn:partner.soap.sforce.com';

    public static String login()
    {
        string user = 'GIVE SOURCE YOUR ORG USERNAME';
        string password = 'GIVE YOUR SOURCE ORG USERNAME & PASSWORD';        
        
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');   
        req.setTimeout(60000);
        req.setEndpoint('https://login.salesforce.com/services/Soap/u/29.0');
        req.setHeader('Content-Type', 'text/xml;charset=UTF-8');        
        req.setHeader('SOAPAction', '""');
        req.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' +user+ '</username><password>' + password + '</password></login></Body></Envelope>');        
        HttpResponse res =  new Http().send(req);
        system.debug('response'+ res);
        system.debug('response'+ res.getBody());
        if(res.getStatusCode() != 200)
        {
            Dom.Document responseDocument = res.getBodyDocument();
            Dom.Xmlnode rootElm = responseDocument.getRootElement(); // soapenv:Envelope
            Dom.Xmlnode bodyElm = rootElm.getChildElement('Body', NS_SOAP); // soapenv:Body 
            Dom.Xmlnode faultElm = bodyElm.getChildElement('Fault', NS_SOAP); // soapenv:Fault
            Dom.Xmlnode faultStringElm = faultElm.getChildElement('faultstring', null); // faultstring          
            throw new LoginException(faultStringElm.getText()); 
        }
        // As per http://wiki.developerforce.com/page/Enterprise_Login
        Dom.Document responseDocument = res.getBodyDocument();
        Dom.Xmlnode rootElm = responseDocument.getRootElement(); // soapenv:Envelope
        Dom.Xmlnode bodyElm = rootElm.getChildElement('Body', NS_SOAP); // soapenv:Body 
        Dom.Xmlnode loginResponseElm = bodyElm.getChildElement('loginResponse', NS_SF); // loginResponse
        Dom.Xmlnode resultElm = loginResponseElm.getChildElement('result', NS_SF); // result
        Dom.Xmlnode sessionIdElm = resultElm.getChildElement('sessionId', NS_SF); // sessionId
        return sessionIdElm.getText();
    }
    public class LoginException extends Exception {}
}

Apex Class: Call above created web service in destination Org.(In Destination Org)
public class fatchAccountRecords{
    public static String fetchAccounts(){
        string strSessionid = loginsalesforce.login();
        
        HttpRequest req = new HttpRequest();		
		//String strEndpointURL = 'https://na15.salesforce.com/services/apexrest/BoxRecords';
		String strEndpointURL = '<YOUR ORGS ENDPOINT URL>/services/apexrest/BoxRecords';
        req.setEndpoint(strEndpointURL);
        req.setMethod('GET');  
        //req.setBody(''); 
        req.setTimeout(60000);
        req.setHeader('Authorization','Bearer '+strSessionid );
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');        

        HttpResponse res =  new Http().send(req);
        system.debug('response'+ res);
        system.debug('response'+ res.getBody());
        return res.getBody();
    }    
}

Let me know if you have any question on this.

Thank You,
Hitesh Patel
Email :- hiteshpatel.aspl@gmail.com
http://mrjavascript.blogspot.in/