Skip to product menu
close
  • Recent Launches
    Press Space or Enter to display list of options
EXPLORE ALL PRODUCTS

Recent Launches

New

Payroll software with automated tax payments and filing.

Try now
New

Robotic process automation software to automate high-volume, rule-based tasks.

Try for free
New

Low-code IoT platform and solutions for connected businesses.

Try now
New

Business formation service to launch and grow your businesses.

Try now
New

Privacy-friendly application analytics solution.

Try for free

Sales

 
CRM

Comprehensive CRM platform for customer-facing teams.

CRM
 
Bigin

Simple CRM for small businesses moving from spreadsheets.

Bigin
 
Forms

Build online forms for every business need.

Forms
 
SalesIQ

Live chat app to engage and convert website visitors.

SalesIQ
 
Bookings

Appointment scheduling app for consultations with customers.

Bookings
 
Sign

Digital signature app for businesses.

Sign
 
RouteIQ

Comprehensive sales map visualization and optimal route planning solution.

RouteIQ
 
Thrive

Complete loyalty and affiliate management platform.

Thrive
 
Voice

Cloud Contact Center Software for businesses.

Voice
 
Suites
CRM Plus

Unified platform to deliver top-notch customer experience.

CRM Plus

Marketing

 
Social

All-in-one social media management software.

Social
 
Campaigns

Create, send, and track targeted email campaigns that drive sales.

Campaigns
 
Forms

Build online forms for every business need.

Forms
 
Survey

Design surveys to reach and interact with your audience.

Survey
 
Sites

Online website builder with extensive customisation options.

Sites
 
PageSense

Website conversion optimization and personalisation platform.

PageSense
 
Backstage

End-to-end event management software.

Backstage
 
Webinar

Webinar platform for webcasting online webinars.

Webinar
 
Marketing Automation

All-in-one marketing automation software.

Marketing Automation
 
LandingPage

Smart landing page builder to increase conversion rates

LandingPage
 
Publish

Manage all your local business listings on a single platform.

Publish
 
SalesIQ

Live chat app to engage and convert website visitors.

SalesIQ
 
Sign

Digital signature app for businesses.

Sign
 
Thrive

Complete loyalty and affiliate management platform.

Thrive
 
Voice

Cloud Contact Center Software for businesses.

Voice
 
NEW
LeadChain

Sync, manage, and convert leads across channels seamlessly.

LeadChain
 
NEW
CommunitySpaces

Online community platform for individuals and businesses to grow their network and brand.

CommunitySpaces
 
Suites
Marketing Plus

Unified marketing platform for marketing teams.

Marketing Plus

Commerce

 
Commerce

eCommerce platform to manage and market your online store.

Commerce

Service

 
Desk

Helpdesk software to deliver great customer support.

Desk
 
Assist

Remote support and unattended remote access software.

Assist
 
Lens

Interactive remote assistance software with augmented reality.

Lens
 
FSM

End-to-end field service management platform for service businesses.

FSM
 
SalesIQ

Live chat app to engage and convert website visitors.

SalesIQ
 
Voice

Cloud Contact Center Software for businesses.

Voice
 
NEW
Solo

The all-in-one toolkit for solopreneurs.

Solo
 
Bookings

Appointment scheduling app for consultations with customers.

Bookings
 
Suites
Service Plus

Unified platform for customer service and support teams.

Service Plus

Finance

 
Books

Powerful accounting platform for growing businesses.

Books
 
FREE
Invoice

100% Free invoicing solution.

Invoice
 
Expense

Effortless expense reporting platform.

Expense
 
Inventory

Powerful stock management and inventory control software.

Inventory
 
Billing

End-to-end billing solution for your business.

Billing
 
Checkout

Collect payments online with custom branded pages.

Checkout
 
NEW
Payroll

Payroll software with automated tax payments and filing.

Payroll
 
NEW
Solo

The all-in-one toolkit for solopreneurs.

Solo
 
Practice

Practice management software for accounting firms.

Practice
 
Sign

Digital signature app for businesses.

Sign
 
Commerce

eCommerce platform to manage and market your online store.

Commerce
 
Suites
Finance Plus

All-in-one suite to manage your operations and finances.

Finance Plus

Email and Collaboration

 
Mail

Secure email service for teams of all sizes.

Mail
 
