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

                                                                                                          • How to create a Zoho Mail extension similar to Outlook's OnSend add-in?

                                                                                                            Hi, I want to create a Zoho Mail extension similar to Outlook’s OnSend add-in. The extension should: Let the user select headers and footers from a taskpane while composing an email. When the user clicks Send, the extension should: Automatically insert
                                                                                                          • Effective Inbox Organization: Folders vs Tags in Zoho Mail?

                                                                                                            I'm exploring the best ways to organize a busy inbox, especially when managing multiple clients or project using Zoho Mail. I’d love to know what works best for others: 1. Do you prefer **folders** (possibly with sub-folders) for each client or project?
                                                                                                          • Piss poor service in Support in Domains and email

                                                                                                            Srijith Narayanan B contacted me today. Very pleasant fellow. Just didn't want to tell him how bad your support service is. You help the person, but you leave before we can finish the next stage. Which causes a lot of frustration. It's been 8 days now
                                                                                                          • Zoho Mail android app update: Block & reject future emails, Report phishing, Spam alerts, Suspicious URL detection

                                                                                                            Hello everyone! In the most recent Zoho Mail Android app update, we have brought in support for the following features: Block & reject future emails Report Phishing Spam alerts in the mail details screen. Suspicious URL detection. Block & reject future
                                                                                                          • Zohomail does not support additional fields in mailto links

                                                                                                            Hello, I set up Zohomail as default composer in Firefox according to manual here: https://www.zoho.com/mail/help/defaultcomposer.html#alink2 Later, I wanted to use this functionality to answer in a Linux mailing list thread using mailto link: mailto:xxxxx@kernel.org?In-Reply-To=%3C727o0521-q24p-s0qq-66n0-sn436rpqqr1p@example.com%3E&amp;Cc=xxxxx%example.org&amp;Subject=Re%3A%20%5BPATCH%20v2%28%29
                                                                                                          • Emails not being received from a particular domain

                                                                                                            Cannot receive any emails sent from atco.com Domain is in the spam whitelist so should be no reason for it not to be coming through. Have filed a ticket and besides a generic response of we are looking at it - it seems there is no actual support workers
                                                                                                          • Email address for forwarding is not saving and there's no confirmation ema

                                                                                                            Steps to reproduce: 1. Enter my forward email in the email forward section of the account 2. Click save 3. See a notification stating saved successfully 4. Refresh the page, no forward email is saved 5. No email confirmation received at the forwarding
                                                                                                          • This domain is not allowed to add in Zoho. Please contact support-as@zohocorp.com for further details

                                                                                                            This is the error i keep getting when trying to use my Zoho Domain Mail. This domain is not allowed to add in Zoho. Please contact support-as@zohocorp.com for further details Find attached. I hope this can be resolved very quickly so i can go on and make
                                                                                                          • Auto CC - Moving Departments

                                                                                                            We have Auto CC e-mail replies to your support mailbox enabled. We have two departments: Helpdesk (helpdesk@domain.com) Delivery (delivery@domain.com) If we create a Helpdesk ticket, and reply, replies are CC'd to helpdesk@domain.com (OK) We then move
                                                                                                          • I have error AS101 when I try to add paypal@mydomain.com to Zoho

                                                                                                            Please help me with this. I tried to call the help line 4 times but don't get any response.
                                                                                                          • unable to send message reason 554 5.1.8 Email outgoing blocked

                                                                                                            unable to send message reason 554 5.1.8 Email outgoing blocked
                                                                                                          • Mailk got blocked / Inquiry About Email Sending Limits and Upgrade Options

                                                                                                            Dear Zoho Support Team, My name is Kamr Elsayed I created this account to use for applying for vocational training in Germany. As part of this process, I send multiple emails to different companies. However, after sending only 8 emails today, I received
                                                                                                          • SMTP email sending problem

                                                                                                            Hello, I've sent emails before, but you haven't responded. Please respond. My work is being disrupted. I can't send emails via SMTP. Initially, there were no problems, but now I'm constantly receiving 550 bounce errors. I can't use the service I paid
                                                                                                          • unblock my zoho mail account. outlines@zoho.com

                                                                                                            please unblock my zoho mail account, outlines@zoho.com
                                                                                                          • Unable to see free plan option

                                                                                                            Hello Zoho Support Team, I hope you are doing well. I am trying to sign up for Zoho Mail, but I am unable to see the option for the free plan. Could you please guide me on how I can access or activate the free plan? Thank you for your assistance.
                                                                                                          • Outgoing blocked: Unusual activity detected.

                                                                                                            I just made payment for my Zohomail Today and have been debited so i will like to be Unblocked because this is what it says (Outgoing blocked: Unusual activity detected) Thank you i await your swift responses
                                                                                                          • How to remove some users in zoho accounts

                                                                                                            How to remove some users in Zoho accounts.
                                                                                                          • Forwarder

                                                                                                            Hi, I tried to add a forwarder from which emails are sent to my main zoho account email . However, it asks me for a code that should be received at the forwarder email, which is still not activated to send to my zoho emial account. So how can I get the
                                                                                                          • Forwarder

                                                                                                            Hi, I tried to add a forwarder from which emails are sent to my main zoho account email . However, it asks me for a code that should be received at the forwarder email, which is still not activated to send to my zoho emial account. So how can I get the
                                                                                                          • DKIM cannot be enabled for the domain as no verified default selector present

                                                                                                            Hi Support Team, For Domain DKIM record trying to enable status. but showing error "DKIM cannot be enabled for the domain as no verified default selector present" So, please resolve the issue. Thank you.
                                                                                                          • I can't log in to my account on Thunderbird

                                                                                                            I've just had to rebuild my PC (calamitous mess from Microsoft with Win10/Win 11 'upgrade' - they confirmed I had to start with a new build). I have used Zoho mail for years via Mozilla Thunderbird, but now I've had to download the latest version of TBird,
                                                                                                          • Sorten the domain of zoho mail ids

                                                                                                            I recently created zoho mail id and am quite excited with the features. But one issue ig nobody wanna type this big zohoaccounts.com I mean silly bold Suggestion zmail.com (sound gmail) (attraction) or some genz words looks cool
                                                                                                          • Weekly Tips : Customize your Zoho Mail Notifications

                                                                                                            In a professional context, email communication remains one of the most crucial channels for staying connected and managing workflows. Keeping track of your emails, task updates, or important announcements can be overwhelming—especially if you are juggling
                                                                                                          • How to move emails to Shared Mailbox?

                                                                                                            Hello, I created a Shred Mailbox instead of using a distribution group. But I cannot move previous emails to certain shared mailbox. Is it possible move some emails from inbox to shared mailbox?
                                                                                                          • Email task creator when task is updated/marked complete

                                                                                                            I am looking for a way to notify the creator of a task in zoho todo when - Task is updated Task is closed Comments entered 1 and 2 are critical, and I cannot find a zoho flow to do this. There is no way that as a manager I will know when someone has completed
                                                                                                          • The attendees will now be redirected to the landing webpage when they exit the webinar, set by the organizer.

                                                                                                            Hello All, In the latest version of the Zoho Meeting iOS mobile app (v1.3.16), we have brought in the below enhancements:   Post Webinar Re-direction Revamped exit UI for Webinar Post Webinar Re-direction:  The attendees will now be redirected to the
                                                                                                          • Download API file contents from browser

                                                                                                            Hi Team - is there something being planned to be able to trigger file downloads from the browser via a deluge script? i.e. retrieve a file via API, trigger the file download directly from the browser. Or... using the convertToPdf function (https://www.zoho.com/deluge/help/functions/file/convert-to-pdf.html)
                                                                                                          • March 15, 2023: Zoho Docs is discontinued

                                                                                                            As of today (March 15, 2023) Zoho Docs is discontinued for all users. We would like to thank our customers for trusting us for so many years! Going forward, we're confident you'll enjoy using Zoho WorkDrive for all your advanced file management and collaboration
                                                                                                          • When using "locations" in zoho books, can you keep the two locations totally separate from each other?

                                                                                                            I am looking to add a location but I don't want to intermingle the banking or other accounts. I want that to be like two separate independent branches that use different banking accounts, accounts payable, and accounts receivable. The people who are in
                                                                                                          • Adding a Channel to SalesIQ

                                                                                                            I have a client that currently uses Zoho CRM and Zoho Desk. They would like a live chat to place on their website that has a mobile app and chat bots (something like SalesIQ). However, they would also like to have all this work over SMS as well. Does the SalesIQ API allow this? Can I add visitors without them being a visitor on a website? Thanks! Bryan Redeagle
                                                                                                          • DataPrep Bigquery Connection failed

                                                                                                            Hello everybody, I want to create a connnection beetwen Bigquery and Dataprep but when I try to connect my project I got this error Loading tables has failed. Table list fetched from the data source expired.
                                                                                                          • How Do I Refund a Customer Directly to Their Credit Card?

                                                                                                            Hi, I use books to auto-charge my customers credit card. But when I create a credit note there doesn't seem to be a way to directly refund the amount back to their credit card. Is the only way to refund a credit note by doing it "offline" - or manually-
                                                                                                          • Zoho Flow Needs to Embrace AI Agent Protocols to Stay Competitive

                                                                                                            Zoho Flow has long been a reliable platform for automating workflows and integrating various applications. However, in the rapidly evolving landscape of AI-driven automation, it risks falling behind competitors like n8n, which are pioneering advancements
                                                                                                          • Important Features Missing

                                                                                                            Hey all I love linkthread, but i am missing some important features. I want to be able to include my Google Tag Manager. I have all the important stuff in my GTM Container: Facebook Pixel, LinkIn Pixel, Zoho Pagesense and so on. So i am able to do retargeting
                                                                                                          • Zoho SignForms: Prefill parameters with spaces render as “+” in the document (even when using %20)

                                                                                                            Hello Zoho Sign team, we are using SignForms with prefill parameters passed via URL. Spaces in parameter values are being rendered as “+” in the finalized document—even when we URL-encode spaces as %20. This is critical for us because we prefill addresses
                                                                                                          • Currency selector (based on variable) usage in comparsion

                                                                                                            Hi, I've developed a currency selector based on the following topic, and it's working well in pivot tables and charts: https://help.zoho.com/portal/en/community/topic/how-can-i-allow-my-users-to-choose-a-currency-for-the-dashboard I also have a comparison
                                                                                                          • Customize Column in Projects - Default View for Template?

                                                                                                            Is there a way to have the columns you'd like to see added to a template? I want my customized columns to show up every single time I create a project from that template. It appears I can customize them in the template but when I create the project they do not transfer over.  Template: See below how the columns in order are : Task, Owner, Status, Assigned, Website URL, Blog H1..etc. When I create a project from that same template it comes out as: Task, Owner, Status, Tags, Start Date, End Date, etc
                                                                                                          • Ask the Experts 24: Analytics, data administration, and mobile experience with Zoho Desk

                                                                                                            Hello Everyone! Welcome back to the Ask the Experts(ATE) series! We were so focused on our Autumn 2025 release that we didn't host an ATE session last month. In this month's ATE, we'd like to expand our areas for discussion: we'd like to listen to your
                                                                                                          • Multi-Page Forms in Zoho Creator!

                                                                                                            Let’s make long applications easier to handle by dividing them into pages, adding a progress bar, and guiding users step by step through complex data entry. This would be a total game-changer for the user experience and could significantly boost completion
                                                                                                          • Unable to Receive Emails on Zoho Mail After Office 365 Coexistence Setup – Error: 553 Relaying Disallowed

                                                                                                            Hello, My domain name is bigniter.com, and I’ve been using Zoho Mail as my email service provider without any issues. Recently, I followed the steps outlined in the Zoho documentation to enable Coexistence with Office 365: 🔗 https://www.zoho.com/mail/help/adminconsole/coexistence-with-office365.html#multi-server
                                                                                                          • Next Page