apimanager.ZohoSupportAPIManager.java Source code

Java tutorial

Introduction

Here is the source code for apimanager.ZohoSupportAPIManager.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package apimanager;

import ConnectionProtccol.HttpsClient;
import JSONParser.JSONOperations;
import loggerapi.CustomLogger;
import fileoperations.FileOperations;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author harsha-1916
 */
public class ZohoSupportAPIManager {

    private static final CustomLogger loggerProperties = new CustomLogger();
    private static Logger loggerObj;
    private static final String ENCODETYPE = "UTF-8";

    private static final String AUTHTOKEN = "authtoken";
    private static final String PORTAL = "portal";
    private static final String DEPARTMENT = "department";

    static {
        initializeLoggerParams();
    }

    private static void initializeLoggerParams() {

        boolean isValidLogger = loggerProperties.setLoggerProperties("zohoSuppportApi",
                "./Logs/ZohoSupportApi.%u.%g.txt");
        if (isValidLogger) {
            loggerObj = loggerProperties.getLogger();
            //loggerObj.setUseParentHandlers(false);
        }

    }

    private String getCurrTimeInDD_MM_YY_HH_MM_SS() {
        DateFormat dateFormat = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
        Date date = new Date();
        return dateFormat.format(date);
    }

    private JSONObject searchTicketsbyCriteria(String authToken, String portal, String department,
            String searchField, String searchValue, String columns, String fileToWriteResponse, int index) {
        int fromIndex = ((index - 1) * 200 + 1);
        int toIndex = index * 200;

        String baseURL = "";

        try {
            baseURL = "https://support.zoho.com/api/json/requests/getrecordsbysearch?authtoken=" + authToken
                    + "&portal=" + URLEncoder.encode(portal, ENCODETYPE) + "&department="
                    + URLEncoder.encode(department, ENCODETYPE) + "&searchfield="
                    + URLEncoder.encode(searchField, ENCODETYPE) + "&searchvalue="
                    + URLEncoder.encode(searchValue, ENCODETYPE) + "&selectfields=requests("
                    + URLEncoder.encode(columns, ENCODETYPE) + ")" + "&fromindex=" + fromIndex + "&toindex="
                    + toIndex;
        } catch (UnsupportedEncodingException ex) {
            loggerObj.log(Level.SEVERE, "UnsupportedEncodingException for the url" + baseURL + "Exception is ", ex);
            return null;
        }

        loggerObj.log(Level.INFO, "Base url to connet to zoho is: " + baseURL);

        //https://support.zoho.com/api/json/requests/getrecordsbysearch?authtoken=46a5e812261b7f237b5fc440866a43fb&portal=medcsupport&department=MDM%20Plus&searchfield=Request%20Id&searchvalue=36485&selectfields=requests(Ticket%20Classification)&fromindex=1&toindex=200
        HttpsClient httpsClient = new HttpsClient();
        String result = httpsClient.OpenHTTPSConnection(baseURL);

        JSONObject json = null;
        if (!JSONOperations.isErrorJSON(result)) {
            JSONParser parser = new JSONParser();
            try {
                json = (JSONObject) parser.parse(result);
            } catch (ParseException ex) {
                loggerObj.log(Level.INFO,
                        "Problem in parsing the data from Zoho Support. Exception is " + ex.toString());
                return null;
            }
        }

        if (json != null) {
            String fileToWrite = fileToWriteResponse + index + ".json";
            loggerObj.log(Level.INFO, "File to write  is " + fileToWrite);
            boolean isFileWriteSuccess = FileOperations.writeObjectToFile(json, fileToWrite);
            if (!isFileWriteSuccess) {
                loggerObj.log(Level.INFO,
                        "Problem in writing the data from Zoho Support to the file: " + fileToWrite);
                return null;
            }
        }
        return json;

    }