Meeting

Online meeting software for all your video conferencing & webinar needs.

Meeting
 
Writer

Word processor for focused writing and discussions.

Writer
 
Sheet

Spreadsheet software for collaborative teams.

Sheet
 
Show

Create, edit, and share slides with a sleek presentation app.

Show
 
Notebook

Beautiful home for all your notes.

Notebook
 
Cliq

Stay in touch with teams no matter where you are.

Cliq
 
Connect

Employee experience platform to communicate, engage, and build positive employee relations.

Connect
 
Bookings

Appointment scheduling app for consultations with customers.

Bookings
 
TeamInbox

Shared inboxes for teams.

TeamInbox
 
WorkDrive

Online file management for teams.

WorkDrive
 
Sign

Digital signature app for businesses.

Sign
 
Office Suite

Powerful collaborative work platform for teams.

Office Suite
 
Office Integrator

Built in document editors for web apps.

Office Integrator
 
ZeptoMail

Secure and reliable transactional email sending service.

ZeptoMail
 
Calendar

Online business calendar to manage events and schedule appointments.

Calendar
 
Learn

Knowledge and learning management platform.

Learn
 
Voice

Cloud Contact Center Software for businesses.

Voice
 
ToDo

Collaborative task management for individuals and teams.

ToDo
 
Tables

Work management tool to connect people, processes, and information.

Tables
 
FREE
PDF Editor

Collaborative online PDF editing tool.

PDF Editor
 
Suites
Workplace

Application suite built to improve team productivity and collaboration.

Workplace

Human Resources

 
People

Organize, automate, and simplify your HR processes.

People
 
Recruit

Intuitive recruiting platform built to provide hiring solutions.

Recruit
 
Expense

Effortless expense reporting platform.

Expense
 
Workerly

Manage temporary staffing with an employee scheduling solution.

Workerly
 
NEW
Payroll

Payroll software with automated tax payments and filing.

Payroll
 
Shifts

Employee scheduling and time tracking app.

Shifts
 
Sign

Digital signature app for businesses.

Sign
 
Suites
People Plus

Comprehensive HR platform for seamless employee experiences.

People Plus

Security and IT Management

 
Creator

Build custom apps to simplify business processes.

Creator
 
Directory

Workforce identity and access management solution for cloud businesses.

Directory
 
FREE
OneAuth

Secure multi-factor authenticator (MFA) for all your online accounts.

OneAuth
 
Vault

Online password manager for teams.

Vault
 
Catalyst

Pro-code platform to build and deploy your apps.

Catalyst
 
Toolkit

Complete resource for any admin-related lookup queries.

Toolkit
 
Lens

Interactive remote assistance software with augmented reality.

Lens
 
Assist

Remote support and unattended remote access software.

Assist
 
QEngine

Test automation software to build, manage, execute, and report testcases.

QEngine
 
NEW
RPA

Automate manual, tedious, and repetitive tasks easily.

RPA

BI and Analytics

 
Analytics

Modern self-service BI and analytics platform.

Analytics
 
Embedded BI

Embedded analytics and white label BI solutions, tailored for your needs.

Embedded BI
 
DataPrep

AI-powered data preparation service for your data-driven organization.

DataPrep
 
NEW
IoT

Harnessing IoT analytics for real-time operational intelligence.

IoT

Project Management

 
Projects

Manage, track, and collaborate on projects with teams.

Projects
 
Sprints

Planning and tracking tool for scrum teams.

Sprints
 
BugTracker

Automatic bug tracking software for managing bugs.

BugTracker
 
NEW
Solo

The all-in-one toolkit for solopreneurs.

Solo

Developer Platforms

 
Creator

Build custom apps to simplify business processes.

Creator
 
Flow

Automate business workflows by creating smart integrations.

Flow
 
Catalyst

Pro-code platform to build and deploy your apps.

Catalyst
 
Office Integrator

Built in document editors for web apps.

Office Integrator
 
ZeptoMail

Secure and reliable transactional email sending service.

ZeptoMail
 
QEngine

Test automation software to build, manage, execute, and report testcases.

QEngine
 
Tables

Work management tool to connect people, processes, and information.

Tables
 
NEW
RPA

Automate manual, tedious, and repetitive tasks easily.

RPA
 
NEW
Apptics

