Skip to content

Latest commit

 

History

History
801 lines (620 loc) · 31.7 KB

folders.md

File metadata and controls

801 lines (620 loc) · 31.7 KB

Folders

Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.).

Get the User's Root Folder

The user's root folder can be accessed with the static getRootFolder(BoxAPIConnection api) method.

BoxFolder rootFolder = BoxFolder.getRootFolder(api);

Get a Folder's Items

Every BoxFolder implements Iterable<BoxItem> which allows you to iterate over the folder's contents. The iterator automatically handles paging and will make additional API calls to load more data when necessary.

BoxFolder folder = new BoxFolder(api, "id");
for (BoxItem.Info itemInfo : folder) {
    if (itemInfo instanceof BoxFile.Info) {
        BoxFile.Info fileInfo = (BoxFile.Info) itemInfo;
        // Do something with the file.
    } else if (itemInfo instanceof BoxFolder.Info) {
        BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo;
        // Do something with the folder.
    }
}

BoxFolder purposely doesn't provide a way of getting a collection of BoxItems. Getting the entire contents of a folder is usually unnecessary and can be extremely inefficient for folders with a large number of items. If you really require a collection instead of an iterable, you can create the collection manually.

Collection<BoxItem> folderItems = new ArrayList<BoxItem>();
BoxFolder folder = new BoxFolder(api, "id");
for (BoxItem.Info itemInfo : folder) {
    folderItems.add(itemInfo.getResource());
}

We also allow users to sort the results of the folder items by name, id, or date. This will maintain the integrity of the ordering when you retrieve the items for a folder. You can do this by calling the getChildren(String sortField, BoxFolder.SortDirection sortDirection, String... fields) method.

BoxFolder folder = new BoxFolder(this.api, "12345");
Iterator<BoxItem.Info> itemIterator = folder.getChildren("name", BoxFolder.SortDirection.ASC).iterator();
while (itemIterator.hasNext()) {
    BoxItem.Info itemInfo = itemIterator.next();
    // Do something
}

SortParameters and Using PagingParameters

SortParameters is an abstraction hiding way that SDK is doing sorting. PagingParameters is an abstraction hiding way that SDK is doing pagination. If you want to start offset based pagination:

BoxFolder folder = new BoxFolder(this.api, "12345");
// setup ascending sorting by name
SortParameters sorting = SortParameters.ascending("name");
// setup paging with offset 0 and limit 100
long offset = 0;
long limit = 100;
PagingParameters paging = PagingParameters.offset(offset, limit)
Iterable<BoxItem.Info> itemIterator = childFolder.getChildren(sorting, paging);
while (itemIterator.hasNext()) {
    BoxItem.Info itemInfo=itemIterator.next();
    // Do something
}

With offset pagination you cannot set offset larger than 300000. With marker based pagination you can iterate over folders containing more than 300000 elements. With marker based pagination you cannot use sorting. Use SortParameters.none() to turn off sort. If you want to use PagingParameters to start marker based pagination do:

BoxFolder folder = new BoxFolder(this.api, "12345");
// disable sorting
SortParameters sorting = SortParameters.none();
// setup paging with makred based pagination and limit 100
long limit = 100;
PagingParameters paging = PagingParameters.marker(limit)
Iterable<BoxItem.Info> itemIterator = childFolder.getChildren(sorting, paging);
while (itemIterator.hasNext()) {
    BoxItem.Info itemInfo=itemIterator.next();
    // Do something
}

Get a Folder's Information

Calling getInfo() on a folder returns a snapshot of the folder's info.

BoxFolder folder = new BoxFolder(api, "id");
BoxFolder.Info info = folder.getInfo();

Requesting information for only the fields you need can improve performance and reduce the size of the network request. The getInfo(String... fields) method lets you specify which fields are retrieved.

BoxFolder folder = new BoxFolder(api, "id");
// Only get information about a few specific fields.
BoxFolder.Info info = folder.getInfo("size", "owned_by");

Update a Folder's Information

Updating a folder's information is done by creating a new BoxFolder.Info object or updating an existing one, and then calling updateInfo(BoxFolder.Info fieldsToUpdate).

BoxFolder folder = new BoxFolder(api, "id");
BoxFolder.Info info = folder.new Info();
info.setName("New Name");
folder.updateInfo(info);

Create a Folder

Create a child folder by calling createFolder(String folderName) on the parent folder.

BoxFolder parentFolder = new BoxFolder(api, "id");
BoxFolder.Info childFolderInfo = parentFolder.createFolder("Child Folder Name");

Copy a Folder

