Showing posts with label rest api. Show all posts
Showing posts with label rest api. Show all posts

Sunday, October 17, 2021

How to write SOQL query in Java

In this post i will tell you how to write SOQL apex query in java. 


Before reading this post i will recommend you to go through Salesforce java integration post.
Variable baseUri in the code is basicallly your org's instance. To know more about how to get it refer my recommended post.

Java Code :

HttpClient httpClient = HttpClientBuilder.create().build(); String url = baseUri + "/services/data/v48.0/query?q=/services/data/v50.0/query?q=Select+id,name+from+account"; HttpGet httpGet = new HttpGet(url); httpGet.addHeader(oauthHeader); httpGet.addHeader(prettyPrintHeader); response = httpClient.execute(httpGet);

In java you have to use special character encoding to write the SOQL. Below are some of the examples for referance.

SOQL Apex : select id from account where name like '%d%'

SOQL Java : select+id+from+account+where+name+like+'%25d%25'

SOQL Apex : select id,name from account where name = 'Pyramid Construction'

SOQL Java : select+id,name+from+account+where+name+=+'Pyramid+Construction'


For metadata objects(Tooling api objects):


Tooling api objects are those which contain records in the form of metadata. You can query tooling api objects in java like below:

String url = baseUri +"/services/data/v52.0/tooling/query?q=+Select+id,Name+from+MetadataContainer"


Thanks, 
Lovesalesforceyes

Sunday, August 1, 2021

How to get single email message limit with apex code in salesforce

This post explains how to get daily single email message(total and remaining) limits with apex code in salesforce. For that you have to hit the rest api end url(/services/data/v51.0/limits) that will return all the salesforce limits. From that you can only get the email limits and use it. Below are the two apex classes for that. SingleEmailDailyLimit class hit the endpoint with the required headers and generated the json response . SingleEmailDailyLimitWrapper class parses the json response and gives the result in required format. Below is both the apex classes:

SingleEmailDailyLimit.cls :


public class SingleEmailDailyLimit {
    public static void mailLimit(){
Http h=new http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://lovesalesforce-dev-ed.my.salesforce.com/services/data/v51.0/limits');
        req.setHeader('Authorization', 'Bearer '+userinfo.getSessionId());
        req.setHeader('Content-Type', 'application/json');
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        SingleEmailDailyLimitWrapper result = new SingleEmailDailyLimitWrapper();
        result = SingleEmailDailyLimitWrapper.parse(res.getBody());
        system.debug('Total daily email limit of your org is : '+result.SingleEmail.Max);
        system.debug('Remaining daily email limit of your org is : '+result.SingleEmail.Remaining);
    }
    
}


SingleEmailDailyLimitWrapper.cls :


public class SingleEmailDailyLimitWrapper {
    
    public SingleEmail SingleEmail;
    public class SingleEmail {
        public Integer Max;
        public Integer Remaining;
    }
    public static SingleEmailDailyLimitWrapper parse(String json) {
        return (SingleEmailDailyLimitWrapper) System.JSON.deserialize(json, SingleEmailDailyLimitWrapper.class);
    }
}


Output :


Single email message limit in salesforce

Thanks, 
Lovesalesforceyes


Friday, March 5, 2021

Salesforce and java integration with rest api

Before starting salesforce java integration, let's discuss the requirements needed to integrate java and salesforce with rest api. 

There are five variables in code which you need to understand what they are :

1.) userName  = Username of salesforce credentials.

2.) passWordAndToken = Password of salesforce and security token combined without any space. If your password is ABC and token is 123 then passWordAndToken is ABC123. You can generate token by My setting => Personal => Reset my security token

3.) loginEnvUrl = If you want to login production then loginEnvUrl is "https://login.salesforce.com" but if you want to login production then loginEnvUrl is "https://test.salesforce.com".

4.) clientId and clientSecret = You can get clientId and clientSecret by setup => create => Apps => connected apps

Connected Apps Salesfore


Client Key and Client Secret


Jars required :

You will need four jar files for this integration and the four jars are required otherwise you will get an error. I am providing the link to all the jar files you can download from here.

Salesforce_Java_Integration_Jars


Java Code :

