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

                                                                                                            • Allocating inventory to specific SO's

                                                                                                              Is there a way that allocate inventory to a specific sales order? For example, let's say we have 90 items in stock. Customer 1 orders 100 items. This allocates all 90 items to their order, and they have a back order for the remaining 10 items which could
                                                                                                            • Mail and OS

                                                                                                              Jai Hind! Zoho is doing good by creating good software (made in india) on par with other tech giants. 🥰 Suggestion: 1. Whenever we sign up on zoho mail its asking for other mail id. It shouldn't be like that. You should ask general details of a user
                                                                                                            • Personal account created under org account

                                                                                                              Hi there, I am Jayesh. We are using ME Central, and we have an account by the email ID soc@kissht.com.. Now I have created a personal account., jayesh.auti@zohomail.in, accidentally. Can you help me to remove this jayesh.auti@zohomail.in from my organization
                                                                                                            • Add another account

                                                                                                              How to add another mail account to my zoho mail.
                                                                                                            • Recover deleted user

                                                                                                              Hi by mistake i have deleted an added user and his email associated. Please help me recover it thank you.
                                                                                                            • No connection to the server

                                                                                                              Hello! I can't add a new email address to my mailbox because your server is rejecting me. Please help. I took and added a screenshot of this problem Marek Olbrys
                                                                                                            • URGENT: Business Email Disruption – SMTP Authentication Failed

                                                                                                              Dear Zoho Support, I am writing to escalate a critical issue with my business email account: 📧 marek@olbrys.de My domain olbrys.de is fully verified in Zoho (MX, SPF, DKIM, DMARC all valid – green status). I am using the correct configuration: smtp.zoho.eu
                                                                                                            • Emails missing from desktop but visible on phone

                                                                                                              Subject says it all. Windows 11 laptop. Apple phone. all systems up to date.
                                                                                                            • Website Hosting

                                                                                                              Hello, I want to host my domain on Hostinger, and I want my emails to run through Zoho Mail. Please provide me with the SPF record, MX record (Type: TXT), and A record, so that I don’t face any issues with my emails. My website is on Hostinger hosting,
                                                                                                            • Can not search zoho mail after update V.1.7.0

                                                                                                              i can not search mail on to and cc box from attached picture and then search contacts box can't click or use anything. include replay mail too.
                                                                                                            • Urgent Security Feature Request – Add MFA to Zoho Projects Client Portal Hello Zoho Projects Team,

                                                                                                              Hello Zoho Projects Team, We hope you are doing well. We would like to submit an urgent security enhancement request regarding the Zoho Projects Client Portal. At this time, as far as we are aware, there is no Multi-Factor Authentication (MFA) available
                                                                                                            • How to retreive the "To be received" value of an Item displayed in Zoho inventory.

                                                                                                              Hi everyone, We have our own Deluge code to generate a PO according to taget quantity and box quantity, pretty usefull and powerful! However, we want to reduce our quantity to order according to "To be received" variable. Seems like this might not even
                                                                                                            • Add Support for Authenticator App MFA in Zoho Desk Help Center

                                                                                                              Hello Zoho Desk Team, We hope you are doing well. We would like to request an enhancement related to security for the Zoho Desk Help Center (customer portal). Currently, the Help Center supports MFA for portal users via SAML, JWT, SMS authentication,
                                                                                                            • Payment on a past due balance

                                                                                                              Scenario: Customer is past due on their account for 4 months. We suspend their billing in Zoho books. Customer finally logs into the portal and enters a new credit card. We associate that cardwith their subscription, which will permit the card to be used
                                                                                                            • Instant Sync of Zoho CRM Data?

                                                                                                              With how valuable Zoho Analytics is to actually creating data driven dashboards/reports, we are surprised that there is no instant or near instant sync between Zoho CRM and Zoho Analytics. Waiting 3 hours is okay for most of our reports, but there are
                                                                                                            • Kaizen #211 - Answering your Questions | Using Canvas and Widgets to Tailor CRM for Mobile

                                                                                                              Howdy, tech wizards! We are back with the final post in addressing the queries you shared for our 200th milestone. This week, we are focusing on a couple of queries on Zoho CRM mobile configurations and custom payment gateway integration. 1. Mobile SDK
                                                                                                            • Remove "Invalid entries found. Rectify and submit again" modal

                                                                                                              Following up on a post from a few years back, but can the Zoho team consider either removing the 'Invalid entries found. Rectify and submit again' modal that displays for empty mandatory fields OR allow an admin to change it? I've built a custom error
                                                                                                            • Validation function not preventing candidates under 18 or over 30 from submitting the web form

                                                                                                              Hello everyone, I’m trying to create a validation rule for the Candidate Webform in Zoho Recruit. I added a custom field called “Date of Birth”, and I want to make sure that candidates cannot submit the form unless their age is between 18 and 30 years.
                                                                                                            • Remember all the ways we've posted?

                                                                                                              The world celebrates World Postal Day in 2025 with the theme “#PostForPeople: Local Service. Global Reach". The story of the “post” is a story of human connection itself, evolving from simple handwritten notes carried over long distances to instant digital
                                                                                                            • Custom domain issue

                                                                                                              I recently changed records for my support area custom domain for a few months, I then wanted to come back to Zoho, but now I can't connect it and I can't login as it's having an SSL issue. I cannot get a good response from support, as I've been notified
                                                                                                            • Cadence reports as front-end reports

                                                                                                              Hello everyone, We have built a cadence which is connected to the Leads module. There are 11 steps in total, 7 are automatic emails and 4 are tasks for the Lead owners. As admins, we have access to this (very nicely made) 'View Reports' tab where we can
                                                                                                            • Zoho Commerce in multiple languages

                                                                                                              When will you be able to offer Zoho Commerce in more languages? We sell in multiple markets and want to be able to offer a local version of our webshop. What does the roadmap look like?
                                                                                                            • Show elapsed time on the thank-you page?

                                                                                                              Is it possible to display the total time a user spent filling out a Zoho Form on the thank-you? I’d like to show the difference between the `form submission timestamp` and the `start time` (currently have a hidden Date-Time field set to autofill the date
                                                                                                            • The present is a "present"

                                                                                                              The conversation around mental health has been gaining attention in recent years. Even with this awareness, we often feel stuck; the relentless pace of modern life makes us too busy to pause, reflect, and recharge. In the world of customer support, this
                                                                                                            • Cliq iOS can't see shared screen

                                                                                                              Hello, I had this morning a video call with a colleague. She is using Cliq Desktop MacOS and wanted to share her screen with me. I'm on iPad. I noticed, while she shared her screen, I could only see her video, but not the shared screen... Does Cliq iOS is able to display shared screen, or is it somewhere else to be found ? Regards
                                                                                                            • Kaizen# 209 - Answering Your Questions | All About Client Script

                                                                                                              Hello everyone! Welcome back to another exciting Kaizen post! Thanks for all your feedback and questions. In this post, let's see the answers to your questions related to Client Script. We took the time to discuss with our development team, carefully
                                                                                                            • Email Integration - Zoho CRM - OAuth and IMAP

                                                                                                              Hello, We are attempting to integrate our Microsoft 365 email with Zoho CRM. We are using the documentation at Email Configuration for IMAP and POP3 (zoho.com) We use Microsoft 365 and per their recommendations (and requirements) for secure email we have
                                                                                                            • Search in Zoho Community Not Working

                                                                                                              I realize this is a bit of a meta topic, but the search for the various Zoho Communities appears to not be working. I'm under the impression that they run on some version of the Zoho Desk platform, so I'm posting this here.
                                                                                                            • I need to do crud with snippet html

                                                                                                              I need to implement a form with an improved user interface. I would like to use snippets to build a CRUD that allows me to create and update records. How could I achieve this using snippets?
                                                                                                            • Allow Stripe Credit Card and Stripe ACH payment methods to be enabled separately on an invoice.

                                                                                                              I need to be able to pick at the invoice level whether Stripe Credit Card and/or Stripe ACH payment methods are available. Currently, I'm not able to select from the two Stripe payment methods individually on an invoice. However, there are some larger
                                                                                                            • Enhancements to finance suite integrations

                                                                                                              Update: Based on your feedback, we’ve updated the capabilities for integration users. In addition to the Estimates module, they can now create, view, and edit records in all the finance modules including Sales Order, Invoices, Purchase Order. We're also
                                                                                                            • Meeting impossible to use when sharing screen

                                                                                                              he Meeting tool in Brazil is practically unusable when sharing anything, whether it’s a presentation or simple navigation. When accessed via Cliq, the situation gets even worse: even basic calls fail to work properly, constantly freezing. And as you are
                                                                                                            • Connecting two modules - phone number

                                                                                                              Hi, I’d like some guidance on setting up an automation in Zoho CRM that links records between the Leads module and a custom module called Customer_Records whenever the phone numbers match. Here’s what I’m trying to achieve: When a new Lead is created
                                                                                                            • Resume Harvester: New Enhancements for Faster Sourcing

                                                                                                              We’re excited to share a set of enhancements to Resume Harvester that make sourcing faster and more flexible. These updates help you cut down on repetitive steps, manage auto searches more efficiently, and review candidate profiles with ease. Why we built
                                                                                                            • Incorrect “correct” password on email client apple mail

                                                                                                              I have troubleshot this account several times. I have deleted and re added account. It keeps saying incorrect password. Can you check that it is not locked on your end?
                                                                                                            • Is it possible to lock editing subform rows?

                                                                                                              Ideally editing would only be locked after the form has been updated but I still want them to be able to add new subform records at any time and they should be able to delete rows from the subform. It is a named subform if that's relevant however the
                                                                                                            • "Spreadsheet Mode" for Fast Bulk Edits

                                                                                                              One of the challenges with using Zoho Inventory is when bulk edits need to be done via the UI, and each value that needs to be changed is different. A very common use case here is price changes. Often, a price increase will need to be implemented, and
                                                                                                            • What is the maximum file size of a video upload in Zoho chat?

                                                                                                              Can I upload a 20 mb video file and share it with my colleagues? 
                                                                                                            • The Social Wall: September 2025

                                                                                                              Hello everyone, As we step into the fall season, some major updates are on the horizon. Meanwhile, here are the exciting updates we rolled out this September. Approvals in iOS Managing approvals just got more seamless on mobile. With this update, the
                                                                                                            • Update a field in ALL all calls under a contact

                                                                                                              HI guys! I have written some deluge code to update a field in my calls after i have comepleted the call, i need this field to update in all my scheduled calls as well that are comeing up. I just cant seem to get it to work, i have put teh code below,
                                                                                                            • Next Page