    public Integer getCompletesearchTicketsbyCriteria(JSONObject urlParams, String[] searchCriteria,
            String[] ColumnSet, String fileToWriteResponse, int maxIndex) {
        loggerObj.log(Level.INFO, "Inside getCompletesearchTicketsbyCriteria method");
        Integer index = 1;

        String authToken = (String) urlParams.get(AUTHTOKEN);
        String portal = (String) urlParams.get(PORTAL);
        String department = (String) urlParams.get(DEPARTMENT);

        String searchField = searchCriteria[0];
        String searchValue = searchCriteria[1];

        String columns = "";

        for (String i : ColumnSet) {
            columns += i;
            columns += ",";
        }
        columns = columns.substring(0, columns.length() - 1);
        System.out.println(columns);

        if (columns.equals("")) {
            loggerObj.log(Level.INFO, "Colums obtained is empty");
        }

        System.out.println("Trying to connect to zoho support(" + portal + " portal) server......");
        loggerObj.log(Level.INFO,
                "Going to connect to zoho support with following params: " + "authToken: " + authToken + " portal: "
                        + portal + " dept: " + department + " searchField: " + searchField + " searchValue: "
                        + searchValue + " columns: " + columns + " fileToWriteResponse: " + fileToWriteResponse
                        + " index: " + index);
        JSONObject resultObj = searchTicketsbyCriteria(authToken, portal, department, searchField, searchValue,
                columns, fileToWriteResponse, index);
        if (resultObj == null) {
            System.out.println("Connection failure");
            loggerObj.log(Level.INFO, "connection problem getCompletesearchTicketsbyCriteria method");
            return null;

        }
        System.out.println("connection successfull...");
        System.out.println("Requesting tickets from zoho support api(" + portal
                + " portal)... \nThis might take around 5 mins");
        index++;
        while (resultObj != null && (maxIndex < 1 || index < maxIndex)) {
            loggerObj.log(Level.INFO,
                    "received tickets in the range: " + ((index - 1) * 200 + 1) + " to " + index * 200);

            System.out.print(".");
            resultObj = searchTicketsbyCriteria(authToken, portal, department, searchField, searchValue, columns,
                    fileToWriteResponse, index);
            index++;
        }
        System.out.println("\nTickets received from zoho support api... Going to process the tickets");

        index = index - 1;
        return index;

    }

    private JSONObject getThreadIds(String authtoken, String portal, String department, String caseID,
            boolean needDescription, String fileToWriteResponse, int index) {

        String baseURL = "";
        try {
            baseURL = "https://support.zoho.com/api/json/requests/getrequestthreads?authtoken=" + authtoken
                    + "&portal=" + URLEncoder.encode(portal, ENCODETYPE) + "&department="
                    + URLEncoder.encode(department, ENCODETYPE) + "&requestid=" + caseID + "&needdescription="
                    + needDescription;
        } catch (UnsupportedEncodingException ex) {
            loggerObj.log(Level.SEVERE, "UnsupportedEncodingException in url " + baseURL + "Exception is :", ex);
            return null;
        }

        loggerObj.log(Level.INFO, "Going to connect " + portal + " portal with base URL " + baseURL);

        HttpsClient httpsClient = new HttpsClient();
        String result = httpsClient.OpenHTTPSConnection(baseURL);

        JSONObject json = null;
        if (!JSONOperations.isErrorJSON(result)) {
            JSONParser parser = new JSONParser();
            try {
                json = (JSONObject) parser.parse(result);
            } catch (ParseException ex) {
                loggerObj.log(Level.INFO,
                        "Problem in parsing the data from Zoho Support. Exception is " + ex.toString());
            }
        }

        if (json != null) {
            String FileToWrite = fileToWriteResponse + index + ".json";
            boolean isFileWriteSuccess = FileOperations.writeObjectToFile(json, FileToWrite);
            if (!isFileWriteSuccess) {
                loggerObj.log(Level.SEVERE,
                        "Problem in writing the data from Zoho Support to the file: " + FileToWrite);
            }
        }
        return json;

    }

