Kaizen #15 - Java SDK for Self Client

Kaizen #15 - Java SDK for Self Client

Hello everyone!
 
Welcome to yet another post in the Kaizen series.
This week, we are going to discuss the  Java SDK for a self client .
 
What is a Software Development Kit (SDK)?
 
A software development kit contains all the tools (compiler, debugger, code samples, and so on) that are needed to create applications in one package. SDKs are language-specific and thus used to build client applications in a specific programming language. 
 
Java Software Development Kit
 
Java SDK allows you to create a client Java applications that can be integrated with Zoho CRM effortlessly. It serves as a wrapper for the  REST APIs , thus making it easier to use the services of Zoho CRM.

Here is a sample of how SDK acts as a middleware between Zoho CRM and Client Java Application.



What can you do with the Java Software Development Kit?
  • You can use Java SDK to exchange data between Zoho CRM and the client Java application. 
  • The authentication process becomes hassle-free with Java SDK. Since it is handled in the SDK code by default, you need not worry about generating the grant token, access/refresh tokens every time you sync data between Zoho CRM and your self client. 
Environment Setup

Java SDK requires Java version 7 or above to be set up in your development environment.

Including the Java SDK in your project

You can include the Java SDK in your project using:
a.  Maven distribution
b.  Gradle
c.  Downloadable JARs

a. Maven distribution - It is a build automation tool used primarily for Java projects. Include the following code to your pom.XML file. 

<repositories>
    <repository>
        <id>java-sdk</id>
        <url> https://maven.zohodl.com </url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.zoho.crm</groupId>
        <artifactId>java-sdk</artifactId>
        <version>2.0.2</version>
    </dependency>
</dependencies>

b. Gradle - It is also a build tool, similar to Maven. The major difference is that, instead of XML files, Gradle uses Groovy (a domain-specific programming language) to declare the Java project configuration. You need to add the following code to your build.gradle file. 

repositories{
    maven { url " https://maven.zohodl.com " }
}
dependencies{
    implementation 'com.zoho.crm:java-sdk:2.0.2'
}


c. Downloadable JARs (by Zoho) - Java Archive is a platform-independent file format that aggregates many files into one. The JAR file consists of the SDK. You have to download individual dependency JARs and add them to your reference libraries in your Java application:  Download JAR (SDK)

Click here to download the dependency JARs.

The list of dependency JARs are:

  • hamcrest-all-1.3 : Hamcrest consists of a single jar file that contains base classes and a library of useful matcher implementations.
  • httpclient-4.4.1 : The Apache HttpClient library allows you to handle HTTP requests.
  • httpcore-4.4.4 : HttpCore is a set of low-level HTTP transport components that you can use to build custom client and server-side HTTP services.   
  • httpmime-4.5.3 : The Apache HttpMime library consists of MIME code entities.
  • json-20170516 : The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and CDL. 
  • servlet-api-2.5 : Servlet API consists of classes to support HTTP servlet.
  • commons-logging-1.1.3 : The commons-logging JAR provides an API for logging in server-based applications that you can use around a variety of different logging implementations.
  • mysql-connector-java-5.1.44-bin.jar : You need to include this JAR if you are using a MySQL database. MySQL Connector JAR provides connectivity for java client applications with MySQL Connector (a driver that implements the Java Database Connectivity (JDBC) API)

How to start using the Java SDK?

In this section, we will discuss how to start using the Java SDK for your application (authenticated via self-client) which uses Zoho CRM.

  1. Prerequisite: Register your application
  2. Knowlege Base: Adding persistence classes
  3. Initialization

1. Prerequisite: Register your application

All the Zoho CRM APIs are authenticated by the OAuth2.0 standards . It is mandatory to authenticate the self client with Zoho.

Step 2: Click ADD CLIENT



Step 3: Choose Self Client and click CREATE NOW



Step 4: Choose the Client Type as Self Client , and click CREATE .



Step 5: Once you successfully register your self-client, you will receive a Client ID and Client Secret .


2. Knowledge Base: Adding persistence classes
This section consists of two parts:
a. Initializing your client application
b. Adding persistence classes

a. Initializing your client application
To authenticate the client application, you need to add the following key-value configuration pairs to the initialization code of your java client.

Key Description