Application analytics for all apps.

Apptics
 
Embedded BI

Embedded analytics and white label BI solutions, tailored for your needs.

Embedded BI
 
NEW
IoT

Build, deploy, and scale IoT solutions for connected businesses.

IoT
 
DataPrep

AI-powered data preparation service for your data-driven organization.

DataPrep

IoT

 
NEW
IoT

Low-code IoT platform and solutions for connected businesses.

IoT

Search Result

 
CRM Plus

Unified platform to deliver top-notch customer experience.

Try now
CRM Plus
 
Service Plus

Unified platform for customer service and support teams.

Try now
Service Plus
 
Finance Plus

All-in-one suite to manage your operations and finances.

Try now
Finance Plus
 
People Plus

Comprehensive HR platform for seamless employee experiences.

Try now
People Plus
 
Workplace

Application suite built to improve team productivity and collaboration.

Try now
Workplace
 
Marketing Plus

Unified marketing platform for marketing teams.

Try now
Marketing Plus
 
All-in-one suite

Zoho One

The Operating System for Business

Run your entire business on Zoho with our unified cloud software, designed to help you break down silos between departments and increase organizational efficiency.

TRY ZOHO ONE
Zoho One
Zoho Marketplace

With over 2000 ready-to-use extensions across 40+ categories, connect your favorite business tools with the Zoho products you already use.

EXPLORE MARKETPLACE
Marketplace
Skip to main content

Java SDK Samples - Bulk Write Operations

Upload File
              
              
package samples.src.com.zoho.crm.api.bulkwrite;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import com.zoho.crm.api.HeaderMap;

import com.zoho.crm.api.bulkwrite.SuccessResponse;

import com.zoho.crm.api.bulkwrite.APIException;

import com.zoho.crm.api.bulkwrite.ActionResponse;

import com.zoho.crm.api.bulkwrite.BulkWriteOperations;

import com.zoho.crm.api.bulkwrite.BulkWriteOperations.UploadFileHeader;

import com.zoho.crm.api.util.Choice;

import com.zoho.crm.api.bulkwrite.BulkWriteResponse;

import com.zoho.crm.api.bulkwrite.CallBack;

import com.zoho.crm.api.bulkwrite.FieldMapping;

import com.zoho.crm.api.bulkwrite.FileBodyWrapper;

import com.zoho.crm.api.bulkwrite.RequestWrapper;

import com.zoho.crm.api.bulkwrite.Resource;

import com.zoho.crm.api.bulkwrite.ResponseHandler;

import com.zoho.crm.api.bulkwrite.ResponseWrapper;

import com.zoho.crm.api.bulkwrite.Result;

import com.zoho.crm.api.util.APIResponse;

import com.zoho.crm.api.util.Model;

import com.zoho.crm.api.util.StreamWrapper;

public class BulkWrite
{
    
