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

                                                                                            Get Started. Write Away!

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

                                                                                              Zoho CRM コンテンツ






                                                                                                Nederlandse Hulpbronnen


                                                                                                    ご検討中の方




                                                                                                          • Recent Topics

                                                                                                          • Live webinar: Mastering data migration, organization, and team collaboration

                                                                                                            Hello everyone, We’re excited to invite you to our upcoming live webinar! Discover how to seamlessly migrate your data, optimize file organization, and boost team collaboration using Zoho WorkDrive’s powerful features. This is a fantastic opportunity
                                                                                                          • BARCODE PICKLIST

                                                                                                            Hello! Does anyone know how the Picklist module works? I tried scanning the barcode using the UPC and EAN codes I added to the item, but it doesn’t work. Which barcode format does this module use for scanning?
                                                                                                          • Join our live webinar: Explore the WorkDrive TrueSync application!

                                                                                                            Hello everyone, We are thrilled to invite you to a live webinar focused on mastering the WorkDrive TrueSync application. Discover how to seamlessly sync your content between the cloud and your computer, ensuring smooth and efficient file management. Our
                                                                                                          • Bug tracking

                                                                                                            Hi, does anyone know how to track errors during picking or packing? This way I can keep track and see how to improve and prevent errors in this area.
                                                                                                          • Can the Product Image on the Quote Template be enlarged

                                                                                                            Hello, I am editing the Quote Template and added ${Products.Product Image} to the line item and the image comes up but it is very tiny. Is there anyway that you can resize this to be larger? Any help would be great! Thanks
                                                                                                          • Zoho Creator customer portal limitation | Zoho One

                                                                                                            I'm asking you all for any feedback as to the logic or reasoning behind drastically limiting portal users when Zoho already meters based on number of records. I'm a single-seat, Zoho One Enterprise license holder. If my portal users are going to add records, wouldn't that increase revenue for Zoho as that is how Creator is monetized? Why limit my customer portal to only THREE external users when more users would equate to more records being entered into the database?!? (See help ticket reply below.)
                                                                                                          • Script Editor not an option

                                                                                                            I am trying to apply a script to a sheet and Script Editor is not an option. I don't want to go outside Sheets to do this (like Creator) if it can be done inside Sheets.
                                                                                                          • Send Automated WhatsApp Messages and Leverage the Improved WhatsApp Templates

                                                                                                            Greetings, I hope all of you are doing well. We're excited to announce a major upgrade to Bigin's WhatsApp integration that brings more flexibility, interactivity, and automation to your customer messaging. WhatsApp message automation You can now use
                                                                                                          • Envio de mails

                                                                                                            Hola! No puedo enviar mails pero si recibirlos. No se como solucionarlo! Mi dominio es chidobebes.com.ar
                                                                                                          • ERROR CODE :554 - Your access to this mail system has been rejected due to poor reputation of a domain used in message transfer

                                                                                                            In my email configuration: The domain's MX Records are pointed to Zoho The domain's SPF Records have been pointed out successfully DKIM is enabled. DMARC Record is pointed for the domain. The domain name is digioorja.in. Still facing the issue of Error:
                                                                                                          • This Operation has been restricted. Please contact support-as@zohocorp.com for further details

                                                                                                            l tried to verify my domain (casalimpaeperfumada.com.br) and its shows this error: This Operation has been restricted. Please contact support-as@zohocorp.com for further details.
                                                                                                          • SLOW EMAILS

                                                                                                            Is there an issue with the Zoho server? For two days now I've been having issues with very long buffering. Please advise. Thank you.
                                                                                                          • POP3 authentication error - SOLVED

                                                                                                            Just in case others are as forgetful as me ... As Zoho has changed the POP server for personal and free organisational users, I needed to change the POP server on my email client. This failed persistently but eventually I remembered that I had chosen
                                                                                                          • Solution to Import PST File into Office 365.

                                                                                                            MailsDaddy OST to Office 365 Migration Tool is an outstanding solution to recover OST files and migrate them into Office 365 without any hassle. Using this software users can multiple OST files into Office 365 with complete data security. It offers users
                                                                                                          • Add Zoho One Groups/Departments to Shared Mailbox Access

                                                                                                            Hi, I hope you're doing well. Currently, in Zoho Mail, I can manually add specific users or the entire organization to a shared mailbox. However, there is no option to add Zoho One groups or departments. Feature Request: We would like the ability to assign
                                                                                                          • Allow Filters with Only Special Characters in Zoho Mail

                                                                                                            Hi Zoho Mail Team, I hope you're doing well. We have noticed that currently, Zoho Mail does not allow creating filter criteria using only special characters, such as = or #. However, there are scenarios where such a filter is necessary. For example: Filtering
                                                                                                          • How to save email as PDF?

                                                                                                            I saw 2 previous threads about this. One is from 14 years ago. The other was closed as "answered" a year ago but the feature was never implemented: https://help.zoho.com/portal/en/community/topic/how-to-download-save-emails-as-pdf Is the "save as PDF"
                                                                                                          • Flexible plans

                                                                                                            Hi, I have a Workplace Standard subscription. On Zoho's website, it mentions that with the annual plan it's possible to have multiple plans under the same organization—for example, Workplace Standard and Mail Lite. However, I can’t find a way to do this
                                                                                                          • Weekly Tips : Teamwork made easy with Multiple Assignees

                                                                                                            Let's say you are working on a big project where different parts of a single task need attention from several people at the same time—like reviewing a proposal that requires input from sales, legal, and finance teams. Instead of sending separate reminders
                                                                                                          • Cannot give public access to Html Snippet in Zoho Creator Page

                                                                                                            Hi, I created a form in Zoho Creator and published it. The permalink works but I want to override the css of the form. (style based URL parameters is not good enough) So I created a page and added an Html snippet. I can now override the css, which is
                                                                                                          • Weekly Tips : Customize your Compose for a smoother workflow

                                                                                                            You are someone who sends a lot of emails, but half the sections in the composer just get in your way — like fields you never use or sections that clutter the space. You find yourself always hunting for the same few formatting tools, and the layout just
                                                                                                          • Unable to confirm Super Admin assignment — confirmation button not working

                                                                                                            I’m trying to change the roles within my organization. I am currently a super admin and would like to add another user as a super admin. When I attempt to confirm the action, a screen appears asking for my password to verify my identity. However, when
                                                                                                          • Installing EMAIL Setup in New Domain

                                                                                                            Respected Support team, I'm facing an issue with cloudflare in Pakistan, I want to setup Zoho Mail Setup but I Don't know how to enable Zoho mail setup without cloudflare. My Website https://stumbleguyzzapk.com/, https://fakservices.com/ is using CF,
                                                                                                          • Will I Get a Refund If I Downgrade Zoho Mail?

                                                                                                            Hello, We upgraded an email account for our new employee. However, the employee left after one month, and now I've reduced the number of Zoho Mail users from 7 to 6. Can we get a refund for the remaining portion of our annual payment?
                                                                                                          • Accounting on the Go Series-43:Enhancing Your Reporting Efficiency with Dashboard Filter State Retention

                                                                                                            Hello everyone! Welcome back to our series on Zoho Books mobile app features. Today, we will talk about a feature that yet again helps you focus on work that really matters-Dashboard Filter State Retention. Imagine you're working on your Zoho Books dashboard,
                                                                                                          • Zoho books/payroll tax payment

                                                                                                            I accidentally made a second payment to my taxes for $300 which is reflected in my bank account and therefore on Zoho books but I can not match it to any transactions because its not reflected in payroll as a tax payment. Is there a way to add an extra
                                                                                                          • I can't renew the Finance Plus subscription

                                                                                                            I tried to renew the Finance Plus subscription but it keeps reloading the same page over and over when ever I click on "Renew Subscription" button
                                                                                                          • Estimate vs Quote

                                                                                                            they are different. Quote is for 1 piece price + other charges. Estimate is for total quantity to be ordered. The gross total amount of the Estimate is the amount payable. Replacing Estimate as Quote is not understandable because they are different. In
                                                                                                          • Accounting on the Go Series-47: Effortless GSTIN Management- Auto Populate TaxPayer Details in Zoho Books Mobile App

                                                                                                            Hello everyone, Welcome back! Today, we're focusing on a feature specifically designed for our Indian users in the Zoho Books-Indian edition, particularly those who deal with GST compliance regularly. We understand the importance of accurate and efficient
                                                                                                          • Accounting on the Go Series-48: Enhance Accuracy with Custom Work Week Start Days in Zoho Books iOS app

                                                                                                            Hello everyone, Welcome back! We’re here with another feature spotlight that might seem small but can have a big impact on your daily routine: setting the first day of the work week in the Zoho Books iOS app. Imagine this: You’re a business owner who
                                                                                                          • Time to Get Paid Report in ZBooks

                                                                                                            Hello, One of our customers who has 25 different companies around the world gets 60 days to make payments. Unfortunately, the subject report does not report an average time to get paid (in days) or the ability to look at a custom period of time. Currently
                                                                                                          • How to prepare a balance sheet for a company that has no operations yet?

                                                                                                            .
                                                                                                          • Project Billing Method from Zoho People

                                                                                                            Normaly our customers use Zoho Projects to manage projects and timesheet that are being charge to the customer. Using the integration from Zoho Project we can have projects base on different billing method. For example most of our customer use Hourly
                                                                                                          • Zoho Books-Accounting on the Go Series!

                                                                                                            Dear users, Continuing in the spirit of our 'Function Fridays' series, where we've been sharing custom function scripts to automate your back office operations, we're thrilled to introduce our latest initiative – the 'Zoho Books-Accounting on the Go Series'.
                                                                                                          • Zoho Books | Product updates | July 2025

                                                                                                            Hello users, We’ve rolled out new features and enhancements in Zoho Books. From plan-based trials to the option to mark PDF templates as inactive, explore the updates designed to enhance your bookkeeping experience. Introducing Plan Based Trials in Zoho
                                                                                                          • Zoho Books | Product updates | August 2025

                                                                                                            Hello users, We’ve rolled out new features and enhancements in Zoho Books. From the right sidebar where you can manage all your widgets, to integrating Zoho Payments feeds in Zoho Books, explore the updates designed to enhance your bookkeeping experience.
                                                                                                          • Apply Payment Received Amount Zoho Books Invoice

                                                                                                            Hello team here is the sample code How can apply the payment received record over a unpaid zoho books invoice. //......................... paymentID = customer_payment.get("payment_id"); organizationID = organization.get("organization_id"); paymentmaplist
                                                                                                          • Update or Upsert Records Using Unique Custom Fields

                                                                                                            Hello customers, We've enhanced the process of updating records via API. You can now: Update records using unique custom fields Upsert records using unique custom fields Note: Both the features are available in the Zoho Books and Zoho Inventory apps.
                                                                                                          • [Webinar] Understanding the New Invoice Management Systems

                                                                                                            Join industry expert CA Pritam Mahure as he discusses the importance of the new Invoice Management System (IMS) and its impact on taxpayers. Topics Covered: - Concept of IMS and pre-requisites - Applicability and Restrictions on Invoices/Records for IMS
                                                                                                          • Accounting on the Go Series-51: Effortless Transactions: Create and Manage Directly from Uploaded Documents

                                                                                                            Hello everyone, We’re back with another useful feature that makes working with Zoho Books even easier! This time, we’re simplifying the process of creating transactions directly from uploaded documents. Imagine you’re out meeting clients, and you receive
                                                                                                          • Next Page