Configure the Event Function

We will now begin coding the WorkDrive Sync app by configuring the Event function.

Note: We will need to code and deploy the application code to the Catalyst remote console before configuring the event listener in the Catalyst console, because we have to associate it with the Event function.

The functions directoryfunctions/WorkDrive contains:

  • The WorkDriveSync.java main function file
  • The catalyst-config.json configuration file
  • Java library files in the lib folder
  • .classpath and .project dependency files

You will be adding code in WorkDriveSync.java.

You can use any IDE to configure the function.

Note: Please go through the code in this section to make sure you fully understand it. We will discuss the function and client code, after you configure the client.

You can directly copy the code below and paste it in WorkDriveSync.java located in the functions/WorkDrive directory and save the file.

WorkDriveSync.java
copy
import com.catalyst.Context;
import com.catalyst.event.EVENT_STATUS;
import com.catalyst.event.EventRequest;
import com.catalyst.event.CatalystEventHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.List;
import java.util.ArrayList;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONObject;
import org.json.JSONArray;
import com.zc.component.object.ZCRowObject;
import com.zc.component.object.ZCTable;
import com.zc.component.zcql.ZCQL;
import com.zc.component.object.ZCObject;
import com.zc.component.object.ZCRowObject;
import com.zc.component.object.ZCTable;
import com.zc.auth.connectors.ZCConnection;
import com.zc.component.stratus.ZCStratus;
import com.zc.component.stratus.ZCBucket;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class WorkDriveSync implements CatalystEventHandler {
	private static final Logger LOGGER = Logger.getLogger(WorkDriveSync.class.getName());
    private static final String CLIENT_ID = "{{YOUR_CLIENT_ID}}"; //Enter your Client ID
    private static final String CLIENT_SECRET = "{{YOUR_CLIENT_SECRET}}"; //Enter your Client Secret
    private static final String AUTH_URL = "https://accounts.zoho.com/oauth/v2/token";
    private static final String REFRESH_URL = "https://accounts.zoho.com/oauth/v2/token";
    private static final String REFRESH_TOKEN = "{{YOUR_REFRESH_TOKEN}}"; //Enter your Refresh Token
    private static final String WORKDRIVE_FOLDER_ID = "{{YOUR_WORKDRIVE_FOLDER_ID}}"; //Enter your WorkDrive Folder ID
    private static final String STRATUS_BUCKET_NAME = "{{YOUR_STRATUS_BUCKET_NAME}}"; // Enter you bucket name
    private static final String FILE_VAULT_TABLE_NAME = "FileVault";
	private static final OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build(); 
	@Override
    public EVENT_STATUS handleEvent(EventRequest paramEventRequest, Context paramContext) throws Exception {
		try {
			JSONObject eventData = (JSONObject) paramEventRequest.getRawData();
			JSONArray eventsArray = (JSONArray) eventData.get("events");
            JSONObject firstEvent = (JSONObject) eventsArray.get(0);
			String eventType = (String) ((JSONObject) firstEvent.get("event_config")).get("api_name");
            String fileName = (String) ((JSONObject) ((JSONArray) ((JSONObject) firstEvent.get("data")).get("object_details")).get(0)).get("key");
			LOGGER.log(Level.INFO, "Received event: " + eventType + " for file: " + fileName);
			String query = "SELECT ROWID, WorkDriveFileID FROM " + FILE_VAULT_TABLE_NAME + " WHERE FileName='" + fileName + "'";
            List<ZCRowObject> queryResult = ZCQL.getInstance().executeQuery(query);
			if (queryResult.isEmpty()) {
				LOGGER.log(Level.INFO, "No entry found in " + FILE_VAULT_TABLE_NAME + " for file: " + fileName);
                return EVENT_STATUS.SUCCESS;
            }
			ZCRowObject fileVaultEntry = queryResult.get(0);
            Long rowId = Long.valueOf((String) fileVaultEntry.get("ROWID"));
            String workDriveFileId = (String) fileVaultEntry.get("WorkDriveFileID");
			LOGGER.log(Level.INFO, "Row Id: " + rowId + " , WorkDriveFileID: " + workDriveFileId);
			if ("stratus_object_uploaded".equals(eventType)) {
                handleUploadEvent(paramContext, fileName, rowId);
            } else if ("stratus_object_deleted".equals(eventType)) {
                handleDeleteEvent(paramContext, fileName, rowId, workDriveFileId);
            }
			return EVENT_STATUS.SUCCESS;
		} catch(Exception ex) {
			LOGGER.log(Level.SEVERE, "Exception in WorkDriveSync Function: ", ex);
			return EVENT_STATUS.FAILURE;
		}
	}
	private void handleUploadEvent(Context context, String fileName, Long rowId) throws Exception {
		ZCStratus stratus = ZCStratus.getInstance();
		ZCBucket bucket = stratus.bucketInstance(STRATUS_BUCKET_NAME);
		LOGGER.log(Level.INFO, "Going to fetch the file " + fileName + " from the bucket " + STRATUS_BUCKET_NAME);
		String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
		InputStream dataStream = bucket.getObject(encodedFileName);
		byte[] buffer = new byte[dataStream.available()];
		dataStream.read(buffer);
		File targetFile = new File(fileName);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(buffer);
		outStream.close();
		String accessToken = getAccessToken();
		RequestBody body = new MultipartBody.Builder()
					.setType(MultipartBody.FORM)
					.addFormDataPart("content", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), new File(fileName)))
					.build();
		Request request = new Request.Builder()
					.url("https://workdrive.zoho.com/api/v1/upload?filename=" + fileName + "&override-name-exist=true&parent_id=" + WORKDRIVE_FOLDER_ID)
					.method("POST", body)
					.addHeader("Authorization", "Zoho-oauthtoken " + accessToken)
					.build();
		Response response = okHttpClient.newCall(request).execute();
		JSONObject responseJSON = new JSONObject(response.body().string());
		JSONObject data = responseJSON.getJSONArray("data").getJSONObject(0);
		String resourceId = data.getJSONObject("attributes").getString("resource_id");
		LOGGER.log(Level.INFO, "WorkDrive File ID :: " + resourceId);
		ZCObject object = ZCObject.getInstance();
        ZCTable table = object.getTable(FILE_VAULT_TABLE_NAME); 
        List<ZCRowObject> rowsToUpdate = new ArrayList<>();
        ZCRowObject row = ZCRowObject.getInstance();
        row.set("ROWID", rowId); 
        row.set("WorkDriveFileID", resourceId);
        row.set("WorkDriveSync", "Uploaded"); 
        rowsToUpdate.add(row);
        table.updateRows(rowsToUpdate);
        LOGGER.log(Level.INFO, "FileVault table updated for ROWID: " + rowId + " with WorkDriveFileID: " + resourceId);
	}
	private void handleDeleteEvent(Context context, String fileName, Long rowId, String workDriveFileId) throws Exception {	
		JSONObject requestBody = new JSONObject();
        JSONObject dataObject = new JSONObject();
        JSONObject attributesObject = new JSONObject();
        attributesObject.put("status", "51"); 
        dataObject.put("attributes", attributesObject);
        dataObject.put("type", "files");
        requestBody.put("data", dataObject);
		Request request = new Request.Builder()
                    .url(String.format("https://workdrive.zoho.com/api/v1/files/%s", workDriveFileId))
                    .patch(RequestBody.create(MediaType.parse("application/json"), requestBody.toString()))
                    .addHeader("Authorization", "Zoho-oauthtoken " + getAccessToken()) 
                    .addHeader("Accept", "application/vnd.api+json")
                    .addHeader("Content-Type", "application/json")
                    .build();
		Response response = okHttpClient.newCall(request).execute();
		LOGGER.log(Level.INFO, "WorkDrive Delete Response Status: " + response.code());
		LOGGER.log(Level.INFO, "WorkDrive Delete Response Body: " + response.body().string());
		ZCObject object = ZCObject.getInstance();
		ZCTable table = object.getTable(FILE_VAULT_TABLE_NAME);
		table.deleteRow(rowId);
		LOGGER.log(Level.INFO, "FileVault table entry deleted for ROWID: " + rowId);
	}
	@SuppressWarnings("unchecked")
    public String getAccessToken() throws Exception {
        org.json.simple.JSONObject authJson = new org.json.simple.JSONObject();
        org.json.simple.JSONObject connectorJson = new org.json.simple.JSONObject();
        authJson.put("client_id", CLIENT_ID);
        authJson.put("client_secret", CLIENT_SECRET);
        authJson.put("auth_url", AUTH_URL);
        authJson.put("refresh_url", REFRESH_URL);
        authJson.put("refresh_token", REFRESH_TOKEN);
        connectorJson.put("WorkDriveConnector", authJson);
        return ZCConnection.getInstance(connectorJson).getConnector("WorkDriveConnector").getAccessToken();
    }
}
View more
Note: After you copy and paste this code in your function file, ensure that you provide the following values in it, as indicated by the comments:
  • Client ID

  • Client Secret

  • The Zoho service links used in this code (for example, accounts.zoho.com, workdrive.zoho.com, etc.) are Data Center (DC) specific. Replace .com with your corresponding Zoho data center domain. Ensure that all URLs in the code use the same DC domain to avoid authentication or API errors.

  • Refresh Token

  • WorkDrive Folder ID: You can obtain this value by opening the folder you created in WorkDrive earlier. The URL contains the Folder ID of the WorkDrive folder. Copy the ID displayed after folders/ from the URL. catalyst_workdrive_folderid

  • Table ID: You can obtain the table ID of your table in the Data Store under its name. catalyst_workdrive_tableid

The Event function is now configured.

Last Updated 2025-10-29 12:32:36 +0530 IST

RELATED LINKS

Event Functions