Skip to main content

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
new Initializer.Builder()
  .user(user)
  .environment(environment)
  .token(token)
  .SDKConfig(sdkConfig)
  .switchUser()


import com.zoho.api.authenticator.OAuthToken
import com.zoho.api.authenticator.Token
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}
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 loggerInstance = new Logger.Builder()
      .level(Logger.Levels.ALL)
      .filePath("/Users/user_name/Documents/scala-sdk-logs.log")
      .build
    val env = USDataCenter.PRODUCTION
    val user1 = new UserSignature("abc.a@zoho.com")
    val tokenstore = new FileStore("/Users/user_name/Documents/scala_sdk_token.txt")
    val token1 = new OAuthToken.Builder()
      .clientID("1000.xxxxx")
      .clientSecret("xxxxxx")
      .refreshToken("1000.xx.xx")
      .redirectURL("https://www.zoho.com")
      .build()
    val resourcePath = "/Users/user_name/Documents/"
    val user1Config = new SDKConfig.Builder()
      .autoRefreshFields(false)
      .pickListValidation(true)
      .build
    new Initializer.Builder()
      .user(user1)
      .environment(env)
      .token(token1)
      .store(tokenstore)
      .SDKConfig(user1Config)
      .resourcePath(resourcePath)
      .logger(loggerInstance)
      .initialize()
    var multiThread = new MultiThread(user1, env, token1, "Deals", user1Config, null)
    multiThread.start()
    val environment = USDataCenter.PRODUCTION
    val user2 = new UserSignature("abc@zoho.com")
    val token2 = new OAuthToken.Builder()
      .clientID("1000.xxxxx")
      .clientSecret("xxxxx")
      .refreshToken("1000.xxxx.xxxxx")
      .build()
    val user2Proxy = new RequestProxy.Builder()
      .host("proxyHost")
      .port(80)
      .user("proxyUser")
      .password("password")
      .userDomain("userDomain")
      .build()
    val user2Config = new SDKConfig.Builder()
      .autoRefreshFields(true)
      .pickListValidation(false).build
    multiThread = new MultiThread(user2, environment, token2, "Leads", user2Config, user2Proxy)
    multiThread.start()
  }
}

class MultiThread(var user: UserSignature, var environment: DataCenter.Environment, var token: Token, var moduleAPIName: String, var sdkConfig: SDKConfig, var userProxy: RequestProxy) extends Thread {
  override def run(): Unit = {
    try {
      new Initializer.Builder()
        .user(user)
        .environment(environment)
        .token(token)
        .SDKConfig(sdkConfig)
        .switchUser()
      println(Initializer.getInitializer.getUser.getEmail)
      val cro = new RecordOperations
      val getResponse = cro.getRecords(this.moduleAPIName, None, None)
      println(getResponse.get.getObject)
    } 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.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 loggerInstance = new Logger.Builder()
      .level(Logger.Levels.ALL)
      .filePath("/Users/user_name/Documents/scala-sdk-logs.log")
      .build
    val env = USDataCenter.PRODUCTION
    val user1 = new UserSignature("abc.a@zoho.com")
    val tokenstore = new FileStore("/Users/user_name/Documents/scala_sdk_token.txt")
    val token1 = new OAuthToken.Builder()
      .clientID("1000.xxxxxx")
      .clientSecret("xxxxxx")
      .refreshToken("1000.xxxxxx")
      .redirectURL("https://www.zoho.com")
      .build()
    val resourcePath = "/Users/user_name/Documents"
    val sdkConfig = new SDKConfig.Builder()
      .autoRefreshFields(false)
      .pickListValidation(true)
      .build
    new Initializer.Builder()
      .user(user1)
      .environment(env)
      .token(token1)
      .store(tokenstore)
      .SDKConfig(sdkConfig)
      .resourcePath(resourcePath)
      .logger(loggerInstance)
      .initialize()
    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.main

import com.zoho.api.authenticator.Token
import com.zoho.api.authenticator.store.DBStore
import com.zoho.api.authenticator.store.TokenStore
import com.zoho.api.authenticator.OAuthToken
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.exception.SDKException
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
      * level -> Level of the log messages to be logged. Can be configured by typing Levels "." and choose any level from the list displayed.
      * filePath -> Absolute file path, where messages need to be logged.
    */
    val loggerInstance = new Logger.Builder()
      .level(Logger.Levels.ALL)
      .filePath("/Users/user_name/Documents/scala-sdk-logs.log")
      .build

    //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,JPDataCenter
      * Available Environments: PRODUCTION, DEVELOPER, SANDBOX
    */
    val environment = USDataCenter.PRODUCTION

    /*
      * Create a Token instance that requires the following
      * clientId -> OAuth client id.
      * clientSecret -> OAuth client secret.
      * refreshToken -> REFRESH token.
      * grantToken -> GRANT token.
      * id -> User unique id.
      * redirectURL -> OAuth redirect URL.
    */
    val token = new OAuthToken.Builder()
      .clientID("1000.xxxxxx")
      .clientSecret("xxxxxx")
      .refreshToken("1000.xxxxxx")
      .redirectURL("https://www.zoho.com")
      .build()

    val tokenstore = new FileStore("/Users/user_name/Documents/scala_sdk_token.txt")

    /*
     * 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()
      .autoRefreshFields(false)
      .pickListValidation(true)
      .connectionTimeout(1000)
      .requestTimeout(1000)
      .socketTimeout(1000)
      .build

    val resourcePath = "/Users/user_name/Documents"

    /*
      * Set the following in InitializeBuilder
      * user -> UserSignature instance
      * environment -> Environment instance
      * token -> Token instance
      * store -> TokenStore instance
      * SDKConfig -> SDKConfig instance
      * resourcePath -> resourcePath - A String
      * logger -> Log instance (optional)
      * requestProxy -> RequestProxy instance (optional)
    */
    new Initializer.Builder()
      .user(user)
      .environment(environment)
      .token(token)
      .store(tokenstore)
      .SDKConfig(sdkConfig)
      .resourcePath(resourcePath)
      .logger(loggerInstance)
      .initialize()
    //		token.remove()

    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")
      }
      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 {}