    /**
     * Upload File
     * This method is used to upload a CSV file in ZIP format for bulk write API. The response contains the file_id.
     * Use this ID while making the bulk write request.
     * @param orgID The unique ID (zgid) of your organization obtained through the Organization API.
     * @param absoluteFilePath The absolute path to the file you want to upload.
     * @throws Exception
     */
    public static void uploadFile(String orgID, String absoluteFilePath) throws Exception
    {
        //example
        //String absoluteFilePath = "/Users/user_name/Documents/Leads.zip";
        //String orgID = "673573045";
        
        //Get instance of BulkWriteOperations Class
        BulkWriteOperations bulkWriteOperations = new BulkWriteOperations();
        
        //Get instance of FileBodyWrapper class that will contain the request file
        com.zoho.crm.api.bulkwrite.FileBodyWrapper fileBodyWrapper = new com.zoho.crm.api.bulkwrite.FileBodyWrapper();
        
        //Get instance of StreamWrapper class that takes absolute path of the file to be attached as parameter
        StreamWrapper streamWrapper = new StreamWrapper(absoluteFilePath);
        
        //FileInputStream stream = new FileInputStream(absoluteFilePath);
        
        //Get instance of StreamWrapper class that takes file name and stream of the file to be attached as parameter
        //StreamWrapper streamWrapper = new StreamWrapper("Leads.zip", stream);
        
        //Set file to the FileBodyWrapper instance
        fileBodyWrapper.setFile(streamWrapper);
        
        //Get instance of HeaderMap Class
        HeaderMap headerInstance = new HeaderMap();
        
        //To indicate that this a bulk write operation
        headerInstance.add(UploadFileHeader.FEATURE, "bulk-write");
        
        headerInstance.add(UploadFileHeader.X_CRM_ORG, orgID);
        
        //Call uploadFile method that takes FileBodyWrapper instance and headerInstance as parameter
        APIResponse response = bulkWriteOperations.uploadFile(fileBodyWrapper, headerInstance);
        
        if(response != null)
        {
            //Get the status code from response
            System.out.println("Status Code: " + response.getStatusCode());
            
            //Check if expected response is received
            if(response.isExpected())
            {
                //Get object from response
                ActionResponse actionResponse = response.getObject();
                
                //Check if the request is successful
                if(actionResponse instanceof SuccessResponse)
                {
                    //Get the received SuccessResponse instance
                    SuccessResponse successResponse = (SuccessResponse)actionResponse;
                    
                    //Get the Status
                    System.out.println("Status: " + successResponse.getStatus().getValue());
                    
                    //Get the Code
                    System.out.println("Code: " + successResponse.getCode().getValue());
                    
                    System.out.println("Details: " );
                    
                    //Get the details map
                    for(Map.Entry entry : successResponse.getDetails().entrySet())
                    {
                        //Get each value in the map
                        System.out.println(entry.getKey() + ": " + entry.getValue());
                    }
                    
                    //Get the Message
                    System.out.println("Message: " + successResponse.getMessage().getValue());
                }
                //Check if the request returned an exception
                else if(actionResponse instanceof APIException)
                {
                    //Get the received APIException instance
                    APIException exception = (APIException) actionResponse;
                    
                    if(exception.getStatus() != null)
                    {
                        //Get the Status
                        System.out.println("Status: " + exception.getStatus().getValue());
                    }
                    
                    if(exception.getCode() != null)
                    {
                        //Get the Code
                        System.out.println("Code: " + exception.getCode().getValue());  
                    }
                    
                    if(exception.getMessage() != null)
                    {
                        //Get the Message
                        System.out.println("Message: " + exception.getMessage().getValue());
                    }
                    
                    System.out.println("Details: " );
                    
                    if(exception.getDetails() != null)
                    {
                        //Get the details map
                        for(Map.Entry entry : exception.getDetails().entrySet())
                        {
                            //Get each value in the map
                            System.out.println(entry.getKey() + ": " + entry.getValue());
                        }
                    }
                    
                    if(exception.getErrorMessage() != null)
                    {
                        //Get the ErrorMessage
                        System.out.println("ErrorMessage: " + exception.getErrorMessage().getValue());
                    }
                    
                    //Get the ErrorCode
                    System.out.println("ErrorCode: " + exception.getErrorCode());
                    
                    if(exception.getXError() != null)
                    {
                        //Get the XError
                        System.out.println("XError: " + exception.getXError().getValue());
                    }
                    
                    if(exception.getInfo() != null)
                    {
                        //Get the Info
                        System.out.println("Info: " + exception.getInfo().getValue());
                    }
                    
                    if(exception.getXInfo() != null)
                    {
                        //Get the XInfo
                        System.out.println("XInfo: " + exception.getXInfo().getValue());
                    }
                    
                    //Get the HttpStatus
                    System.out.println("HttpStatus: " + exception.getHttpStatus());
                }
            }
            else
            {//If response is not as expected
                
                //Get model object from response
                Model responseObject = response.getModel();
                
                //Get the response object's class
                Class extends Model> clas = responseObject.getClass();
                
                //Get all declared fields of the response class
                java.lang.reflect.Field[] fields = clas.getDeclaredFields();
                
                for(java.lang.reflect.Field field : fields)
                {
                    //Get each value
                    System.out.println(field.getName() + ":" + field.get(responseObject));
                }
            }
        }
    }
}
 
Create a Bulk Write Job
              
              
package samples.src.com.zoho.crm.api.bulkwrite;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import com.zoho.crm.api.HeaderMap;

import com.zoho.crm.api.bulkwrite.SuccessResponse;

import com.zoho.crm.api.bulkwrite.APIException;

import com.zoho.crm.api.bulkwrite.ActionResponse;

