Monday 24 December 2012

Apex Generation Failed Unable to find element + Amzon S3

Hi,

While generating Apex code from wsdl provided by Amazon (For S3) I got the above mentioned error. Below is a snippet from WSDL file.

 <xsd:schema
     elementFormDefault="qualified"
     targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/">
      <xsd:include schemaLocation="AmazonS3.xsd"/>
    </xsd:schema>


To Resolve the error I downloaded XSD file from Amzon only and replaced the content of tag <xsd:include> with the content of the XSD file, and I was able to generate the Apex code file.

Sunday 23 September 2012

Open Connection SalesForce Rest API

Hi

I have written a sample code in java to make a persistent connection to Salesforce's Rest API, This example uses Oauth Grant_Type ="password" to provide a fresh access_token each time the request is made.

Please find the code below. To make this code work you need to add package <httpcomponents-client> to your classpath. which can easily be downloaded from  http://hc.apache.org/httpcomponents-client-ga/

 


Please find the code :

package connection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONValue;



public class OauthConnection {

    //Variables to be populated after gaining the Access token.
    private String accessToken = null;
    private Map<String, String> oauthLoginResponse;
   
    //Constants to be used in this class.
    private static final String clientId = <Your Client ID>;  
    private static final String clientSecret = <Your Client Secret>;
    private static final String environment = "<SalesForce Instance>";
    private static final String authUrl = "/services/oauth2/token";
    private static final String restUrl = "/services/data/v25.0/";
    private static final String queryUrl = "/services/data/v25.0/query";
    private static final String username = "<Your SFDC USER NAME>";
    private static final String password = <SFDC PASSWORD WITH SECURITY TOKEN>;
   
   
   
    public static void main(String[] args){
        try{
       
            OauthConnection oc = new OauthConnection();
            oc.oAuthSessionProvider();
           
            oc.executeQuery();
       
        }catch(Exception e){
            e.printStackTrace();
        }
      }
       
    public void oAuthSessionProvider()
            throws HttpException, IOException
    {
        // Set up an HTTP client that makes a connection to REST API.
        DefaultHttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);

        // Set the SID.
        System.out.println("Logging in as " + username + " in environment " + environment);
        String baseUrl = environment + authUrl;
       
        // Send a post request to the OAuth URL.
        HttpPost oauthPost = new HttpPost(baseUrl);
       
        // The request body must contain these 5 values.
        List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
        parametersBody.add(new BasicNameValuePair("grant_type", "password"));
        parametersBody.add(new BasicNameValuePair("username", username));
        parametersBody.add(new BasicNameValuePair("password", password));
        parametersBody.add(new BasicNameValuePair("client_id", clientId));
        parametersBody.add(new BasicNameValuePair("client_secret", clientSecret));
        oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));

        // Execute the request.
        System.out.println("POST " + baseUrl + "...\n");
      
        HttpResponse response = client.execute(oauthPost);
        int code = response.getStatusLine().getStatusCode();
      
        System.out.println("Code >> " +code);
       
        //populate Response map to fetch ACCESS TOKEN for any future call.
        this.oauthLoginResponse = (Map<String, String>)JSONValue.parse(EntityUtils.toString(response.getEntity()));
       
        System.out.println("OAuth login response");
       
        for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet())
        {
            System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
        }
       
        //Populate Access Token 
        this.accessToken = oauthLoginResponse.get("access_token");
        System.out.println("");
    }
   
    public void executeQuery(){
         DefaultHttpClient httpClient = new DefaultHttpClient();
       
        List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
        qsList.add(new BasicNameValuePair("q", "Select a.ParentId, a.OwnerId, a.Name, a.IsPrivate,  a.Id, a.Description, a.ContentType, a.BodyLength, a.Body " +
                "                                From Attachment a where  a.ParentId = '00390000006DEGb'"));
       
        String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
        HttpGet get = new HttpGet(environment + queryUrl+"?"+queryString);
        get.setHeader("Authorization", "OAuth " + accessToken);
        try{
            HttpResponse queryResponse = httpClient.execute(get);
           
            System.out.println(queryResponse.getStatusLine().getReasonPhrase());
              Map<String, Object> querynfo = (Map<String, Object>)
                        JSONValue.parse(EntityUtils.toString(queryResponse.getEntity()));
             
              System.out.println("Query response");
                for (Map.Entry<String, Object> entry : querynfo.entrySet())
                {
                    System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
                }
                System.out.println("");
             
        }catch(Exception e){
            e.printStackTrace();
        }
       
    }
 }

