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.
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 java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
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 okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import com.catalyst.Context;
import com.catalyst.event.EVENT_STATUS;
import com.catalyst.event.EventRequest;
import com.catalyst.event.CatalystEventHandler;
import com.zc.auth.connectors.ZCConnection;
import com.zc.component.files.ZCFile;
import com.zc.component.files.ZCFolder;
import com.zc.component.object.ZCObject;
import com.zc.component.object.ZCRowObject;
import com.zc.component.object.ZCTable;
import com.zc.component.zcql.ZCQL;
public class WorkDriveSync implements CatalystEventHandler {
private static final Logger LOGGER = Logger.getLogger(WorkDriveSync.class.getName());
JSONParser jsonParser = new JSONParser();
private static final String WORKDRIVE_FOLDERID = "{{WORKDRIVE_FOLDER_ID}}"; //Enter your WorkDrive Folder ID
@Override
public EVENT_STATUS handleEvent(EventRequest paramEventRequest, Context paramContext) throws Exception {
try {
ZCFile fileStore = ZCFile.getInstance();
org.json.JSONObject eventData = (org.json.JSONObject) paramEventRequest.getData();
ZCFolder folder = fileStore.getFolderInstance(Long.parseLong(eventData.get("folder_details").toString()));
InputStream is = folder.downloadFile(Long.parseLong(eventData.get("id").toString()));
Response response = uploadFiletoWorkdrive(is, eventData);
if (response.code() == 200) {
org.json.simple.JSONObject resData = (org.json.simple.JSONObject) jsonParser
.parse(response.body().string());
JSONArray array = (JSONArray) resData.get("data");
JSONObject data = (JSONObject) array.get(0);
JSONObject attributes = (JSONObject) data.get("attributes");
String resourceId = (String) attributes.get("resource_id");
LOGGER.log(Level.SEVERE, resourceId);
String query = "SELECT ROWID FROM WorkDriveFileID where FileID=" + eventData.get("id").toString();
ArrayList rowList = ZCQL.getInstance().executeQuery(query);
Object ROWID = rowList.get(0).get("WorkDriveFileID", "ROWID");
ZCObject object = ZCObject.getInstance();
ZCTable table = object.getTable(1611000000552900L); //Replace this with your Table ID
List rows = new ArrayList();
ZCRowObject row = ZCRowObject.getInstance();
row.set("WorkDriveFileID", resourceId);
row.set("WorkDriveSync", "Completed");
row.set("ROWID", Long.parseLong(ROWID.toString()));
rows.add(row);
table.updateRows(rows);
return EVENT_STATUS.SUCCESS;
} else {
LOGGER.log(Level.SEVERE, "WorkDrive API Exception");
return EVENT_STATUS.FAILURE;
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in WDSync Function", e);
return EVENT_STATUS.FAILURE;
}
}
@SuppressWarnings("unchecked")
public String getAccessToken() throws Exception {
JSONObject authJson = new JSONObject();
JSONObject connectorJson = new JSONObject();
authJson.put("client_id", "{{YOUR_CLIENT_ID}}"); //Enter your Client ID
authJson.put("client_secret", "{{YOUR_CLIENT_SECRET}}"); //Enter your Client Secret
authJson.put("auth_url", "https://accounts.zoho.com/oauth/v2/token");
authJson.put("refresh_url", "https://accounts.zoho.com/oauth/v2/token");
authJson.put("refresh_token", "{{YOUR_REFRESH_TOKEN}}"); //Enter your Refresh Token
connectorJson.put("WorkDriveConnector", authJson);
return ZCConnection.getInstance(connectorJson).getConnector("WorkDriveConnector").getAccessToken();
}
public Response uploadFiletoWorkdrive(InputStream is, org.json.JSONObject eventData) throws Exception {
byte[] buffer = new byte[is.available()];
is.read(buffer);
File targetFile = new File(eventData.get("file_name").toString());
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
String accessToken = getAccessToken();
OkHttpClient client = new OkHttpClient().newBuilder().build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("content", eventData.get("file_name").toString(), RequestBody.create(MediaType.parse("application/octet-stream"), new File(eventData.get("file_name").toString()))).build();
Request request = new Request.Builder().url("https://workdrive.zoho.com/api/v1/upload?filename=" + eventData.get("file_name").toString() + "&override-name-exist=true&parent_id=" + WORKDRIVE_FOLDERID).method("POST", body).addHeader("Authorization", "Zoho-oauthtoken " + accessToken).build();
return client.newCall(request).execute();
}
}
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:
WorkDrive Folder ID in line 37: 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.
Table ID in line 68: You can obtain the table ID of your table in the Data Store under its name.