Call the copy(BoxFolder destination) method to copy a folder to another folder.

BoxFolder folder = new BoxFolder(api, "id1");
BoxFolder destination = new BoxFolder(api, "id2");
folder.copy(destination);

You can also use the copy(BoxFolder destination, String newName) method to rename the folder while copying it. This allows you to make a copy of the folder in the same parent folder, but with a different name.

BoxFolder folder = new BoxFolder(api, "id1");
BoxFolder.Info parentFolderInfo = folder.getInfo().getParent();
BoxFolder parentFolder = parentFolderInfo.getResource();
folder.copy(parentFolder, "New Name");

Move a Folder

Call the move(BoxFolder destination) method with the destination you want the folder moved to.

BoxFolder folder = new BoxFolder(api, "id1");
BoxFolder destination = new BoxFolder(api, "id2");
folder.move(destination);

Rename a Folder

Call the rename(String newName) method with a new name for the folder.

BoxFolder folder = new BoxFolder(api, "id");
folder.rename("New Name");

A folder can also be renamed by updating the folder's information. This is useful if you want to perform more than one change to the folder in a single API request.

BoxFolder folder = new BoxFolder(api, "id");
BoxFolder.Info info = folder.new Info();
info.setName("New Name");
folder.updateInfo(info);

Delete a Folder

A folder can be deleted with the delete(boolean recursive) method. Passing true to this method indicates that the folder and its contents should be recursively deleted.

// Delete the folder and all its contents
BoxFolder folder = new BoxFolder(api, "id");
folder.delete(true);

Find Folder for Shared Link

To get the folder information for a shared link, you can call BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink) with the shared link to get information about the folder behind it.

String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456";
BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink);

If the shared link is password-protected, call BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password) with the shared link and password.

String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456";
String password = "letmein";
BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password);

Create a Shared Link

A shared link for a folder can be generated by calling createSharedLink(BoxSharedLinkRequest sharedLinkRequest).

// Optionally we can calculate and set the date when shared link will automatically be disabled
final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7;
long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS;
Date unsharedDate = new Date(unsharedTimestamp);

BoxFolder folder = new BoxFolder(api, "id");
BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest()
        .access(OPEN)
        .permissions(true, true)
        .unsharedDate(unsharedDate);
BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest);

A set of shared link access level constants are available through the SDK for convenience:

  • BoxSharedLink.Access.OPEN
  • BoxSharedLink.Access.COLLABORATORS
  • BoxSharedLink.Access.COMPANY
  • BoxSharedLink.Access.DEFAULT

Get a Shared Link

Retrieve the shared link for a folder by calling getSharedLink().

BoxFolder folder = new BoxFolder(api, "id");
BoxFolder.Info info = folder.getInfo()
BoxSharedLink link = info.getSharedLink()
String url = link.getUrl()

Update a Shared Link

A shared link for a folder can be updated by calling the same method as used when creating a shared link, createSharedLink(BoxSharedLinkRequest sharedLinkRequest).

BoxFolder folder = new BoxFolder(api, "id");
BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest()
    .access(OPEN)
    .permissions(true, true);

BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest);

Remove a Shared Link

A shared link for a folder can be removed by calling removeSharedLink().

BoxFolder folder = new BoxFolder(api, "12345");
BoxFolder.Info info = folder.getInfo();
info.removeSharedLink();
folder.updateInfo(info);

Share a Folder

You can invite another person to collaborate on a folder with the collaborate(String emailAddress, BoxCollaboration.Role role) method.

BoxFolder folder = new BoxFolder(api, "id");
BoxCollaboration.Info collabInfo = folder.collaborate("[email protected]",
    BoxCollaboration.Role.EDITOR);

If you already know the user's ID, you can invite them directly without needing to know their email address with the collaborate(BoxCollaborator user, BoxCollaboration.Role role) method.

BoxUser collaborator = new User(api, "user-id");
BoxFolder folder = new BoxFolder(api, "folder-id");
BoxCollaboration.Info collabInfo = folder.collaborate(collaborator,
    BoxCollaboration.Role.EDITOR);

You can also create a collaboration with all properties set at once by using the collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly) method.

The notify parameter will determine if the user or group will receive an email notification when being added as a collaborator. This option is only available to enterprise administrators.

The canViewPath parameter allows the invitee to see the entire list of ancestor folders of the associated file. The user will not gain privileges in any ancestor folder, but will be able to see the whole path to that file in the owner's account.

The expiresAt parameter allows the owner to set a date-time in the future when the collaboration should expire.