Tuesday 4 September 2012

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

While creating New Force.com project or while adding new resource to your already existing projects, if you are getting the below mentioned error message.

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

 Please follow the steps below.

This error is because of the Java 1.7 so till the time this release gets fixed, we need to downgrade our JRE to 1.6, this could be a really tedious task and the simplest way that I found and  I did was, Replaced the contents of floder C:\Program Files\Java\jre7 with that of C:\Program Files\Java\jre6 (i already had java 6 hence i could do so, If you do not have you would need to download Jre6).

Doing above mentioned swapping of files saved me from uninstalling (Java7) and reinstalling (Java6) just by copying files of these two folders i can anytime switch back to java7 or java6 as per my requirement.

Friday 31 August 2012

Apex DataLoader Command Line Password

To Generate the password to be used in Command Line Dataloader operations, please follow the below mentioned steps.

1.) Open command prompt in your system.
2.) Go to bin directory of your data loader e.g C:\Program Files\Dataloader\bin
3.) Type encrypt.bat -g <password>
4.) you will get an encrypted password like varun1233123
5.) Copy above password into the config.properties file sfdc.password = varun1233123

with the steps above you have generated you password to be used in dataloader beans.

Friday 2 March 2012

Tool for SalesForce Profile Comparison, Field Level Security

Hi many a time while working in Salesforce we get the boring and mechanical task of comparing profiles, and out of this worst part is field level security. This task gets worse when we have some objects with large number of custom fields. So to sort this out I have written a java code that will read files from two different folders(Download profiles in your eclipse and pass the path of the Profile folders from two different project) or if you want to compare just two files, put them in two folders and provide the path of those two folders.

After comparison, the code will generate a parent directory, containing children directories named on the profile, the children directories will contain two csv files each one for object comparison and other for Field level security comparison.

To execute this code, you just need eclipse of core java libraries, and change the path mentioned in the class to that of your system specific path, and get the results.

please find the code below.



Tuesday 31 January 2012

Problem: failed to create task or type antlib:com.salesforce:deploy

Hi, Today while trying to deploy my org's metadata on production using Salesforce's migration tool I faced the error "Problem: failed to create task or type antlib:com.salesforce:deploy".

I was using Ubuntu 11.04 (It should be useful in MAC systems as well), so i discovered the solution to this problem is we need to download the salesforce migration tool from our deployment org's Your Name | Setup | Develop | Tools.

After downloading the zip file on your drive, extract the content and copy the ant-salesforce.jar to /usr/share/ant/lib/ 

This should resolve the particular error.





Monday 30 January 2012

Download Salesforce Attachments on Drive.

Many a times in salesforce we need to download selective attachments, in that case the SFDC's Data Export tool doesn't seem helpful as it will download all the attachments (yes you can select objects but not the records in that object). So for this purpose i have written a small Java code, that will take help of the enterprise wsdl of the org from which i need to extract the data.

To generate code stub from enterprise wsdl you need WSC jar, which can be downloaded easily from net, once you get it, go to command prompt and paste the below mentioned command, with your own directory structure and it will generate the required jar to make connections to your org.

java -classpath  < YOUR PATH OF WSC JAR>\wsc-20.jar com.sforce.ws.tools.wsdlc  <PATH where you have kept your enterprise wsdl> \enterprise.wsdl  <PATH where you want to genrate the jar> \Enterprise.jar