    public Integer getCompleteThreadIds(JSONObject urlParams, String[] requestParams, String fileToWriteResponse,
            int maxIndex) {
        Integer index = 1;

        String authToken = (String) urlParams.get(AUTHTOKEN);
        String portal = (String) urlParams.get(PORTAL);
        String department = (String) urlParams.get(DEPARTMENT);

        String caseId = requestParams[0];
        boolean needDescription = Boolean.parseBoolean(requestParams[1]);

        System.out.println("Trying to connect to zoho support(" + portal + " portal) server......");
        JSONObject resultObj = getThreadIds(authToken, portal, department, caseId, needDescription,
                fileToWriteResponse, index);
        if (resultObj == null) {
            System.out.println("Connection failure");
            loggerObj.log(Level.INFO, "connection problem getCompleteThreadIds method");
            return null;

        }
        System.out.println("connection successfull...");
        System.out.println("Requesting tickets from zoho support api(" + portal
                + " portal)... \nThis might take around 5 mins");
        index++;
        while (resultObj != null && (maxIndex < 1 || index < maxIndex)) {
            loggerObj.log(Level.INFO,
                    "received tickets in the range: " + ((index - 1) * 200 + 1) + " to " + index * 200);

            System.out.print(".");
            resultObj = getThreadIds(authToken, portal, department, caseId, needDescription, fileToWriteResponse,
                    index);
            index++;
        }
        System.out.println("\nTickets received from zoho support api... Going to process the tickets");

        index = index - 1;
        return index;

    }

    public boolean getThreadContent(JSONObject urlParams, String threadId, String fileToWriteResponse) {
        String authToken = (String) urlParams.get(AUTHTOKEN);
        String portal = (String) urlParams.get(PORTAL);
        String department = (String) urlParams.get(DEPARTMENT);

        String baseURL = null;
        try {
            baseURL = "https://support.zoho.com/api/xml/requests/getthreadinfo?authtoken=" + authToken + "&portal="
                    + URLEncoder.encode(portal, ENCODETYPE) + "&department="
                    + URLEncoder.encode(department, ENCODETYPE) + "&threadid=" + threadId;

            // https://support.zoho.com/api/xml/requests/getthreadinfo?authtoken=46a5e812261b7f237b5fc440866a43fb&portal=medcsupport&department=MDM%20Plus&threadid=255000004261484
        } catch (UnsupportedEncodingException ex) {
            loggerObj.log(Level.INFO, "baseURL is not formed properly" + ex.toString());
        }

        HttpsClient httpsClient = new HttpsClient();
        String result = httpsClient.OpenHTTPSConnection(baseURL);

        boolean isFileWriteSuccess = FileOperations.writeObjectToFile(result, fileToWriteResponse);
        if (!isFileWriteSuccess) {
            loggerObj.log(Level.INFO,
                    "Problem in writing the data from Zoho Support to the file: " + fileToWriteResponse);
            return false;
        }

        return true;
    }

    private JSONObject getSupportsRecordsAPI(int index, String authtoken, String portal, String dept,
            String columns, String folderToWriteResponse) {

        int fromIndex = ((index - 1) * 200 + 1);
        int toIndex = index * 200;

        String baseURL = null;
        try {
            baseURL = "https://support.zoho.com/api/json/requests/getrecords?authtoken=" + authtoken + "&portal="
                    + URLEncoder.encode(portal, ENCODETYPE) + "&department=" + URLEncoder.encode(dept, ENCODETYPE)
                    + "&selectfields=requests(" + URLEncoder.encode(columns, ENCODETYPE) + ")";
            //String baseURL = "https://support.zoho.com/api/json/requests/getrecords?authtoken=8ecc8d0229b00b83d4c398b19a4282bc&portal=memdmissuemgr&department=MDM%20Issue%20Mgr&selectfields=requests(Status,Module,Created%20At,Functionality,Issue%20Type,OS%20Platform)";
        } catch (UnsupportedEncodingException ex) {
            loggerObj.log(Level.INFO, "baseURL is not formed properly" + ex.toString());
        }

        String fromIndexString = "&fromindex=" + fromIndex;
        String toIndexString = "&toindex=" + toIndex;
        String baseURL_Critirea = baseURL + fromIndexString + toIndexString;
        HttpsClient httpsClient = new HttpsClient();

        loggerObj.log(Level.INFO, "Going to connect to the url: " + baseURL_Critirea);
        System.out.println("Going to connect to the url: " + baseURL_Critirea);

        String result = httpsClient.OpenHTTPSConnection(baseURL_Critirea);
        JSONObject json = null;
        if (!JSONOperations.isErrorJSON(result)) {
            JSONParser parser = new JSONParser();
            try {
                json = (JSONObject) parser.parse(result);
            } catch (ParseException ex) {
                loggerObj.log(Level.INFO,
                        "Problem in parsing the data from Zoho Support. Exception is " + ex.toString());
                return null;
            }
        }
        if (json != null) {
            String FileToWrite = folderToWriteResponse + "/JSONResponse_" + index + ".json";
            boolean isFileWriteSuccess = FileOperations.writeObjectToFile(json, FileToWrite);
            if (!isFileWriteSuccess) {
                loggerObj.log(Level.INFO,
                        "Problem in writing the data from Zoho Support to the file: " + FileToWrite);
            }
        }
        return json;
    }