import com.zoho.crm.api.bulkwrite.BulkWriteOperations;

import com.zoho.crm.api.bulkwrite.BulkWriteOperations.UploadFileHeader;

import com.zoho.crm.api.util.Choice;

import com.zoho.crm.api.bulkwrite.BulkWriteResponse;

import com.zoho.crm.api.bulkwrite.CallBack;

import com.zoho.crm.api.bulkwrite.FieldMapping;

import com.zoho.crm.api.bulkwrite.FileBodyWrapper;

import com.zoho.crm.api.bulkwrite.RequestWrapper;

import com.zoho.crm.api.bulkwrite.Resource;

import com.zoho.crm.api.bulkwrite.ResponseHandler;

import com.zoho.crm.api.bulkwrite.ResponseWrapper;

import com.zoho.crm.api.bulkwrite.Result;

import com.zoho.crm.api.util.APIResponse;

import com.zoho.crm.api.util.Model;

import com.zoho.crm.api.util.StreamWrapper;

public class BulkWrite
{
    /**
     * Create BulkWrite Job
     * This method is used to create a bulk write job.
     * @param moduleAPIName The API Name of the record's module.
     * @param fileId The ID of the uploaded file to create BulkWrite Job.
     */
    public static void createBulkWriteJob(String moduleAPIName, String fileId) throws Exception
    {
        //example
        //String moduleAPIName = "Leads";
        //String fileId  = "34770616121001";
        
        //Get instance of BulkWriteOperations Class
        BulkWriteOperations bulkWriteOperations = new BulkWriteOperations();
        
        //Get instance of RequestWrapper Class that will contain the request body
        RequestWrapper requestWrapper = new RequestWrapper();
        
        //Get instance of CallBack Class
        CallBack callback = new CallBack();
        
        // To set valid callback URL.
        callback.setUrl("https://www.example.com/callback");
        
        //To set the HTTP method of the callback URL. The allowed value is post.
        callback.setMethod(new Choice("post"));
        
        //The Bulk Write Job's details are posted to this URL on successful completion of job or on failure of job.
        requestWrapper.setCallback(callback);
        
        //To set the charset of the uploaded file
        requestWrapper.setCharacterEncoding("UTF-8");
        
        //To set the type of operation you want to perform on the bulk write job.
        requestWrapper.setOperation(new Choice("upsert"));
        
        List resource = new ArrayList();
        
        //Get instance of Resource Class
        Resource resourceIns = new Resource();
        
        // To set the type of module that you want to import. The value is data.
        resourceIns.setType(new Choice("data"));
        
        //To set API name of the module that you select for bulk write job.
        resourceIns.setModule(moduleAPIName);
        
        //To set the file_id obtained from file upload API.
        resourceIns.setFileId(fileId);
        
        //True - Ignores the empty values.The default value is false. 
        resourceIns.setIgnoreEmpty(true);
        
        // To set a field as a unique field or ID of a record. 
        resourceIns.setFindBy("Email");
        
        List fieldMappings = new ArrayList();
        
        FieldMapping fieldMapping;
        
        //Get instance of FieldMapping Class
        fieldMapping = new FieldMapping();
        
        //To set API name of the field present in Zoho module object that you want to import. 
        fieldMapping.setAPIName("Last_Name");
        
        //To set the column index of the field you want to map to the CRM field.
        fieldMapping.setIndex(0);
        
        fieldMappings.add(fieldMapping);

        fieldMapping = new FieldMapping();
        
        fieldMapping.setAPIName("Email");
        
        fieldMapping.setIndex(1);
        
        fieldMappings.add(fieldMapping);
        
        fieldMapping = new FieldMapping();
        
        fieldMapping.setAPIName("Company");
        
        fieldMapping.setIndex(2);
        
        fieldMappings.add(fieldMapping);
        
        fieldMapping = new FieldMapping();
        
        fieldMapping.setAPIName("Phone");
        
        fieldMapping.setIndex(3);
        
        fieldMappings.add(fieldMapping);
        
        fieldMapping = new FieldMapping();
        
        fieldMapping.setAPIName("Website");
        
        //fieldMapping.setFormat("");
        
        //fieldMapping.setFindBy("");
        
        Map defaultValue = new HashMap();
        
        defaultValue.put("value", "https://www.zohoapis.com");
        
        //To set the default value for an empty column in the uploaded file.
        fieldMapping.setDefaultValue(defaultValue);
        
        fieldMappings.add(fieldMapping);
        
        resourceIns.setFieldMappings(fieldMappings);
        
        resource.add(resourceIns);
        
        requestWrapper.setResource(resource);
       
        //Call createBulkWriteJob method that takes RequestWrapper instance as parameter 
        APIResponse response = bulkWriteOperations.createBulkWriteJob(requestWrapper);
        
        if(response != null)
        {
            //Get the status code from response
            System.out.println("Status Code: " + response.getStatusCode());
            
            //Check if expected response is received
            if(response.isExpected())
            {
                //Get object from response
                ActionResponse actionResponse = response.getObject();
                
                //Check if the request is successful
                if(actionResponse instanceof SuccessResponse)
                {
                    //Get the received SuccessResponse instance
                    SuccessResponse successResponse = (SuccessResponse)actionResponse;
                    
                    //Get the Status
                    System.out.println("Status: " + successResponse.getStatus().getValue());
                    
                    //Get the Code
                    System.out.println("Code: " + successResponse.getCode().getValue());
                    
                    System.out.println("Details: " );
                    
                    //Get the details map
                    for(Map.Entry entry : successResponse.getDetails().entrySet())
                    {
                        //Get each value in the map
                        System.out.println(entry.getKey() + ": " + entry.getValue());
                    }
                    
                    //Get the Message
                    System.out.println("Message: " + successResponse.getMessage().getValue());
                }
                //Check if the request returned an exception
                else if(actionResponse instanceof APIException)
                {
                    //Get the received APIException instance
                    APIException exception = (APIException) actionResponse;
                    
                    //Get the Status
                    System.out.println("Status: " + exception.getStatus().getValue());
                    
                    //Get the Code
                    System.out.println("Code: " + exception.getCode().getValue());
                    
                    System.out.println("Details: " );
                    
                    //Get the details map
                    for(Map.Entry entry : exception.getDetails().entrySet())
                    {
                        //Get each value in the map
                        System.out.println(entry.getKey() + ": " + entry.getValue());
                    }
                    
                    //Get the Message
                    System.out.println("Message: " + exception.getMessage().getValue());
                }
            }
            else
            {//If response is not as expected
                
                //Get model object from response
                Model responseObject = response.getModel();
                
                //Get the response object's class
                Class extends Model> clas = responseObject.getClass();
                
                //Get all declared fields of the response class
                java.lang.reflect.Field[] fields = clas.getDeclaredFields();
                
                for(java.lang.reflect.Field field : fields)
                {
                    //Get each value
                    System.out.println(field.getName() + ":" + field.get(responseObject));
                }
            }
        }
    }
}
 