Include this newly generated jar into your Java(Eclipse's) build path, and you are ready to make connection to your org.

This code will also create a CSV file to relate the parent with that to its attachment(s).


package com.mypackage;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Attachment;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class ExportAttachments {
 
  static final String USERNAME = "<YOUR USER NAME>";
  static final String PASSWORD = "<YOUR PASSWORD>";
  static EnterpriseConnection connection;
  static final String ATTACHIDS ="00P50000007HYMJEA4,00P50000007HmAjEAK,00P50000004CmZ3EAK";
  static final String AccountIds = "0015000000SQSmIAAX,0015000000bBP1pAAG,0015000000bCfjTAAS,0015000000LKHCFAA5";
 
  static List<String> str = new ArrayList<String>();
  static List<String> stracct = new ArrayList<String>();
  static Map<String,String> idMap = new HashMap<String,String>();
  static Map<String,String> csvMap = new HashMap<String,String>();
 

  public static void main(String[] args) {

    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    //config.setTraceMessage(true);
    str = Arrays.asList(ATTACHIDS.split(","));
    stracct = Arrays.asList(AccountIds.split(","));
    for(String s:stracct){
        idMap.put(s,s);
    }
    try {
     
      connection = Connector.newConnection(config);
     
      // display some current settings
      System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
      System.out.println("Service EndPoint: "+config.getServiceEndpoint());
      System.out.println("Username: "+config.getUsername());
      System.out.println("SessionId: "+config.getSessionId());
   
      queryAccounts();
      createCSV();
      queryAttachments();
     
    } catch (ConnectionException e1) {
        e1.printStackTrace();
    } 

  }
 
 private static void queryAccounts() {
       
        
        try {
          for(String s:idMap.keySet()){
          // query for the 5 newest contacts     
          QueryResult queryResults = connection.query("SELECT Id, VSX_ID__c " +
                  "FROM Account WHERE Id in ('"+s+"')");
          if (queryResults.getSize() > 0) {
            for (int i=0;i<queryResults.getRecords().length;i++) {
              // cast the SObject to a strongly-typed Account
              Account a = (Account)queryResults.getRecords()[i];
              csvMap.put(a.getId(),a.getVSX_ID__c());
            }
          }
           }
        } catch (Exception e) {
          e.printStackTrace();
        }   
       
      }
 
  private static void queryAttachments() {
      try{
          for(String s:str){
           QueryResult queryResults = connection.query("Select Id, ParentId, Name, ContentType, Body " +
            "From Attachment WHERE id in('"+s+"')");
       
           if (queryResults.getSize() > 0) {
               for (int i=0;i<queryResults.getRecords().length;i++) {
                  // cast the SObject to a strongly-typed Contact
                    Attachment a = (Attachment)queryResults.getRecords()[i];
                    writeOnDisk(a.getId()+"-"+a.getName(),a.getBody());
                    System.out.println("Id: " + a.getId() + " - Name: "+a.getName()+" "+" - Account: "+a.getParentId());
                }
              }
          }
      }catch (Exception e) {
          e.printStackTrace();
        }   
     
     
  }
 
  private static void writeOnDisk(String fileName, byte[] bdy){
      try
      {
          String filePath = "C://Documents and Settings//varun//Desktop//JavaExport//"+fileName;
          FileOutputStream fos = new FileOutputStream(filePath);//File OutPutStream is used to write Binary Contents like pictures
          fos.write(bdy);
          fos.close();
      }
      catch (IOException e)
      {
      System.out.println(e.getMessage());
      }
  }
 
  private static void createCSV(){
      try
      {   
          String toWrite="";
   
          if(csvMap!=null){
              for(String s:csvMap.keySet()){
                  toWrite +="\""+s+"\""+","+"\""+csvMap.get(s)+"\"\n";
              }
         
          System.out.println(toWrite);
          String file_name = "C://Documents and Settings//varun//Desktop//JavaExport/AccountVSX.csv";
          FileWriter file = new FileWriter(file_name);
          BufferedWriter out = new BufferedWriter (file);
          out.write(toWrite);
          out.close();
          }
      }
      catch (IOException e)
      {
          System.out.println(e.getMessage());
      }
  }


}