The isAccessOnly parameter allows the owner to set the collaboration to be access only collaboration.

The notify, canViewPath, expiresAt and isAccessOnly parameters can be left as null.

Get All Collaborations for a Folder

The getCollaborations() method will return a collection of BoxCollaboration.Info objects for a folder.

BoxFolder folder = new BoxFolder(api, "id");
Collection<BoxCollaboration.Info> collaborations = folder.getCollaborations();

Create Metadata

Metadata can be created on a folder by calling createMetadata(Metadata metadata), createMetadata(String templateName, Metadata metadata), or createMetadata(String templateName, String scope, Metadata metadata)

BoxFolder folder = new BoxFolder(api, "id");
folder.createMetadata(new Metadata().add("/foo", "bar"));

Note: This method will only succeed if the provided metadata template is not currently applied to the folder, otherwise it will fail with a Conflict error. To get to know how to edit existing metadata please go to set metadata and update metadata sections.

Set Metadata

To set metadata on a folder, call setMetadata(String templateName, String scope, Metadata metadata). This method will try to create provided metadata on a folder. However, if metadata has already been applied to this folder, it will overwrite values of metadata keys specified in the metadata parameter. The metadata keys not specified in the metadata parameter will remain unchanged.

BoxFolder folder = new BoxFolder(api, "id");
folder.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar"));

Note: If you want to set new metadata on a folder including hard reset of the current metadata (also removing keys not specified in the metadata param): first delete metadata as specified in delete metadata section and then set new metadata again.

Get Metadata

Retrieve a folder's metadata by calling getMetadata(), getMetadata(String templateName), or getMetadata(String templateName, String scope). These methods return a Metadata object, which allows access to metadata values.

BoxFolder folder = new BoxFolder(api, "id");
Metadata metadata = folder.getMetadata();

// Unknown type metadata field, you can test for type or try to get as any type
JsonValue unknownValue = metadata.getValue("/someField");

// String or Enum metadata fields
String stringValue = metadata.getString("/author");

// Float metadata fields can be interpreted as any numeric type
float floatValue = metadata.getFloat("/price");

// Date metadata fields
Date dateValue = metadata.getDate("/deadline");

Update Metadata

Update a folder's metadata by calling updateMetadata(Metadata properties).

Note: This method will only succeed if the provided metadata template has already been applied to the folder. If the folder does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the folder will already have metadata applied, since it will save an API call compared to setMetadata().

BoxFolder folder = new BoxFolder(api, "id");
folder.updateMetadata(new Metadata().add("/foo", "bar"));

Also, it is possible to add multi-select fields for your folder metadata by calling updateMetadata(Metadata properties) with a list of values.

BoxFolder folder = new BoxFolder(api, "id");
List<String> valueList = new ArrayList<String>();
valueList.add("bar");
valueList.add("qux");
folder.updateMetadata(new Metadata().add("/foo", valueList));

If you wanted to replace all selected fields for a specified key you can use the replace(String key, List<String> values).

BoxFolder folder = new BoxFolder(api, "id");
List<String> valueList = new ArrayList<String>();
valueList.add("bar");
valueList.add("qux");
folder.updateMetadata(new Metadata().replace("/foo", valueList));

Delete Metadata

A folder's metadata can be deleted by calling deleteMetadata(), deleteMetadata(String templateName), or deleteMetadata(String templateName, String scope).

BoxFolder folder = new BoxFolder(api, "id");
folder.deleteMetadata("myMetadataTemplate");

Get All Metadata on Folder

getAllMetadata() method will return an iterable that will page through all of the metadata associated with the folder.

BoxFolder file = new BoxFolder(api, "id");
Iterable<Metadata> metadataList = folder.getAllMetadata();
for (Metadata metadata : metadataList) {
    // Do something with the metadata.
}

Get Metadata for Multiple Files

When fetching a large number of items, for example the items in a folder, it would often be impractical to fetch the metadata for each of those items individually. Instead, you can get the metadata for all of the items in a single API call by requesting the metadata field on those items:

Note: The field name should have the form metadata.<templateScope>.<templateKey>

BoxFolder root = BoxFolder.getRootFolder();
Iterable<BoxItem.Info> itemsInFolder = root.getChildren("metadata.global.properties")
for (BoxItem.Info itemInfo : itemsInFolder) {
    if (itemInfo instanceof BoxFile.Info) {
        BoxFile.Info fileInfo = (BoxFile.Info) itemInfo;
        Metadata itemMetadata = fileInfo.getMetadata("properties", "global");
    } else if (itemInfo instanceof BoxFolder.Info) {
        BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo;
        Metadata itemMetadata = folderInfo.getMetadata("properties", "global");
    }
}