Key
Description
client_id, client_secret, and redirect_uri 
mandatory
You can get these values after registering your client.
currentUserEmail 
mandatory
The Email ID of the current user.
persistence_handler_class
mandatory
The implementation of ZohoOAuthPersistenceInterface
logFilePath
optional
The absolute/relative file path of the file that stores the logs.
domainSuffix
optional
The domain from which the API calls are made. It can be .com (for US), .eu (for Europe), .cn (for China). If you specify this value, you need not specify apiBaseUrl  and iamURL.
accessType
optional
The type of environment from which the API calls are made. Possible values are "Production", "Development", or "Sandbox"
access_type
optional
Must be set as as "offline". 
Online OAuth client is not supported by the Java SDK as of now
apiBaseUrl 
optional
The URL that is used to make API calls. You need not specify this value if you give domainSuffix. 
The possible values are:
iamURL 
optional
The accounts URL. You need not specify this value if you specify domainSuffix. The possible values are:
mysql_password and mysql_username
mandatory when you use MySQL persistence
The MySQL username and password, respectively. 

Key Value Configuration 

HashMap <String, String> zcrmConfigurations = new HashMap <String, String >();
zcrmConfigurations.put("minLogLevel", "ALL");
zcrmConfigurations.put("currentUserEmail","{user_email_id}");
zcrmConfigurations.put("client_id","1000. xxxxxxxxx");
zcrmConfigurations.put("client_secret","xxxxxxxxxxxx");
zcrmConfigurations.put("redirect_uri","");
zcrmConfigurations.put("persistence_handler_class","com.zoho.oauth.clientapp.ZohoOAuthDBPersistence ");//for database. "com.zoho.oauth.clientapp.ZohoOAuthFilePersistence" for file, user can implement his own persistence and provide the path here
zcrmConfigurations.put("oauth_tokens_file_path","/path/to/oauthtokens.properties");//optional path can be absolute(Ex:/User/Document/testapplication/src/oauthtokens.properties) or relative (Ex: /testapplication/src/oauthtokens.properties)
zcrmConfigurations.put("domainSuffix","com");//optional. Default is com. "cn", "eu", and "in" supported
zcrmConfigurations.put("accessType","Production");//Production->www(default), Development->developer, Sandbox->sandbox(optional)
zcrmConfigurations.put("access_type","offline");//optional
zcrmConfigurations.put("apiBaseUrl"," https://www.zohoapis.com ");//optional
zcrmConfigurations.put("iamURL"," https://accounts.zoho.com ");//optional
zcrmConfigurations.put("logFilePath","/path/to/file.log");//path can be absolute(Ex:/User/Document/testapplication/src/file.log) or relative (Ex: /testapplication/src/file.log)
zcrmConfigurations.put("mysql_password","pass@123");//optional
zcrmConfigurations.put("mysql_username",username");//optional
ZCRMRestClient.initialize(zcrmConfigurations);//for initializing

2. Adding persistence class
Your application should retain tokens (grant, access, and refresh tokens) to automate the process of data-sync between your java application and Zoho CRM. 

You can persist tokens in your application by using any one of the below mentioned persistence methods: 
a. By using an implementation of the inbuilt ZohoPersistenceHandler interface
    • ZohoOAuthFilePersistence (To store tokens in a File )
    • ZohoOAuthDBPersistence (To store tokens in a Database
b. By using your own implementation

Let us now look into each of the above mentioned methods.

a. By using an implementation of the inbuilt ZohoPersistenceHandler interface

Our Java SDK provides two default implementations of the ZohoPersistenceHandler interface within the client library. They are:
i. ZohoOAuthFilePersistence
ii. ZohoOAuthDBPersistence

i. ZohoOAuthFilePersistence - This type of persistence uses a file to read and write OAuth tokens. The file persists the token of a single user. So, it is best used for the 'self-client' type of authentication since it involves only one user.  

Values to be given in configuration map

persistence_handler_class =com.zoho.oauth.clientapp.ZohoOAuthFilePersistence
oauth_tokens_file_path =absolute or relative path of the "oauthtokens.properties" file in the workspace.

ii. ZohoOAuthDBPersistence - This type of persistence uses MySQL persistence. You can use this type of persistence if you have more than one user using the application. 

Some of the prerequisites for using this type of persistence are:

  • MySQL should be running in the same machine serving at the default port 3306.
  • The database name should be "zohooauth".
There must be a table "oauthtokens" with the columns "useridentifier"  (varchar(255)), "accesstoken" (varchar(255)), "refreshtoken" (varchar(255)) and "expirytime" (bigint).

Values to be given in configuration map

persistence_handler_class =com.zoho.oauth.clientapp.ZohoOAuthDBPersistence
mysql_username =root
mysql_password ={your MySQL password}

b. By using your own implementation

You can also use your own implementation. The ZohoPersistenceHandler interface must have the following methods:

  • getOAuthTokens() — invoked to fetch the saved tokens. This method should return ZohoOAuthTokens object for the library to process it. 
  • saveOAuthData(ZohoOAuthTokens tokens) — invoked to store the tokens.
  • deleteOAuthTokens() — invoked to delete the tokens.

C. Initialization

Intializing your application involves the following steps:

Step 1: Generating the grant token
Step 2: Generating the access and refresh tokens using the grant token
Step 3: Generating the access token using the refresh token

Step 1: Generating the Grant Token



(ii). Choose Self-Client
(iii). Enter the comma separated ZohoCRM scopes along with aaaserver.profile.READ . Choose the time duration (the grant token will be valid only till the time chosen here) and enter the description . Now, click GENERATE.


(iii). Copy the grant token displayed


Step 2: Generating the Access and Refresh Tokens

After obtaining the grant token, put the following code snippet in a java file and execute it from your main class to get access and refresh tokens. 

ZCRMRestClient.initialize(configurations_map);
ZohoOAuthClient cli = ZohoOAuthClient.getInstance();
String grantToken = “paste_the_self_authorized_grant_token_here”;
ZohoOAuthTokens tokens = cli.generateAccessToken(grantToken);
String accessToken = tokens.getAccessToken();
String refreshToken = tokens.getRefreshToken();
System.out.println("access token = " + accessToken + " & refresh token = " + refreshToken);

2a. On using ZohoOAuthFilePersistence method
The access and refresh tokens are generated and stored in the oauth_tokens.properties file .

2b. On using ZohoOAuthDBPersistence method
The access and refresh tokens are generated and stored in " oauthtokens "  table of your MySQL

Step 3: Generating the Access token from Refresh token
Use the below code snippet to generate the access token from the refresh token.

ZohoOAuthClient client = ZohoOAuthClient.getInstance();
client.generateAccessTokenFromRefreshToken(refreshToken, userMailId);

Sample SDK Code

When you build your application using the Java SDK, the code template will be similar to:




Refer to the attachment to get the code. For more sample codes, refer to our SDK guide .

The isTokenGenerated Method:

This method checks if the access token has already been generated or not. It returns a boolean value:

true - The access token has already been generated. 
false - The access token has not been generated previously, thus, it shifts the control to the code snippet that leads to access token generation.

See you next week with another post.
Cheers!

Previous 'Kaizen' - Notification API
Next 'Kaizen' - Python SDK



    Access your files securely from anywhere



                          Zoho Developer Community




                                                  • Desk Community Learning Series


                                                  • Digest


                                                  • Functions


                                                  • Meetups


                                                  • Kbase


                                                  • Resources


                                                  • Glossary


                                                  • Desk Marketplace


                                                  • MVP Corner


                                                  • Word of the Day


                                                  • Ask the Experts





                                                            Manage your brands on social media



                                                                  Zoho TeamInbox Resources



                                                                      Zoho CRM Plus Resources

                                                                        Zoho Books Resources


                                                                          Zoho Subscriptions Resources

                                                                            Zoho Projects Resources


                                                                              Zoho Sprints Resources


                                                                                Qntrl Resources


                                                                                  Zoho Creator Resources



                                                                                      Zoho CRM Resources

                                                                                      • CRM Community Learning Series

                                                                                        CRM Community Learning Series


                                                                                      • Kaizen

                                                                                        Kaizen

                                                                                      • Functions

                                                                                        Functions

                                                                                      • Meetups

                                                                                        Meetups

                                                                                      • Kbase

                                                                                        Kbase

                                                                                      • Resources

                                                                                        Resources

                                                                                      • Digest

                                                                                        Digest

                                                                                      • CRM Marketplace

                                                                                        CRM Marketplace

                                                                                      • MVP Corner

                                                                                        MVP Corner





                                                                                          Design. Discuss. Deliver.

                                                                                          Create visually engaging stories with Zoho Show.

                                                                                          Get Started Now


                                                                                            Zoho Show Resources


                                                                                              Zoho Writer Writer

                                                                                              Get Started. Write Away!

                                                                                              Writer is a powerful online word processor, designed for collaborative work.

                                                                                                Zoho CRM コンテンツ










                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方




                                                                                                            • Recent Topics

                                                                                                            • If Problema Formula

                                                                                                              Ceil(Datecomp(${Seguimiento de Venta.Fecha de la proxima visita},Now())/1440) Tengo porblema al plantear el If Quiero que si el valor es dega
                                                                                                            • Zoho CRM - Analytics: How Can I Set Monday as First Day of The Week?

                                                                                                              Hello, In the analytics section of our Zoho CRM (not Zoho Analytics), we would like to track our SDRs' outreach activity. However, it appears that Zoho CRM treats Sunday as the first day of the week for the "This Week" and "Previous Week" filters. How
                                                                                                            • Filter lookup field using client script

                                                                                                              Hi, I used client scipt to filter a lookup field- the trigger is on detail page onload. It works, however sometimes when I start typing in that field the filter is removed and the whole list is shown. What can I do so that should not happen? Thanks
                                                                                                            • Record Locking for Meetings CRM

                                                                                                              How can I lock meetings module in CRM? For other modules I can use Record Locking or Client Script, to lock some fields But for Meetings Client Script and Record Locking are both absent We have a problem, where employees are able to change meeting time
                                                                                                            • Data Model - CRM Adjusting size of Entity boxes

                                                                                                              (Sorry if duplicate, previous post seems to have disappeared.) I am viewing the Data Model for CRM, and while it is great to see such a model, there is an obstacle. Many of the entities show only a subset of their fields. The entity boxes have scrollbars
                                                                                                            • The Status in Zoho Finance is inaccurate

                                                                                                              We have many overdue invoices, but when we try to filter it by Status Overdue in the Zoho Finance Module it shows it as none This is also creating a problem when I need to Create a Chart or KPI for overdue Invoices If I open the Invoice I can see the
                                                                                                            • Zoho API integration - missing tables even after using MODULES.READ scope across all modules

                                                                                                              I tried to connect Zoho CRM to my Airbyte connector. I used clientid, client secret and the refresh token to do so. All I see is 77 tables available after connector. I miss few tables like lead agreement deal contact Can you please let me know, what scope
                                                                                                            • In Zoho CRM, is it possible to transition from Approach 1 to Approach 3 based on the contract End Date? automatically

                                                                                                              In Zoho CRM, is it possible to transition from Approach 1 to Approach 3 based on the contract End Date? I have one issue between Approach 1 to Approach 3 there is another transition Approach 2 Iam faceing the issue if use the blue print API means i able
                                                                                                            • How to get the Logo

                                                                                                              Hii Can you please Help me the how to get the Company Setting Photo using the Deluge I will Write this Code But here Will Fetch the Photo_id but We needed the image curl1= "https://www.zohoapis.eu/crm/v7/org"; info curl1 ; getTemplate1 = invokeurl [ url
                                                                                                            • subscribe email list for offer and updates is not working for zoho commerce

                                                                                                              my subscribing to email list is not working for offers and updates for my ecommerce website soignee it is saying please wait can anyone tell me the reason for this
                                                                                                            • "In Zoho CRM, during the Blueprint transition to the QC stage, I want to make the 'Packing Proof' image field mandatory."

                                                                                                              @Dr Saurabh Joshi @Haiku Technical Support @Ishwarya SG @Sparrow Hill President @Hugh Marshall "In Zoho CRM, during the Blueprint transition to the QC stage, I want to make the 'Packing Proof' image field mandatory."
                                                                                                            • Can Zoho CRM Emails be used in Zoho Analytics in any capacity?

                                                                                                              We're wanting to display details about Lead Activity in regular reports through Zoho Analytics but we're having difficulty integrating Emails at all. We'd like to be able to note when an email is received and when it is sent somewhere other than just
                                                                                                            • Recurring Events Not Appearing in "My Events" and therefore not syncing with Google Apps

                                                                                                              We use the Google Sync functionality for our events, and it appears to have been working fine except: I've created a set of recurring events that I noticed were missing from my Google Apps calendar. Upon further research, it appears this is occurring
                                                                                                            • Product Updates in Zoho Workplace applications | March 2025

                                                                                                              Hello Workplace Community, Let’s take a look at the new features and enhancements that went live across all Workplace applications this March. Zoho Mail Include original attachments in reply email When you Reply or Reply All to an email, original attachments
                                                                                                            • Free Webinar Alert! Track, Bill, Get Paid: Streamline Finances with Zoho Books and Zoho Mail

                                                                                                              Hello Zoho Community! Struggling to keep track of invoices, payments, and client communication? We’ve got you covered! In this webinar, we’ll show you how Zoho Mail and Zoho Books work together to simplify invoicing, track payments, and streamline financial
                                                                                                            • Bug in Kiosk Studio: GetRecords "Fields to Display" Change does not work

                                                                                                              I made a Change in our Kiosk GetRecords "Fields to Display". The change does not appear in the actual Kiosk. Neither on preview, nor on live usage. Configuration: Actual Kiosk:
                                                                                                            • Field of Lookup Module 2 Way Dynamic Connection

                                                                                                              I have several lookup fields in my custom Module And I have added fields from lookup fields to my module In my account module, I have a field called Quarterly Revenue Forecast But this is only one way i-e the field value is only fetched during record
                                                                                                            • payment gateway disabling in my ecommerce store

                                                                                                              hi i have disabled my payment gateway paytm from my website soigne from the backend but it is showing in my front end part when someone orders my products i want to remove it completelty so that it does not show in the front end part plz give me a suitable
                                                                                                            • "In Zoho CRM, during the Blueprint transition to the image field mandatory and file upload field mandatory

                                                                                                              I want image and file upload field want to be mandatory during the blueprint transition In the QC done Transtion Iwant to make QC done file upload and Case QR Sticker Mandatory In Pre delivery Stage i want to make Site ready file upload field mandagtory
                                                                                                            • View Filter for Date field type doesn't give option for "not in the last" or "before x days"

                                                                                                              I'm trying to set up some saved filters to organize a view better and I want to have saved filters based on the amount of contact that has been had with a client. We have a custom date field that records the last exchange with the client (whether call
                                                                                                            • need a third party to fix email authentication dns records

                                                                                                              at my wit's end - zoho began giving me spf, dmarc, dkim errors two weeks ago fussed with it since and now it seems dkim is the only problem and when i added the dkim record with the key from zoho mail it still wont work tired of this, need someone who
                                                                                                            • Zoho Not Receiving Emails Sent via PHP mail() – Arrives at Gmail/Outlook, but Not Zoho

                                                                                                              I have a PHP script on my website that sends emails using the basic mail() function — not SMTP or wp_mail() from WordPress. The email sends successfully to other addresses I own (like Gmail and Outlook), but emails sent to my Zoho-hosted address are never
                                                                                                            • Custom code ass to header and footer code doesn't appear

                                                                                                              I am trying to insert custom code into both the header and footer of my Zoho site. I edit the site "general settings" as demonstrated in the various articles, click save, but the code does not appear on my site. Is there something special I need to do
                                                                                                            • Differentiating between invoice templates when adding custom fields

                                                                                                              We are adding HS codes to the items which we would like published on our international customers invoices plus other export data required. We don't need this data on our domestic customer invoices. We have setup an invoice template for them but it if
                                                                                                            • Limit POP Downloads to Inbox?

                                                                                                              Hello, When I connect to and download email from my account using the POP3 protocol, it appears that it's also downloading email from my Sent mailbox. Is there any way to limit the POP downloads to Inbox emails only? Thanks!
                                                                                                            • Market Automation is hung in sync with crm in zoho one

                                                                                                              Sync between Market automation and crm stuck in loop. MA says they are connected, but does not allow module selection, building of lists, etc. can not go back around and disconnect and restart. Does not show in "Connected Apps", yet when you ty to connect
                                                                                                            • Currency Field Does Not show commas upon entry - leading to inaccurate entries!

                                                                                                              Hello Zoho.. When our sales reps are entering deals and the profit/revenue it is difficult to accurately enter numbers with lots of zeros when there commas are NOT added until the record is saved. Could commas be added to this filed type as it is being
                                                                                                            • Kaizen #116 - Client Types in Zoho API Console

                                                                                                              Hello everyone! Welcome back to another post in the Kaizen series! This week, we will discuss different client types available in Zoho API Console, and when to use each. When you register an app in Zoho API Console, you typically choose a client type
                                                                                                            • Used Car Inventory Tracker

                                                                                                              I need a to create an inventory database that has detailed information about each car we have in our inventory. Specifically, I need to know exactly how much labor and parts we have into each car as well as the cars purchase price, VIN, color, year, source etc. Budget : Negotiable | Duration : 1 week To leave a private message, please click the link for private response in post Action section.
                                                                                                            • Create Funnel to Track Email Outreach Conversion

                                                                                                              Hello, We would like to create a funnel that measures: N° of emails sent -> N° of emails opened -> N° of emails responded We would like to measure this email response conversion rate for each of our SDRs. We use the analytics tool of Zoho CRM and not
                                                                                                            • Flow-Level Access Permissions in Zoho Flow

                                                                                                              Hi Zoho Flow Team, Hope you're doing well. We would like to request a feature enhancement for Zoho Flow related to user-level access control. Use Case: As Zoho One users, we often work with multiple teams and departments. In our setup, we have several
                                                                                                            • Tip of the week 63- Know your contacts well with polls in Zoho Campaigns

                                                                                                              Communication in its true form is characterised by feedback. In email campaigns there are a few avenues via which you can achieve this. Using polls in Zoho Campaigns is one such way. With polls enabled in campaigns, your contacts can interact with your emails and help you understand them well.     There are three types of polls available to be enabled in your email campaigns:   Basic poll Rating based poll Reaction based poll     Basic poll-    Provide a question and allow the email recipients to
                                                                                                            • Subform data to Sheets

                                                                                                              I have been trying to setup a Zoho Flow automation to bring any Subform input to a Zoho Sheets but it seems impossible to post the subform entries to a Zoho Sheet. Is there any way to do it via Zoho Sheet API? https://www.zoho.com/sheet/help/api/v2/#CONTENT-Insert-row-with-JSON-data
                                                                                                            • Error AS101 when adding new email alias

                                                                                                              Hi, I am trying to add apple@(mydomain).com The error AS101 is shown while I try to add the alias.
                                                                                                            • Filter by technical IDs that should not be displayed

                                                                                                              Hello Zoho and Cumminity. I know I have already found similar requests elsewhere, but have not yet received a solution from Zoho. Therefore I would like to refresh the topic and hope that a solution can be found. I have reports in the Creator, which I
                                                                                                            • Problem Pasting Into Notes

                                                                                                              Occasionally I want to create a note by copying and pasting a few paragraphs from an article on line. When I create a new note and paste in the section the newly created note winds up with each paragraph in white text on a dark background rather than
                                                                                                            • Bank transaction automation

                                                                                                              I would like to automatically update the "Reference#" field with whatever text is in the "Description" field each time Zoho Books pulls my bank feeds. I've figured out the automation all the way up to the Field Update, where "Reference Number = ...???"
                                                                                                            • Payment Gateways For South Africa

                                                                                                              Hi, Can you please incorporate a payment gateway like Payfast etc for South African clients?
                                                                                                            • Zoho Error: This Operation has been restricted. Please contact support-as@zohocorp.com for further details

                                                                                                              Hello There, l tried to verify my domain (florindagoreti.com.br) and its shows this error: This Operation has been restricted. Please contact support-as@zohocorp.com for further details. Screenshot Given Below -  please check what went wrong. Thanks
                                                                                                            • Sales IQ - Bot Builder - Forward to Operator Action Card Improvement

                                                                                                              Hi team, It would be a great improvement to have an additional branch out of the Forward to Operator Action Card. I would like to allow 10 seconds for an operator to pick up the chat, if they don't or if they reject the chat I would like the Bot to continue
                                                                                                            • Next Page