    //maxIndex is used to determine the maximum amount of requests that can be sent from our app to support
    public String[] getCompleteSupportRecordsApi(JSONObject connectionParams, String[] columnSet,
            String folderToWriteResponse, int maxIndex) {

        if (connectionParams == null) {
            return null;
        }

        String authtoken = (String) connectionParams.get(AUTHTOKEN);
        String portal = (String) connectionParams.get(PORTAL);
        String dept = (String) connectionParams.get(DEPARTMENT);

        Integer index = 1;

        String columns = "";
        for (String i : columnSet) {
            columns += i;

            columns += ",";
        }
        columns = columns.substring(0, columns.length() - 1);
        System.out.println(columns);

        loggerObj.log(Level.INFO, "Colums got from columset is " + columns);

        if (columns.equals("")) {
            loggerObj.log(Level.INFO, "Colums obtained is empty");
            return null;
        }

        //FromMEMDMServer

        System.out.println("Trying to connect to zoho support " + portal + " server......");
        JSONObject resultObj = getSupportsRecordsAPI(index, authtoken, portal, dept, columns,
                folderToWriteResponse);
        if (resultObj == null) {
            System.out.println("Connection failure");
            loggerObj.log(Level.INFO, "connection problem in getCompleteRecordsForMEDCSupport method");
            return null;

        }
        System.out.println("connection successfull...");
        System.out.println(
                "Requesting tickets from zoho support api(MEMDM portal)... \nThis might take around 5 mins");

        //Handling case when maxIndex = 1;
        if (index == maxIndex) {
            return new String[] { folderToWriteResponse + "/JSONResponse_", index.toString() };
        }
        while (resultObj != null && (maxIndex < 1 || index < maxIndex)) {
            loggerObj.log(Level.INFO,
                    "received tickets in the range: " + ((index - 1) * 200 + 1) + " to " + index * 200);

            System.out.print(".");
            index++;
            resultObj = getSupportsRecordsAPI(index, authtoken, portal, dept, columns, folderToWriteResponse);
            loggerObj.log(Level.INFO, "current Index obtained is: " + index);
        }
        System.out.println("\nTickets received from zoho support api... Going to process the tickets");

        index = index - 1;
        loggerObj.log(Level.INFO, "Finalized Index obtained from zoho support is " + index);
        return new String[] { folderToWriteResponse + "/JSONResponse_", index.toString() };
    }

