Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Google Drive - Build a Local Cache of Metadata

See more Google Drive Examples

This example demonstrates how to download the metadata for all files in a Google Drive account to create a local filesystem cache with the information. The cache can be used to fetch information without having to query Google Drive.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.AuthGoogle;
import com.chilkatsoft.chilkat2.Cache;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Hashtable;
import com.chilkatsoft.chilkat2.JsonArray;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.StringArray;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        success = true;

        // It requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // This example uses a previously obtained access token having permission for the
        // Google Drive scope.

        AuthGoogle gAuth = new AuthGoogle();
        gAuth.setAccessToken("GOOGLE_DRIVE_ACCESS_TOKEN");

        Rest rest = new Rest();

        // Connect using TLS.
        boolean bAutoReconnect = true;
        rest.connect("www.googleapis.com", 443, true, bAutoReconnect);

        // Provide the authentication credentials (i.e. the access token)
        rest.setAuthGoogle(gAuth);

        // -------------------------------------------------------------------
        // Initialize our cache object.  Indicate the location of the root cache directory, and how many cache levels are to exist.
        // For small caches (level 0) all cache files are in the root directory.
        // For medium caches (level 1) cache files are located in 256 sub-directories from the root.
        // For large caches (level 2) cache files are located in 256x256 sub-directories two levels down from the root.
        Cache gdCache = new Cache();
        gdCache.setLevel(0);
        // Use a root directory that makes sense on your operating system..
        gdCache.addRoot("C:/ckCache/googleDrive");

        // If we are re-building the cache, we can first delete the entire contents of the cache.
        int numCacheFilesDeleted = gdCache.deleteAll();

        // Create a date/time object with an time 7 days from the current date/time.
        DateTime dtExpire = new DateTime();
        dtExpire.setFromCurrentSystemTime();
        dtExpire.addDays(7);

        // Indicate that we want ALL possible fields.
        // If no fields are indicated, then only the basic fields are returned.
        String allFields = "appProperties,capabilities,contentHints,createdTime,description,explicitlyTrashed,fileExtension,folderColorRgb,fullFileExtension,headRevisionId,iconLink,id,imageMediaMetadata,isAppAuthorized,kind,lastModifyingUser,md5Checksum,mimeType,modifiedByMeTime,modifiedTime,name,originalFilename,ownedByMe,owners,parents,permissions,properties,quotaBytesUsed,shared,sharedWithMeTime,sharingUser,size,spaces,starred,thumbnailLink,trashed,version,videoMediaMetadata,viewedByMe,viewedByMeTime,viewersCanCopyContent,webContentLink,webViewLink,writersCanShare";

        // We're going to keep a master list of fileId's as we iterate over all the files in this Google Drive account.
        // This master list will also be saved to the cache under the key "AllGoogleDriveFileIds".
        JsonObject jsonMaster = new JsonObject();

        JsonArray jsonMasterArr = new JsonArray();
        jsonMaster.appendArray2("fileIds", jsonMasterArr);

        // Also keep a list of file paths.
        JsonArray jsonMasterPaths = new JsonArray();
        jsonMaster.appendArray2("filePaths", jsonMasterPaths);

        // The default page size is 100, with a max of 1000.
        rest.addQueryParam("pageSize", "200");

        JsonObject json = new JsonObject();
        JsonObject jsonFileMetadata = new JsonObject();
        int i = 0;
        int numFiles = 0;

        // Send the request for the 1st page.
        String jsonResponse = rest.fullRequestNoBody("GET", "/drive/v3/files");

        int pageNumber = 1;
        String pageToken = "";
        boolean bContinueLoop = rest.getLastMethodSuccess() && (rest.getResponseStatusCode() == 200);

        while (bContinueLoop) {
            System.out.println("---- Page " + pageNumber + " ----");
            json.load(jsonResponse);

            numFiles = json.sizeOfArray("files");
            i = 0;
            while (i < numFiles) {
                // Add this file ID to the master list.
                json.setI(i);
                jsonMasterArr.addStringAt(-1, json.stringOf("files[i].id"));

                i = i + 1;
            }

            // Get the next page of files.
            // If the "nextPageToken" is present in the JSON response, then use it in the "pageToken" parameter
            // for the next request.   If no "nextPageToken" was present, then this was the last page of files.
            pageToken = json.stringOf("nextPageToken");
            bContinueLoop = false;
            boolean bHasMorePages = json.getLastMethodSuccess();
            if (bHasMorePages) {
                rest.clearAllQueryParams();
                rest.addQueryParam("pageSize", "200");
                rest.addQueryParam("pageToken", pageToken);
                jsonResponse = rest.fullRequestNoBody("GET", "/drive/v3/files");
                bContinueLoop = rest.getLastMethodSuccess() && (rest.getResponseStatusCode() == 200);
                pageNumber = pageNumber + 1;
            }
        }

        // Check to see if the above loop exited with errors...
        if (!rest.getLastMethodSuccess()) {
            System.out.println(rest.getLastErrorText());
            return;
        }

        // Check to see if the above loop exited with errors...
        // A successful response will have a status code equal to 200.
        if (rest.getResponseStatusCode() != 200) {
            System.out.println("response status code = " + rest.getResponseStatusCode());
            System.out.println("response status text = " + rest.getResponseStatusText());
            System.out.println("response header: " + rest.getResponseHeader());
            System.out.println("response JSON: " + jsonResponse);
            return;
        }

        // Iterate over the file IDs and download the metadata for each, saving each to the cache...
        // Also, keep in-memory hash entries of the name and parent[0] so we can quickly
        // build the path-->fileId cache entries. (Given that the Google Drive REST API uses
        // fileIds, this gives us an easy way to lookup a fileId based on a filePath.)
        Hashtable hashTable = new Hashtable();
        // Set the capacity of the hash table to something reasonable for the number of files
        // to be hashed.
        hashTable.clearWithNewCapacity(521);

        StringBuilder sbPathForFileId = new StringBuilder();

        // Used for storing the file name and parents[0] in the hashTable.
        StringArray saFileInfo = new StringArray();
        saFileInfo.setUnique(false);

        String fileId = "";
        numFiles = jsonMaster.sizeOfArray("fileIds");
        i = 0;
        while (i < numFiles) {
            jsonMaster.setI(i);
            fileId = jsonMaster.stringOf("fileIds[i]");
            sbPathForFileId.setString("/drive/v3/files/");
            sbPathForFileId.append(fileId);

            rest.clearAllQueryParams();
            rest.addQueryParam("fields", allFields);
            jsonResponse = rest.fullRequestNoBody("GET", sbPathForFileId.getAsString());
            if ((!rest.getLastMethodSuccess()) || (rest.getResponseStatusCode() != 200)) {
                // Force an exit of this loop..
                numFiles = 0;
            }

            // Save this file's metadata to the local cache.
            // The lookup key is the fileId.
            gdCache.saveTextDt(fileId, dtExpire, "", jsonResponse);

            // Get this file's name and parent[0], and put this information
            // in our in-memory hashtable to be used below..
            json.load(jsonResponse);

            saFileInfo.clear();
            saFileInfo.append(json.stringOf("name"));
            saFileInfo.append(json.stringOf("parents[0]"));
            hashTable.addStr(fileId, saFileInfo.serialize());

            System.out.println(json.stringOf("name") + ", " + json.stringOf("parents[0]"));

            i = i + 1;
        }

        // Check to see if the above loop exited with errors...
        if (!rest.getLastMethodSuccess()) {
            System.out.println(rest.getLastErrorText());
            return;
        }

        // Check to see if the above loop exited with errors...
        // A successful response will have a status code equal to 200.
        if (rest.getResponseStatusCode() != 200) {
            System.out.println("response status code = " + rest.getResponseStatusCode());
            System.out.println("response status text = " + rest.getResponseStatusText());
            System.out.println("response header: " + rest.getResponseHeader());
            System.out.println("response JSON: " + jsonResponse);
            return;
        }

        // Now that all the fileId's are in the cache, let's build the directory path
        // for each fileID.

        // (Technically, a fileId can have multiple parents, which means it can be in multiple directories
        // at once.  This is only going to build directory paths following the 0'th parent ID in the parents list.)

        // The directory path for files in "My Drive" will be just the filename.
        // For files in sub-directories, the path will be relative, such as "subdir1/subdir2/something.pdf"
        //

        System.out.println("---- building paths ----");

        StringBuilder sbPath = new StringBuilder();
        numFiles = jsonMaster.sizeOfArray("fileIds");
        i = 0;
        while (i < numFiles) {
            jsonMaster.setI(i);

            sbPath.clear();

            fileId = jsonMaster.stringOf("fileIds[i]");
            boolean bFinished = false;
            while (!bFinished) {
                saFileInfo.clear();
                saFileInfo.appendSerialized(hashTable.lookupStr(fileId));
                // Append this file or directory name.
                sbPath.prepend(saFileInfo.getString(0));
                // Get the parent fileId
                fileId = saFileInfo.getString(1);
                // If this fileId is not in the hashtable, then it's the fileId for "My Drive", and we are finished.
                if (!hashTable.contains(fileId)) {
                    bFinished = true;
                } else {
                    sbPath.prepend("/");
                }
            }

            System.out.println(i + ": " + sbPath.getAsString());

            // Store the filePath --> fileId mapping in our local cache.
            fileId = jsonMaster.stringOf("fileIds[i]");
            gdCache.saveTextDt(sbPath.getAsString(), dtExpire, "", fileId);

            jsonMasterPaths.addStringAt(-1, sbPath.getAsString());

            i = i + 1;
        }

        // Save the master list of file IDs and file paths to the local cache.
        jsonMaster.setEmitCompact(false);
        String strJsonMaster = jsonMaster.emit();
        gdCache.saveTextNoExpire("AllGoogleDriveFileIds", "", strJsonMaster);
        System.out.println("JSON Master Record:");
        System.out.println(strJsonMaster);

        // The JSON Master Cache Record looks something like this:
        // An application can load the JSON master record and iterate over all the files
        // in Google Drive by file ID, or by path.
        // {
        //   "fileIds": [
        //     "0B53Q6OSTWYolQlExSlBQT1phZXM",
        //     "0B53Q6OSTWYolVHRPVkxtYWFtZkk",
        //     "0B53Q6OSTWYolRGZEV3ZGUTZfNFk",
        //     "0B53Q6OSTWYolS2FXSjliMXQxSU0",
        //     "0B53Q6OSTWYolZUhxckMzb0dRMzg",
        //     "0B53Q6OSTWYolbUF6WS1Gei1oalk",
        //     "0B53Q6OSTWYola296ODZUSm5GYU0",
        //     "0B53Q6OSTWYolbTE3c3J5RHBUcHM",
        //     "0B53Q6OSTWYolTmhybWJSUGd5Q2c",
        //     "0B53Q6OSTWYolY2tPU1BnYW02T2c",
        //     "0B53Q6OSTWYolTTBBR2NvUE81Zzg",
        //   ],
        //   "filePaths": [
        //     "testFolder/abc/123/pigs.json",
        //     "testFolder/starfish20.jpg",
        //     "testFolder/penguins2.jpg",
        //     "testFolder/starfish.jpg",
        //     "testFolder/abc/123/starfish.jpg",
        //     "testFolder/abc/123/penguins.jpg",
        //     "testFolder/abc/123",
        //     "testFolder/abc",
        //     "testFolder/testHello.txt",
        //     "testFolder",
        //     "helloWorld.txt",
        //   ]
        // }

        System.out.println("Entire cache rebuilt...");
    }
}