Threading in the Scala SDK
Threads in a scala program help you achieve parallelism. By using multiple threads, you can make a scala program run faster and do multiple things simultaneously.
The Scala SDK supports both single-threading and multi-threading irrespective of a single-user or a multi-user app.
Refer to the below code snippets that use multi-threading for a single-user and multi-user app.
Multi-threading in a Multi-user App
import com.zoho.crm.api.Initializer
Initializer.switchUser(user, environment, token, sdkConfig)
Initializer.switchUser(user, environment, token, sdkConfig, Option(proxy))
import com.zoho.api.authenticator.OAuthToken
import com.zoho.api.authenticator.Token
import com.zoho.api.authenticator.OAuthToken.TokenType
import com.zoho.api.authenticator.store.{DBStore, FileStore, TokenStore}
import com.zoho.crm.api.Initializer
import com.zoho.crm.api.RequestProxy
import com.zoho.crm.api.SDKConfig
import com.zoho.crm.api.UserSignature
import com.zoho.crm.api.dc.{DataCenter, USDataCenter,EUDataCenter}
import com.zoho.crm.api.exception.SDKException
import com.zoho.api.logger.Logger
import com.zoho.crm.api.record.RecordOperations
object MultiThread {
@throws[SDKException]
def main(args: Array[String]): Unit = {
val logger = Logger.getInstance(Logger.Levels.INFO, "/Users/user_name/Documents/scala-sdk-logs.log")
val environment1 = USDataCenter.PRODUCTION
val tokenStore = new FileStore("/Users/user_name/Documents/scala-sdk-tokens.txt")
val user1 = new UserSignature("user1@zoho.com")
val token1 = new OAuthToken("clientId1", "clientSecret1", "REFRESH/GRANT token", TokenType.REFRESH / GRANT)
val resourcePath = "/Users/user_name/Documents/scalasdk-application"
val sdkConfig = new SDKConfig.Builder().setAutoRefreshFields(false).setPickListValidation(true).build
Initializer.initialize(user, environment, token, tokenstore, sdkConfig, resourcePath, Option(logger), Option(requestProxy))
var multiThread = new MultiThread(user1, environment1, token1, "Leads", sdkConfig, null)
multiThread.start()
val environment2 = EUDataCenter.PRODUCTION
val user2 = new UserSignature("user2@zoho.eu")
val user2Proxy = new RequestProxy("proxyHost", 80, Option("proxyUser"), Option("password"), Option("userDomain"))
val token2 = new OAuthToken("clientId2", "clientSecret2", "REFRESH/GRANT token", TokenType.REFRESH / GRANT, Option("redirectURL"))
val sdkConfig2 = new SDKConfig.Builder().setAutoRefreshFields(true).setPickListValidation(false).build
multiThread = new MultiThread(user2, environment2, token2, "Leads", sdkConfig2,user2Proxy )
multiThread.start()
}
}
class MultiThread(var user: UserSignature, var environment: DataCenter.Environment, var token: Token, var moduleAPIName: String, var sdkConfig: SDKConfig, var requestProxy: RequestProxy) extends Thread {
override def run(): Unit = {
try {
Initializer.switchUser(user, environment, token, sdkConfig, Option(requestProxy))
println("Getting Records for: " + Initializer.getInitializer.getUser.getEmail)
val cro = new RecordOperations
val getResponse = cro.getRecords(this.moduleAPIName, None, None)
} catch {
case e: Exception =>
e.printStackTrace()
}
}
}
The program execution starts from main().
The details of "user1" are given in the variables user1, token1, environment1.
Similarly, the details of another user "user2" are given in the variables user2, token2, environment2.
For each user, an instance of MultiThread class is created.
When start() is called which in-turn invokes run(), the details of user1 are passed to the switchUser function through the MultiThread object. Therefore, this creates a thread for user1.
Similarly, When start() is invoked again, the details of user2 are passed to the switchUser function through the MultiThread object. Therefore, this creates a thread for user2.
Multi-threading in a Single-user App
import com.zoho.api.authenticator.OAuthToken
import com.zoho.api.authenticator.OAuthToken.TokenType
import com.zoho.api.authenticator.store.FileStore
import com.zoho.crm.api.Initializer
import com.zoho.crm.api.SDKConfig
import com.zoho.crm.api.UserSignature
import com.zoho.crm.api.dc.USDataCenter
import com.zoho.api.logger.Logger
import com.zoho.crm.api.record.RecordOperations
object MultiThread {
@throws[Exception]
def main(args: Array[String]): Unit = {
val logger = Logger.getInstance(Logger.Levels.INFO, "/Users/user_name/Documents/scala-sdk-logs.log")
val environment = USDataCenter.PRODUCTION
val tokenStore = new FileStore("/Users/user_name/Documents/scala-sdk-tokens.txt")
val user = new UserSignature("user1@zoho.com")
val token = new OAuthToken("clientId1", "clientSecret1", "REFRESH/GRANT token", TokenType.REFRESH / GRANT)
val sdkConfig = new SDKConfig.Builder().setAutoRefreshFields(false).setPickListValidation(true).build
val resourcePath = "/Users/user_name/Documents/scalasdk-application"
Initializer.initialize(user, environment, token, tokenstore, sdkConfig, resourcePath, Option(logger), Option(requestProxy))
var mtsu = new MultiThread("Deals")
mtsu.start()
mtsu = new MultiThread("Leads")
mtsu.start()
}
}
class MultiThread(var moduleAPIName: String) extends Thread {
override def run(): Unit = {
try {
val cro = new RecordOperations
@SuppressWarnings(Array("rawtypes")) val getResponse = cro.getRecords(this.moduleAPIName, None, None)
println(getResponse.get.getObject)
} catch {
case e: Exception =>
e.printStackTrace()
}
}
}
The program execution starts from main() where the SDK is initialized with the details of user and an instance of MultiThread class is created.
When start() is called which in-turn invokes run(), the details of user1 are passed to the switchUser function through the MultiThread object. Therefore, this creates a thread for user1.
The MultiThread object is reinitialized with a different moduleAPIName.
Similarly, When start() is invoked again, the details of user2 are passed to the switchUser function through the MultiThread object. Therefore, this creates a thread for user2.
SDK Sample code
package com.zoho.crm.sample.threading.multiuser;
import com.zoho.api.authenticator.Token
import com.zoho.api.authenticator.store.DBStore
import com.zoho.api.authenticator.store.TokenStore
import com.zoho.crm.api.exception.SDKException
import com.zoho.api.logger.Logger
import com.zoho.api.logger.Logger.Levels
import com.zoho.api.authenticator.OAuthToken
import com.zoho.api.authenticator.OAuthToken.TokenType
import com.zoho.crm.api.HeaderMap
import com.zoho.crm.api.Initializer
import com.zoho.crm.api.ParameterMap
import com.zoho.crm.api.SDKConfig
import com.zoho.crm.api.UserSignature
import com.zoho.crm.api.dc.DataCenter.Environment
import com.zoho.crm.api.dc.USDataCenter
import com.zoho.api.logger.Logger
import com.zoho.api.logger.Logger.Levels
import com.zoho.crm.api.record.RecordOperations
import com.zoho.crm.api.record.APIException
import com.zoho.crm.api.record.ResponseHandler
import com.zoho.crm.api.record.ResponseWrapper
import com.zoho.crm.api.tags.Tag
import com.zoho.crm.api.record.RecordOperations.GetRecordsHeader
import com.zoho.crm.api.record.RecordOperations.GetRecordsParam
import com.zoho.crm.api.util.APIResponse
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util
object Record {
@throws[SDKException]
def main(args: Array[String]): Unit = {
/*
* Create an instance of Logger Class that takes two parameters
* 1 -> Level of the log messages to be logged. Can be configured by typing Levels "." and choose any level from the list displayed.
* 2 -> Absolute file path, where messages need to be logged.
*/
val logger = Logger.getInstance(Logger.Levels.INFO, "/Users/user_name/Documents/scala-sdk-logs.log")
//Create an UserSignature instance that takes user Email as parameter
val user = new UserSignature("abc@zoho.com")
/*
* Configure the environment
* which is of the pattern Domain.Environment
* Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter
* Available Environments: PRODUCTION, DEVELOPER, SANDBOX
*/
val environment = USDataCenter.PRODUCTION
/*
* Create a Token instance
* 1 -> OAuth client id.
* 2 -> OAuth client secret.
* 3 -> REFRESH/GRANT token.
* 4 -> Token type(REFRESH/GRANT).
* 5 -> OAuth redirect URL.
*/
val token = new OAuthToken("clientId", "clientSecret", "REFRESH/GRANT token", TokenType.REFRESH / GRANT)
/*
* Create an instance of TokenStore.
* 1 -> DataBase host name. Default "localhost"
* 2 -> DataBase name. Default "zohooauth"
* 3 -> DataBase user name. Default "root"
* 4 -> DataBase password. Default ""
* 5 -> DataBase port number. Default "3306"
*/
//TokenStore tokenstore = new DBStore()
val tokenstore = new DBStore(Option("hostName"),Option( "dataBaseName"), Option("userName"), Option("password"), Option("portNumber"))
//TokenStore tokenstore = new FileStore("absolute_file_path")
/*
* autoRefreshFields
* if true - all the modules' fields will be auto-refreshed in the background, every hour.
* if false - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(com.zoho.crm.api.util.ModuleFieldsHandler)
*
* pickListValidation
* if true - value for any picklist field will be validated with the available values.
* if false - value for any picklist field will not be validated, resulting in creation of a new value.
*
* connectionTimeout
* A Integer field to set connection timeout
*
* requestTimeout
* A Integer field to set request timeout
*
* socketTimeout
* A Integer field to set socket timeout
*/
val sdkConfig = new SDKConfig.Builder().setAutoRefreshFields(false).setPickListValidation(true).connectionTimeout(1000).requestTimeout(1000).socketTimeout(1000).build
val resourcePath = "/Users/user_name/Documents/scalasdk-application"
/*
* Call static initialize method of Initializer class that takes the arguments
* 1 -> UserSignature instance
* 2 -> Environment instance
* 3 -> Token instance
* 4 -> TokenStore instance
* 5 -> SDKConfig instance
* 6 -> resourcePath - A String
* 7 -> Logger instance
*/
Initializer.initialize(user, environment, token, tokenstore, sdkConfig, resourcePath, Option(logger), Option(requestProxy))
val moduleAPIName = "Leads"
val recordOperations = new RecordOperations
val paramInstance = new ParameterMap
paramInstance.add(new GetRecordsParam().approved, "both")
val headerInstance = new HeaderMap
val enddatetime = OffsetDateTime.of(2020, 5, 20, 10, 0, 1, 0, ZoneOffset.of("+05:30"))
headerInstance.add(new GetRecordsHeader().IfModifiedSince, enddatetime)
//Call getRecords method
val responseOption = recordOperations.getRecords(moduleAPIName, Option(paramInstance), Option(headerInstance))
if (responseOption.isDefined) {
val response = responseOption.get
println("Status Code: " + response.getStatusCode)
if (util.Arrays.asList(204, 304).contains(response.getStatusCode)) {
println(if (response.getStatusCode == 204) "No Content"
else "Not Modified")
return
}
if (response.isExpected) { //Get the object from response
val responseHandler = response.getObject
responseHandler match {
case responseWrapper : ResponseWrapper =>
//Get the obtained Record instances
val records = responseWrapper.getData()
for (record <- records) {
println("Record ID: " + record.getId)
var createdByOption = record.getCreatedBy()
if (createdByOption.isDefined) {
var createdBy= createdByOption.get
println("Record Created By User-ID: " + createdBy.getId)
println("Record Created By User-Name: " + createdBy.getName)
println("Record Created By User-Email: " + createdBy.getEmail)
}
println("Record CreatedTime: " + record.getCreatedTime)
var modifiedByOption = record.getModifiedBy()
if (modifiedByOption.isDefined) {
var modifiedBy = modifiedByOption.get
println("Record Modified By User-ID: " + modifiedBy.getId)
println("Record Modified By User-Name: " + modifiedBy.getName)
println("Record Modified By User-Email: " + modifiedBy.getEmail)
}
println("Record ModifiedTime: " + record.getModifiedTime)
val tags = record.getTag()
if (tags.nonEmpty) {
for (tag <- tags) {
println("Record Tag Name: " + tag.getName)
println("Record Tag ID: " + tag.getId)
}
}
println("Record Field Value: " + record.getKeyValue("Last_Name"))
println("Record KeyValues: ")
}
//Get the Object obtained Info instance
val infoOption = responseWrapper.getInfo
//Check if info is not null
if (infoOption.isDefined) {
var info = infoOption.get
if (info.getPerPage().isDefined) { //Get the PerPage of the Info
println("Record Info PerPage: " + info.getPerPage.toString)
}
if (info.getCount.isDefined) { //Get the Count of the Info
println("Record Info Count: " + info.getCount.toString)
}
if (info.getPage.isDefined) { //Get the Page of the Info
println("Record Info Page: " + info.getPage().toString)
}
if (info.getMoreRecords().isDefined) { //Get the MoreRecords of the Info
println("Record Info MoreRecords: " + info.getMoreRecords().toString)
}
}
case exception : APIException =>
println("Status: " + exception.getStatus().getValue)
println("Code: " + exception.getCode().getValue)
println("Details: ")
exception.getDetails().foreach(entry=>{
println(entry._1 + ": " + entry._2)
})
println("Message: " + exception.getMessage().getValue)
case _ =>
}
}
else {
val responseObject = response.getModel
val clas = responseObject.getClass
val fields = clas.getDeclaredFields
for (field <- fields) {
println(field.getName + ":" + field.get(responseObject))
}
}
}
}
}
class Record {}