Get Bulk Write Job Details
Download Result
              
              
package samples.src.com.zoho.crm.api.bulkwrite;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import com.zoho.crm.api.HeaderMap;

import com.zoho.crm.api.bulkwrite.SuccessResponse;

import com.zoho.crm.api.bulkwrite.APIException;

import com.zoho.crm.api.bulkwrite.ActionResponse;

import com.zoho.crm.api.bulkwrite.BulkWriteOperations;

import com.zoho.crm.api.bulkwrite.BulkWriteOperations.UploadFileHeader;

import com.zoho.crm.api.util.Choice;

import com.zoho.crm.api.bulkwrite.BulkWriteResponse;

import com.zoho.crm.api.bulkwrite.CallBack;

import com.zoho.crm.api.bulkwrite.FieldMapping;

import com.zoho.crm.api.bulkwrite.FileBodyWrapper;

import com.zoho.crm.api.bulkwrite.RequestWrapper;

import com.zoho.crm.api.bulkwrite.Resource;

import com.zoho.crm.api.bulkwrite.ResponseHandler;

import com.zoho.crm.api.bulkwrite.ResponseWrapper;

import com.zoho.crm.api.bulkwrite.Result;

import com.zoho.crm.api.util.APIResponse;

import com.zoho.crm.api.util.Model;

import com.zoho.crm.api.util.StreamWrapper;