package Integration;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Salesforce_Java_Integration {

public Salesforce_Java_Integration()
{
final String baseUri;
final Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
final Header oauthHeader;
final String userName  = "n*********gmail.com";               
final String passWordAndToken  = "***************************";    
final String loginEnvUrl  = "https://login.salesforce.com";
final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
final String clientId     = "3MVG97quA*************************bfh";
final String clientSecret = "7117DE190*****************FD40809299AE";

HttpResponse response = null;
HttpClient httpclient = HttpClientBuilder.create().build();
// Create login request URL
String loginURL = "";
try {
loginURL = loginEnvUrl + GRANTSERVICE +
"&client_id="+URLEncoder.encode(clientId, "UTF-8")+
"&client_secret=" +clientSecret +"&username=" +
URLEncoder.encode(userName, "UTF-8") +
"&password=" +URLEncoder.encode(passWordAndToken , "UTF-8");

System.out.println("loginURL---- "+loginURL);
HttpPost httpPost = new HttpPost(loginURL);
{
// POST request to Login
response = httpclient.execute(httpPost);
if(null!=response) {
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
System.out.println("Login Successfull");
}
else{
System.out.println("Error whie Login");
}
String getResult = null;
getResult = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = null;
String loginAccessToken = null;
String loginInstanceUrl = null;
jsonObject = (JSONObject)
                                                              new JSONTokener(getResult).nextValue();
loginAccessToken = jsonObject.getString("access_token");
loginInstanceUrl = jsonObject.getString("instance_url");
baseUri = loginInstanceUrl;
oauthHeader = new BasicHeader("Authorization", "OAuth "
                                                    + loginAccessToken) ;
// release connection
httpPost.releaseConnection();
System.out.println("oauthHeader===>>>"+oauthHeader);
System.out.println("prettyPrintHeader===>>>"+prettyPrintHeader);
System.out.println("baseUri===>>>"+baseUri);
}
else {
System.out.println("Please check your internet connection !!!");
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(final String[] args)
{
@SuppressWarnings("unused")
Salesforce_Java_Integration Integration = new Salesforce_Java_Integration();
}
}


OutPut:

Java Salesforce Integration

Now with the help of outhHeder, PrettyPrintHeader and baseUri you can get and set data in salesforce.


Thanks, 
Lovesalesforceyes



Thursday, March 4, 2021

Publish knowledge articles with rest api in salesforce

Whenever you create an article in salesforce its publish status is 'draft' by default. You have to publish that article to make it 'online'. In this blog we will learn how to publish draft article in salesforce by Rest API with the help of workbench :

Publish Draft article :

Here I am publishing one draft article. As you can see there is one one draft article in my org.

Draft articles in salesforce


First you need to find articleVersionId of the article which you want to publish. To get the articleVersionIdList you have to query on the KnowledgeArticleVersion object.

"SELECT KnowledgeArticleId, Id, PublishStatus, Title, UrlName FROM KnowledgeArticleVersion"

soql to get knowledgeVersionId


Method :- Post
URL:- /services/data/v50.0/actions/standard/publishKnowledgeArticles

Request Body :-
                        {
                            "inputs" : [
                             {
                                "articleVersionIdList" : [ "ka02x000000WGbwAAG" ],
                                 "pubAction" : "PUBLISH_ARTICLE"
                             }
                             ]
                         }

 

If you want to mass publish articles, you have to give comma separated id's in articleVersionIdList value in the request body.

Publish knowledge articles with workbench

Article Published:-  After executing the rest service, you can see the article is published now.

published articles in salesforce

Thanks, 
Lovesalesforceyes


Sunday, February 14, 2021

Insert attachments in salesforce with rest api

In this blog we will learn how to insert file type attachment in salesforce by Rest API with the help of workbench :

There is basically four subfields of file field in salesforce :

  1.  FieldName__Name__s  : Name of the attachment file.
  2.  FieldName__Body__s  :  Body of the attachment file.
  3.  FieldName__Length__s  : Length of the attachment file.
  4. FieldName__ContentType__s  : Type of the attachment file.  It is a picklist field which means it accepts only the values that are listed in picklist values. It has values like :
    application/html
    application/java-archive
    application/javascript
    application/msword
    application/octet-stream
    application/octet-stream;type=unknown
    application/pdf .... etc....

When inserting attachment with rest api only three subfields are required Name, Body and ContentType. Length will automatically generated after insertion of record. In The place of  Body__s subfield you have to give Base64 of that file which you want to insert. In the place of Name__s you have to give the name of the file and In the place of  ContentType__s you have to give the type of that file. Let's get Start :

Create a record with attachment :

Here i am creating one record with and inserting text file as attachment :

Method :- Post
URL:- /services/data/v50.0/sobjects/Knowledge__kav
Request Body :-

Insert attachment with rest api salesforce

In the place of Attachment__Body__s , I am giving converted base64 of text file.

Response :-

insert attachment with rest api salesforce

Record Created:-

insert attachment in salesforce


Thanks, 
Lovesalesforceyes

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...