Set Classification on Folder

Calling the setClassification(String classificationType) method on a folder will add a classification template on the folder. This method will return the classification type applied on the folder. The classification types include Public, Internal, and Confidential. Public being the most available permission, Internal which restricts the specified file to company and collaborators only, and finally, Confidential, which is for collaborators only.

BoxFolder folder = new BoxFolder(api, "id");
String classificationType = folder.setClassification("Public");

It is important to note that this call will attempt to create a classification on the folder first, if one already exists then it will do the update. If you already know that a classification exists on the folder and would like to save an API call, we encourage you to use the updateClassification(String classificationType) method.

BoxFolder folder = new BoxFolder(api, "id");
String classificationType = folder.updateClassification("Public");

Get Classification on Folder

To retrieve the classification assigned on the folder, use the getClassification() method. This will return the classification type on the folder.

BoxFolder folder = new BoxFolder(api, "id");
String classificationType = folder.getClassification();

Remove Classification on Folder

To remove classification from the folder, use the deleteClassification() method.

BoxFolder folder = new BoxFolder(api, "id");
folder.deleteClassification();

Create Cascade Policy On Folder

To set a metadata policy, which applies metadata values on a folder to new items in the folder, call BoxFolder.addMetadataCascadePolicy(String scope, String template).

String scope = "global";
String templateKey = "template";
String folderId = "12345";
BoxFolder folder = new BoxFolder(api, folderId);
BoxMetadataCascadePolicy.Info cascadePolicyInfo = folder.addMetadataCascadePolicy(scope, template);

Get a Cascade Policy's Information

To retrieve information about a specific metadata cascade policy, call getInfo()

String cascadePolicyID = "1234";
BoxMetadataCascadePolicy metadataCascadePolicy = new BoxMetadataCascadePolicy(api, cascadePolicyID);
BoxMetadataCascadePolicy.Info metadataCascadePolicyInfo = metadataCascadePolicy.getInfo();

Get All Cascade Policies on Folder

To get a list of all cascade policies on a folder, which show the metadata templates that are being applied to all items in the folder, call getMetadataCascadePolicies() on that folder.

String folderID = "2222";
BoxFolder folder = new BoxFolder(api, folderID);
Iterable<BoxMetadataCascadePolicy.Info> metadataCascadePolicies = folder.getMetadataCascadePolicies();
for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) {
    // take action on policy here
}

You can also call getMetadataCascadePolicies(String enterpriseID, int limit, String... fields) and set the enterpriseID option to retrieve metadata cascade policies from another enterprise.

String folderID = "2222";
String enterpriseID = "3333";
int limit = 50;
BoxFolder folder = new BoxFolder(api, folderID);
Iterable<BoxMetadataCascadePolicy.Info> metadataCascadePolicies = folder.getMetadataCascadePolicies(enterpriseID, limit);
for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) {
    // take action on policy here
}

Force Apply Cascade Policy on Folder

To force apply a metadata template policy and apply metadata values to all existing items in an affected folder, call forceApply(String conflictResolution) with the conflict resolution method for dealing with items that already have a metadata value that conflicts with the folder. Specifying a resolution value of none will preserve the existing values on items, and specifying overwrite will overwrite values on items in the folder with the metadata value from the folder.

String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067";
BoxMetadataCascadePolicy policy = new BoxMetadataCascadePolicy(api, cascadePolicyID);
policy.forceApply("none");

Delete Cascade Policy

To remove a cascade policy and stop applying metadata from a folder to items in the folder, call delete().

String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067";
BoxMetadataCascadePolicy policyToDelete = new BoxMetadataCascadePolicy(api, cascadePolicyID);
policyToDelete.delete();

Lock a Folder

To lock a folder and prevent it from being moved and/or deleted, call lock() on a folder.

BoxFolder folder = new BoxFolder(api, "id");
FolderLock.Info folderLock = folder.lock();

Get All Locks on a Folder

To get all locks on a folder, call getlock() on folder.

BoxFolder folder = new BoxFolder(this.api, "id");
Iterable<BoxFolderLock.Info> locks = folder.getLocks();
for (BoxFolderLock.Info lockInfo : locks) {
    // Do something with each lockInfo here
}

Delete a Lock on a Folder

To delete a lock on a folder, call delete() on a BoxFolderLock object. This cannot be called on a BoxFolder object.

BoxFolderLock folderLock = new BoxFolderLock(this.api, "folderLockID");
folderLock.delete();