public class BulkWrite
{
    /**
     * Download BulkWrite Result
     * This method is used to download the result of the bulk write job as a CSV file.
     * @param downloadUrl The URL present in the download_url parameter in the response of Get Bulk Write Job Details.
     * @param destinationFolder The absolute path where downloaded file has to be stored.
     * @throws Exception
     */
    public static void downloadBulkWriteResult(String downloadUrl, String destinationFolder) throws Exception
    {
        //example
        //String downloadUrl = "https://download-accl.zoho.com/v2/crm/6735/bulk-write/347706122009/347706122009.zip";
        //String destinationFolder = "/Users/user_name/Documents";
        
        //Get instance of BulkWriteOperations Class
        BulkWriteOperations bulkWriteOperations = new BulkWriteOperations();
        
        //Call downloadBulkWriteResult method that takes downloadUrl as parameter
        APIResponse response = bulkWriteOperations.downloadBulkWriteResult(downloadUrl);
        
        if(response != null)
        {
            //Get the status code from response
            System.out.println("Status Code: " + response.getStatusCode());
            
            if(Arrays.asList(204,304).contains(response.getStatusCode()))
            {
                System.out.println(response.getStatusCode() == 204? "No Content" : "Not Modified");
                return;
            }
            
            //Check if expected response is received
            if(response.isExpected())
            {
                //Get object from response
                ResponseHandler responseHandler = response.getObject();
                
                if(responseHandler instanceof FileBodyWrapper)
                {
                    //Get object from response
                    FileBodyWrapper fileBodyWrapper = (FileBodyWrapper)responseHandler;
                    
                    //Get StreamWrapper instance from the returned FileBodyWrapper instance
                    StreamWrapper streamWrapper = fileBodyWrapper.getFile();
                    
                    //Create a file instance with the absolute_file_path
                    File file = new File(destinationFolder + File.separatorChar + streamWrapper.getName());
                    
                    //Get InputStream from the response
                    InputStream is = streamWrapper.getStream();
                    
                    //Create an OutputStream for the destination file
                    OutputStream os = new FileOutputStream(file);
                    
                    byte[] buffer = new byte[1024];
                    
                    int bytesRead;
                    
                    //read the InputStream till the end
                    while((bytesRead = is.read(buffer)) != -1)
                    {
                        //write data to OutputStream
                        os.write(buffer, 0, bytesRead);
                    }
                    
                    //Close the InputStream
                    is.close();
                    
                    //Flush and close the OutputStream
                    os.flush();
                    
                    os.close();
                }
                //Check if the request returned an exception
                else if(responseHandler instanceof APIException)
                {
                    //Get the received APIException instance
                    APIException exception = (APIException) responseHandler;
                    
                    if(exception.getStatus() != null)
                    {
                        //Get the Status
                        System.out.println("Status: " + exception.getStatus().getValue());
                    }
                    
                    if(exception.getCode() != null)
                    {
                        //Get the Code
                        System.out.println("Code: " + exception.getCode().getValue());
                    }
                    
                    if(exception.getDetails() != null)
                    {
                        System.out.println("Details: " );
                        
                        //Get the details map
                        for(Map.Entry entry : exception.getDetails().entrySet())
                        {
                            //Get each value in the map
                            System.out.println(entry.getKey() + ": " + entry.getValue());
                        }
                    }
                    
                    if(exception.getMessage() != null)
                    {
                        //Get the Message
                        System.out.println("Message: " + exception.getMessage().getValue());
                    }
                    
                    if(exception.getXError() != null)
                    {
                        //Get the Message
                        System.out.println("XError: " + exception.getXError().getValue());
                    }
                    
                    if(exception.getXInfo() != null)
                    {
                        //Get the Message
                        System.out.println("XInfo: " + exception.getXInfo().getValue());
                    }
                    
                    if(exception.getHttpStatus() != null)
                    {
                        //Get the Message
                        System.out.println("Message: " + exception.getHttpStatus());
                    }
                }
            }
            else
            {//If response is not as expected
                
                //Get model object from response
                Model responseObject = response.getModel();
                
                //Get the response object's class
                Class extends Model> clas = responseObject.getClass();
                
                //Get all declared fields of the response class
                java.lang.reflect.Field[] fields = clas.getDeclaredFields();
                
                for(java.lang.reflect.Field field : fields)
                {
                    //Get each value
                    System.out.println(field.getName() + ":" + field.get(responseObject));
                }
            }   
        }
    }
}