    public JSONObject getRecordsForMEDCSupport(String departmentName, String folderToWriteResponse, int index) {
        //this logic uses index to increment the fromIndex and toIndex in the sequence: 1 to 200 , 201 to 400, 401 to 600, 601 to 800, etc,. 
        int fromIndex = ((index - 1) * 200 + 1);
        int toIndex = index * 200;
        String baseURL = "https://support.zoho.com/api/json/requests/getrecords?authtoken=46a5e812261b7f237b5fc440866a43fb&portal=medcsupport&department="
                + departmentName
                + "&selectfields=requests(Department%20Map,Created%20Time,Status,Ticket%20Id,Email,Subject,Developers,Ticket%20Owner,Modules,Due%20Date,Problem%20Description)";
        baseURL = baseURL.replace(" ", "%20");
        String fromIndexString = "&fromindex=" + fromIndex;
        String toIndexString = "&toindex=" + toIndex;
        String baseURL_Critirea = baseURL + fromIndexString + toIndexString;
        loggerObj.log(Level.INFO, "BaseURL generated to open connection is " + baseURL);

        HttpsClient httpsClient = new HttpsClient();
        String result = httpsClient.OpenHTTPSConnection(baseURL_Critirea);
        loggerObj.log(Level.INFO, "Resultant object received from MEDC server" + result);
        JSONObject json = null;
        if (!JSONOperations.isErrorJSON(result)) {
            JSONParser parser = new JSONParser();
            try {
                json = (JSONObject) parser.parse(result);
            } catch (ParseException ex) {
                loggerObj.log(Level.INFO, "JSON recieved from MEDCSupport is not valid: " + result.toString());
                return null;
            }
        } else {
            return null;
        }
        DateFormat dateFormat = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
        Date date = new Date();
        String currTime = dateFormat.format(date);
        if (json != null) {
            String FileToWrite = folderToWriteResponse + "/JSONResponse_" + index + ".json";
            FileOperations.writeObjectToFile(json, FileToWrite);
        }

        return json;

    }

    //This method returns a string array consisting of two values:
    //1: String which contains the folder name where all the response JSON is written.
    //2. The index which contains the number of files inside the folder.
    // The files are written as JSONResponse_1, JSONResponse_2,..JSONResponse_10 (if index = 10)
    //So the api call to this method can get the folder and iterate over JSONResponse_1 to JSONResponse_10(where index =10)
    //to get all the JSON responses from support api
    public String[] getCompleteRecordsForMEDCSupport(String departName) {
        Integer index = 1;

        System.out.println(
                "Trying to connect to zoho support(MEDCSupport portal -->" + departName + ") server......");
        loggerObj.log(Level.INFO,
                "Trying to connect to zoho support(MEDCSupport portal -->" + departName + ") server......");

        DateFormat dateFormat = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
        Date date = new Date();
        String currTime = dateFormat.format(date);
        String folderToWriteResponse = "./Files/FromMEDCServer/" + currTime;
        boolean createFolderToWriteResponse = new File(folderToWriteResponse).mkdirs();

        if (!createFolderToWriteResponse) {
            loggerObj.log(Level.INFO, "Cannot create a folder" + folderToWriteResponse + " to write response");
            return null;
        }

        JSONObject resultObj = getRecordsForMEDCSupport(departName, folderToWriteResponse, index);
        loggerObj.log(Level.INFO, "Resultant object received from MEDC server is:" + resultObj.toString());

        if (resultObj == null) {
            System.out.println("Connection failure");
            loggerObj.log(Level.INFO, "connection problem in getCompleteRecordsForMEDCSupport method");
            return null;

        }
        System.out.println("connection successfull...");
        loggerObj.log(Level.INFO, "connection successfull...");
        System.out.println("Requesting tickets from zoho support api(MEDC support portal--->" + departName
                + ") server... \nThis might take around 5 mins");
        loggerObj.log(Level.INFO, "Requesting tickets from zoho support api(MEDC support portal--->" + departName
                + ") server... \nThis might take around 5 mins");

        while (resultObj != null) {
            //this logic uses index to increment the fromIndex and toIndex in the sequence: 1 to 200 , 201 to 400, 401 to 600, 601 to 800, etc,.
            loggerObj.log(Level.INFO,
                    "received tickets in the range: " + ((index - 1) * 200 + 1) + " to " + index * 200);

            System.out.print(".");
            resultObj = getRecordsForMEDCSupport(departName, folderToWriteResponse, ++index);

        }
        System.out.println("\nReceived tickets from zoho support api... Going to process the tickets");
        loggerObj.log(Level.INFO, "\nReceived tickets from zoho support api... Going to process the tickets");

        //This is done so the last file is not written as that is a error file.
        index = index - 1;
        loggerObj.log(Level.INFO, "The folderToWriteResponse is " + folderToWriteResponse + "/JSONResponse_"
                + "The index value is " + index);

        return new String[] { folderToWriteResponse + "/JSONResponse_", index.toString() };
    }

}