001package com.box.sdk;
002
003import java.io.IOException;
004import java.io.InputStream;
005import java.net.URL;
006import java.util.ArrayList;
007import java.util.Collection;
008import java.util.Date;
009import java.util.EnumSet;
010import java.util.Iterator;
011import java.util.List;
012import java.util.Map;
013import java.util.concurrent.TimeUnit;
014
015import com.box.sdk.internal.utils.Parsers;
016import com.eclipsesource.json.JsonArray;
017import com.eclipsesource.json.JsonObject;
018import com.eclipsesource.json.JsonValue;
019/**
020 * Represents a folder on Box. This class can be used to iterate through a folder's contents, collaborate a folder with
021 * another user or group, and perform other common folder operations (move, copy, delete, etc.).
022 * <p>
023 * <p>Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked
024 * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error
025 * handling for errors related to the Box REST API, you should capture this exception explicitly.</p>
026 */
027@BoxResourceType("folder")
028public class BoxFolder extends BoxItem implements Iterable<BoxItem.Info> {
029    /**
030     * An array of all possible folder fields that can be requested when calling {@link #getInfo()}.
031     */
032    public static final String[] ALL_FIELDS = {"type", "id", "sequence_id", "etag", "name", "created_at", "modified_at",
033        "description", "size", "path_collection", "created_by", "modified_by", "trashed_at", "purged_at",
034        "content_created_at", "content_modified_at", "owned_by", "shared_link", "folder_upload_email", "parent",
035        "item_status", "item_collection", "sync_state", "has_collaborations", "permissions", "tags",
036        "can_non_owners_invite", "collections", "watermark_info", "metadata", "is_externally_owned",
037        "is_collaboration_restricted_to_enterprise", "allowed_shared_link_access_levels", "allowed_invitee_roles"};
038
039    /**
040     * Used to specify what direction to sort and display results.
041     */
042    public enum SortDirection {
043        /**
044         * ASC for ascending order.
045         */
046        ASC,
047
048        /**
049         * DESC for descending order.
050         */
051        DESC
052    }
053
054    /**
055     * Create Folder URL Template.
056     */
057    public static final URLTemplate CREATE_FOLDER_URL = new URLTemplate("folders");
058    /**
059     * Create Web Link URL Template.
060     */
061    public static final URLTemplate CREATE_WEB_LINK_URL = new URLTemplate("web_links");
062    /**
063     * Copy Folder URL Template.
064     */
065    public static final URLTemplate COPY_FOLDER_URL = new URLTemplate("folders/%s/copy");
066    /**
067     * Delete Folder URL Template.
068     */
069    public static final URLTemplate DELETE_FOLDER_URL = new URLTemplate("folders/%s?recursive=%b");
070    /**
071     * Folder Info URL Template.
072     */
073    public static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s");
074    /**
075     * Upload File URL Template.
076     */
077    public static final URLTemplate UPLOAD_FILE_URL = new URLTemplate("files/content");
078    /**
079     * Add Collaboration URL Template.
080     */
081    public static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations");
082    /**
083     * Get Collaborations URL Template.
084     */
085    public static final URLTemplate GET_COLLABORATIONS_URL = new URLTemplate("folders/%s/collaborations");
086    /**
087     * Get Items URL Template.
088     */
089    public static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/%s/items/");
090    /**
091     * Search URL Template.
092     */
093    public static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search");
094    /**
095     * Metadata URL Template.
096     */
097    public static final URLTemplate METADATA_URL_TEMPLATE = new URLTemplate("folders/%s/metadata/%s/%s");
098    /**
099     * Upload Session URL Template.
100     */
101    public static final URLTemplate UPLOAD_SESSION_URL_TEMPLATE = new URLTemplate("files/upload_sessions");
102
103    /**
104     * Constructs a BoxFolder for a folder with a given ID.
105     *
106     * @param api the API connection to be used by the folder.
107     * @param id  the ID of the folder.
108     */
109    public BoxFolder(BoxAPIConnection api, String id) {
110        super(api, id);
111    }
112
113    /**
114     * {@inheritDoc}
115     */
116    @Override
117    protected URL getItemURL() {
118        return FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
119    }
120
121    /**
122     * Gets the current user's root folder.
123     *
124     * @param api the API connection to be used by the folder.
125     * @return the user's root folder.
126     */
127    public static BoxFolder getRootFolder(BoxAPIConnection api) {
128        return new BoxFolder(api, "0");
129    }
130
131    /**
132     * Adds a collaborator to this folder.
133     *
134     * @param collaborator the collaborator to add.
135     * @param role         the role of the collaborator.
136     * @return info about the new collaboration.
137     */
138    public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role) {
139        JsonObject accessibleByField = new JsonObject();
140        accessibleByField.add("id", collaborator.getID());
141
142        if (collaborator instanceof BoxUser) {
143            accessibleByField.add("type", "user");
144        } else if (collaborator instanceof BoxGroup) {
145            accessibleByField.add("type", "group");
146        } else {
147            throw new IllegalArgumentException("The given collaborator is of an unknown type.");
148        }
149
150        return this.collaborate(accessibleByField, role, null, null);
151    }
152
153    /**
154     * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box
155     * account.
156     *
157     * @param email the email address of the collaborator to add.
158     * @param role  the role of the collaborator.
159     * @return info about the new collaboration.
160     */
161    public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role) {
162        JsonObject accessibleByField = new JsonObject();
163        accessibleByField.add("login", email);
164        accessibleByField.add("type", "user");
165
166        return this.collaborate(accessibleByField, role, null, null);
167    }
168
169    /**
170     * Adds a collaborator to this folder.
171     *
172     * @param collaborator the collaborator to add.
173     * @param role         the role of the collaborator.
174     * @param notify       the user/group should receive email notification of the collaboration or not.
175     * @param canViewPath  the view path collaboration feature is enabled or not.
176     *                     View path collaborations allow the invitee to see the entire ancestral path to the associated
177     *                     folder. The user will not gain privileges in any ancestral folder.
178     * @return info about the new collaboration.
179     */
180    public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role,
181                                             Boolean notify, Boolean canViewPath) {
182        JsonObject accessibleByField = new JsonObject();
183        accessibleByField.add("id", collaborator.getID());
184
185        if (collaborator instanceof BoxUser) {
186            accessibleByField.add("type", "user");
187        } else if (collaborator instanceof BoxGroup) {
188            accessibleByField.add("type", "group");
189        } else {
190            throw new IllegalArgumentException("The given collaborator is of an unknown type.");
191        }
192
193        return this.collaborate(accessibleByField, role, notify, canViewPath);
194    }
195
196    /**
197     * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box
198     * account.
199     *
200     * @param email       the email address of the collaborator to add.
201     * @param role        the role of the collaborator.
202     * @param notify      the user/group should receive email notification of the collaboration or not.
203     * @param canViewPath the view path collaboration feature is enabled or not.
204     *                    View path collaborations allow the invitee to see the entire ancestral path to the associated
205     *                    folder. The user will not gain privileges in any ancestral folder.
206     * @return info about the new collaboration.
207     */
208    public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role,
209                                             Boolean notify, Boolean canViewPath) {
210        JsonObject accessibleByField = new JsonObject();
211        accessibleByField.add("login", email);
212        accessibleByField.add("type", "user");
213
214        return this.collaborate(accessibleByField, role, notify, canViewPath);
215    }
216
217    private BoxCollaboration.Info collaborate(JsonObject accessibleByField, BoxCollaboration.Role role,
218                                              Boolean notify, Boolean canViewPath) {
219
220        JsonObject itemField = new JsonObject();
221        itemField.add("id", this.getID());
222        itemField.add("type", "folder");
223
224        return BoxCollaboration.create(this.getAPI(), accessibleByField, itemField, role, notify, canViewPath);
225    }
226
227    @Override
228    public BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate,
229                                          BoxSharedLink.Permissions permissions) {
230
231        BoxSharedLink sharedLink = new BoxSharedLink(access, unshareDate, permissions);
232        Info info = new Info();
233        info.setSharedLink(sharedLink);
234
235        this.updateInfo(info);
236        return info.getSharedLink();
237    }
238
239    /**
240     * Creates new SharedLink for a BoxFolder with a password.
241     *
242     * @param access        The access level of the shared link.
243     * @param unshareDate   A specified date to unshare the Box folder.
244     * @param permissions   The permissions to set on the shared link for the Box folder.
245     * @param password      Password set on the shared link to give access to the Box folder.
246     * @return information about the newly created shared link.
247     */
248    public BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate,
249                                          BoxSharedLink.Permissions permissions, String password) {
250
251        BoxSharedLink sharedLink = new BoxSharedLink(access, unshareDate, permissions, password);
252        Info info = new Info();
253        info.setSharedLink(sharedLink);
254
255        this.updateInfo(info);
256        return info.getSharedLink();
257    }
258
259    /**
260     * Gets information about all of the collaborations for this folder.
261     *
262     * @return a collection of information about the collaborations for this folder.
263     */
264    public Collection<BoxCollaboration.Info> getCollaborations() {
265        BoxAPIConnection api = this.getAPI();
266        URL url = GET_COLLABORATIONS_URL.build(api.getBaseURL(), this.getID());
267
268        BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
269        BoxJSONResponse response = (BoxJSONResponse) request.send();
270        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
271
272        int entriesCount = responseJSON.get("total_count").asInt();
273        Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);
274        JsonArray entries = responseJSON.get("entries").asArray();
275        for (JsonValue entry : entries) {
276            JsonObject entryObject = entry.asObject();
277            BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString());
278            BoxCollaboration.Info info = collaboration.new Info(entryObject);
279            collaborations.add(info);
280        }
281
282        return collaborations;
283    }
284
285    @Override
286    public BoxFolder.Info getInfo() {
287        URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
288        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
289        BoxJSONResponse response = (BoxJSONResponse) request.send();
290        return new Info(response.getJSON());
291    }
292
293    @Override
294    public BoxFolder.Info getInfo(String... fields) {
295        String queryString = new QueryStringBuilder().appendParam("fields", fields).toString();
296        URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
297
298        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
299        BoxJSONResponse response = (BoxJSONResponse) request.send();
300        return new Info(response.getJSON());
301    }
302
303    /**
304     * Updates the information about this folder with any info fields that have been modified locally.
305     *
306     * @param info the updated info.
307     */
308    public void updateInfo(BoxFolder.Info info) {
309        URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
310        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
311        request.setBody(info.getPendingChanges());
312        BoxJSONResponse response = (BoxJSONResponse) request.send();
313        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
314        info.update(jsonObject);
315    }
316
317    @Override
318    public BoxFolder.Info copy(BoxFolder destination) {
319        return this.copy(destination, null);
320    }
321
322    @Override
323    public BoxFolder.Info copy(BoxFolder destination, String newName) {
324        URL url = COPY_FOLDER_URL.build(this.getAPI().getBaseURL(), this.getID());
325        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
326
327        JsonObject parent = new JsonObject();
328        parent.add("id", destination.getID());
329
330        JsonObject copyInfo = new JsonObject();
331        copyInfo.add("parent", parent);
332        if (newName != null) {
333            copyInfo.add("name", newName);
334        }
335
336        request.setBody(copyInfo.toString());
337        BoxJSONResponse response = (BoxJSONResponse) request.send();
338        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
339        BoxFolder copiedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
340        return copiedFolder.new Info(responseJSON);
341    }
342
343    /**
344     * Creates a new child folder inside this folder.
345     *
346     * @param name the new folder's name.
347     * @return the created folder's info.
348     */
349    public BoxFolder.Info createFolder(String name) {
350        JsonObject parent = new JsonObject();
351        parent.add("id", this.getID());
352
353        JsonObject newFolder = new JsonObject();
354        newFolder.add("name", name);
355        newFolder.add("parent", parent);
356
357        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),
358                "POST");
359        request.setBody(newFolder.toString());
360        BoxJSONResponse response = (BoxJSONResponse) request.send();
361        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
362
363        BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
364        return createdFolder.new Info(responseJSON);
365    }
366
367    /**
368     * Deletes this folder, optionally recursively deleting all of its contents.
369     *
370     * @param recursive true to recursively delete this folder's contents; otherwise false.
371     */
372    public void delete(boolean recursive) {
373        URL url = DELETE_FOLDER_URL.build(this.getAPI().getBaseURL(), this.getID(), recursive);
374        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
375        BoxAPIResponse response = request.send();
376        response.disconnect();
377    }
378
379    @Override
380    public BoxItem.Info move(BoxFolder destination) {
381        return this.move(destination, null);
382    }
383
384    @Override
385    public BoxItem.Info move(BoxFolder destination, String newName) {
386        URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
387        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
388
389        JsonObject parent = new JsonObject();
390        parent.add("id", destination.getID());
391
392        JsonObject updateInfo = new JsonObject();
393        updateInfo.add("parent", parent);
394        if (newName != null) {
395            updateInfo.add("name", newName);
396        }
397
398        request.setBody(updateInfo.toString());
399        BoxJSONResponse response = (BoxJSONResponse) request.send();
400        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
401        BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
402        return movedFolder.new Info(responseJSON);
403    }
404
405    /**
406     * Renames this folder.
407     *
408     * @param newName the new name of the folder.
409     */
410    public void rename(String newName) {
411        URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
412        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
413
414        JsonObject updateInfo = new JsonObject();
415        updateInfo.add("name", newName);
416
417        request.setBody(updateInfo.toString());
418        BoxJSONResponse response = (BoxJSONResponse) request.send();
419        response.getJSON();
420    }
421
422    /**
423     * Checks if the file can be successfully uploaded by using the preflight check.
424     *
425     * @param name     the name to give the uploaded file.
426     * @param fileSize the size of the file used for account capacity calculations.
427     */
428    public void canUpload(String name, long fileSize) {
429        URL url = UPLOAD_FILE_URL.build(this.getAPI().getBaseURL());
430        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS");
431
432        JsonObject parent = new JsonObject();
433        parent.add("id", this.getID());
434
435        JsonObject preflightInfo = new JsonObject();
436        preflightInfo.add("parent", parent);
437        preflightInfo.add("name", name);
438
439        preflightInfo.add("size", fileSize);
440
441        request.setBody(preflightInfo.toString());
442        BoxAPIResponse response = request.send();
443        response.disconnect();
444    }
445
446    /**
447     * Uploads a new file to this folder.
448     *
449     * @param fileContent a stream containing the contents of the file to upload.
450     * @param name        the name to give the uploaded file.
451     * @return the uploaded file's info.
452     */
453    public BoxFile.Info uploadFile(InputStream fileContent, String name) {
454        FileUploadParams uploadInfo = new FileUploadParams()
455                .setContent(fileContent)
456                .setName(name);
457        return this.uploadFile(uploadInfo);
458    }
459
460    /**
461     * Uploads a new file to this folder.
462     *
463     * @param callback the callback which allows file content to be written on output stream.
464     * @param name     the name to give the uploaded file.
465     * @return the uploaded file's info.
466     */
467    public BoxFile.Info uploadFile(UploadFileCallback callback, String name) {
468        FileUploadParams uploadInfo = new FileUploadParams()
469                .setUploadFileCallback(callback)
470                .setName(name);
471        return this.uploadFile(uploadInfo);
472    }
473
474    /**
475     * Uploads a new file to this folder while reporting the progress to a ProgressListener.
476     *
477     * @param fileContent a stream containing the contents of the file to upload.
478     * @param name        the name to give the uploaded file.
479     * @param fileSize    the size of the file used for determining the progress of the upload.
480     * @param listener    a listener for monitoring the upload's progress.
481     * @return the uploaded file's info.
482     */
483    public BoxFile.Info uploadFile(InputStream fileContent, String name, long fileSize, ProgressListener listener) {
484        FileUploadParams uploadInfo = new FileUploadParams()
485                .setContent(fileContent)
486                .setName(name)
487                .setSize(fileSize)
488                .setProgressListener(listener);
489        return this.uploadFile(uploadInfo);
490    }
491
492    /**
493     * Uploads a new file to this folder with a specified file description.
494     *
495     * @param fileContent a stream containing the contents of the file to upload.
496     * @param name        the name to give the uploaded file.
497     * @param description the description to give the uploaded file.
498     * @return the uploaded file's info.
499     */
500    public BoxFile.Info uploadFile(InputStream fileContent, String name, String description) {
501        FileUploadParams uploadInfo = new FileUploadParams()
502                .setContent(fileContent)
503                .setName(name)
504                .setDescription(description);
505        return this.uploadFile(uploadInfo);
506    }
507
508    /**
509     * Uploads a new file to this folder with custom upload parameters.
510     *
511     * @param uploadParams the custom upload parameters.
512     * @return the uploaded file's info.
513     */
514    public BoxFile.Info uploadFile(FileUploadParams uploadParams) {
515        URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());
516        BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);
517
518        JsonObject fieldJSON = new JsonObject();
519        JsonObject parentIdJSON = new JsonObject();
520        parentIdJSON.add("id", getID());
521        fieldJSON.add("name", uploadParams.getName());
522        fieldJSON.add("parent", parentIdJSON);
523
524        if (uploadParams.getCreated() != null) {
525            fieldJSON.add("content_created_at", BoxDateFormat.format(uploadParams.getCreated()));
526        }
527
528        if (uploadParams.getModified() != null) {
529            fieldJSON.add("content_modified_at", BoxDateFormat.format(uploadParams.getModified()));
530        }
531
532        if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {
533            request.setContentSHA1(uploadParams.getSHA1());
534        }
535
536        if (uploadParams.getDescription() != null) {
537            fieldJSON.add("description", uploadParams.getDescription());
538        }
539
540        request.putField("attributes", fieldJSON.toString());
541
542        if (uploadParams.getSize() > 0) {
543            request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());
544        } else if (uploadParams.getContent() != null) {
545            request.setFile(uploadParams.getContent(), uploadParams.getName());
546        } else {
547            request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());
548        }
549
550        BoxJSONResponse response;
551        if (uploadParams.getProgressListener() == null) {
552            response = (BoxJSONResponse) request.send();
553        } else {
554            response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());
555        }
556        JsonObject collection = JsonObject.readFrom(response.getJSON());
557        JsonArray entries = collection.get("entries").asArray();
558        JsonObject fileInfoJSON = entries.get(0).asObject();
559        String uploadedFileID = fileInfoJSON.get("id").asString();
560
561        BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);
562        return uploadedFile.new Info(fileInfoJSON);
563    }
564
565    /**
566     * Uploads a new weblink to this folder.
567     *
568     * @param linkURL the URL the weblink points to.
569     * @return the uploaded weblink's info.
570     */
571    public BoxWebLink.Info createWebLink(URL linkURL) {
572        return this.createWebLink(null, linkURL,
573                null);
574    }
575
576    /**
577     * Uploads a new weblink to this folder.
578     *
579     * @param name    the filename for the weblink.
580     * @param linkURL the URL the weblink points to.
581     * @return the uploaded weblink's info.
582     */
583    public BoxWebLink.Info createWebLink(String name, URL linkURL) {
584        return this.createWebLink(name, linkURL,
585                null);
586    }
587
588    /**
589     * Uploads a new weblink to this folder.
590     *
591     * @param linkURL     the URL the weblink points to.
592     * @param description the weblink's description.
593     * @return the uploaded weblink's info.
594     */
595    public BoxWebLink.Info createWebLink(URL linkURL, String description) {
596        return this.createWebLink(null, linkURL, description);
597    }
598
599    /**
600     * Uploads a new weblink to this folder.
601     *
602     * @param name        the filename for the weblink.
603     * @param linkURL     the URL the weblink points to.
604     * @param description the weblink's description.
605     * @return the uploaded weblink's info.
606     */
607    public BoxWebLink.Info createWebLink(String name, URL linkURL, String description) {
608        JsonObject parent = new JsonObject();
609        parent.add("id", this.getID());
610
611        JsonObject newWebLink = new JsonObject();
612        newWebLink.add("name", name);
613        newWebLink.add("parent", parent);
614        newWebLink.add("url", linkURL.toString());
615
616        if (description != null) {
617            newWebLink.add("description", description);
618        }
619
620        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(),
621                CREATE_WEB_LINK_URL.build(this.getAPI().getBaseURL()), "POST");
622        request.setBody(newWebLink.toString());
623        BoxJSONResponse response = (BoxJSONResponse) request.send();
624        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
625
626        BoxWebLink createdWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString());
627        return createdWebLink.new Info(responseJSON);
628    }
629
630    /**
631     * Returns an iterable containing the items in this folder. Iterating over the iterable returned by this method is
632     * equivalent to iterating over this BoxFolder directly.
633     *
634     * @return an iterable containing the items in this folder.
635     */
636    public Iterable<BoxItem.Info> getChildren() {
637        return this;
638    }
639
640    /**
641     * Returns an iterable containing the items in this folder and specifies which child fields to retrieve from the
642     * API.
643     *
644     * @param fields the fields to retrieve.
645     * @return an iterable containing the items in this folder.
646     */
647    public Iterable<BoxItem.Info> getChildren(final String... fields) {
648        return new Iterable<BoxItem.Info>() {
649            @Override
650            public Iterator<BoxItem.Info> iterator() {
651                String queryString = new QueryStringBuilder().appendParam("fields", fields).toString();
652                URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID());
653                return new BoxItemIterator(getAPI(), url);
654            }
655        };
656    }
657
658    /**
659     * Returns an iterable containing the items in this folder sorted by name and direction.
660     * @param sort the field to sort by, can be set as `name`, `id`, and `date`.
661     * @param direction the direction to display the item results.
662     * @param fields the fields to retrieve.
663     * @return an iterable containing the items in this folder.
664     */
665    public Iterable<BoxItem.Info> getChildren(String sort, SortDirection direction, final String... fields) {
666        QueryStringBuilder builder = new QueryStringBuilder()
667                .appendParam("sort", sort)
668                .appendParam("direction", direction.toString());
669
670        if (fields.length > 0) {
671            builder.appendParam("fields", fields).toString();
672        }
673        final String query = builder.toString();
674        return new Iterable<BoxItem.Info>() {
675            @Override
676            public Iterator<BoxItem.Info> iterator() {
677                URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID());
678                return new BoxItemIterator(getAPI(), url);
679            }
680        };
681    }
682
683    /**
684     * Retrieves a specific range of child items in this folder.
685     *
686     * @param offset the index of the first child item to retrieve.
687     * @param limit  the maximum number of children to retrieve after the offset.
688     * @param fields the fields to retrieve.
689     * @return a partial collection containing the specified range of child items.
690     */
691    public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {
692        QueryStringBuilder builder = new QueryStringBuilder()
693                .appendParam("limit", limit)
694                .appendParam("offset", offset);
695
696        if (fields.length > 0) {
697            builder.appendParam("fields", fields).toString();
698        }
699
700        URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());
701        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
702        BoxJSONResponse response = (BoxJSONResponse) request.send();
703        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
704
705        String totalCountString = responseJSON.get("total_count").toString();
706        long fullSize = Double.valueOf(totalCountString).longValue();
707        PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);
708        JsonArray jsonArray = responseJSON.get("entries").asArray();
709        for (JsonValue value : jsonArray) {
710            JsonObject jsonObject = value.asObject();
711            BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);
712            if (parsedItemInfo != null) {
713                children.add(parsedItemInfo);
714            }
715        }
716        return children;
717    }
718
719    /**
720     * Returns an iterator over the items in this folder.
721     *
722     * @return an iterator over the items in this folder.
723     */
724    @Override
725    public Iterator<BoxItem.Info> iterator() {
726        URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID());
727        return new BoxItemIterator(BoxFolder.this.getAPI(), url);
728    }
729
730    /**
731     * Adds new {@link BoxWebHook} to this {@link BoxFolder}.
732     *
733     * @param address  {@link BoxWebHook.Info#getAddress()}
734     * @param triggers {@link BoxWebHook.Info#getTriggers()}
735     * @return created {@link BoxWebHook.Info}
736     */
737    public BoxWebHook.Info addWebHook(URL address, BoxWebHook.Trigger... triggers) {
738        return BoxWebHook.create(this, address, triggers);
739    }
740
741    /**
742     * Used to retrieve the watermark for the folder.
743     * If the folder does not have a watermark applied to it, a 404 Not Found will be returned by API.
744     *
745     * @param fields the fields to retrieve.
746     * @return the watermark associated with the folder.
747     */
748    public BoxWatermark getWatermark(String... fields) {
749        return this.getWatermark(FOLDER_INFO_URL_TEMPLATE, fields);
750    }
751
752    /**
753     * Used to apply or update the watermark for the folder.
754     *
755     * @return the watermark associated with the folder.
756     */
757    public BoxWatermark applyWatermark() {
758        return this.applyWatermark(FOLDER_INFO_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT);
759    }
760
761    /**
762     * Removes a watermark from the folder.
763     * If the folder did not have a watermark applied to it, a 404 Not Found will be returned by API.
764     */
765    public void removeWatermark() {
766        this.removeWatermark(FOLDER_INFO_URL_TEMPLATE);
767    }
768
769    /**
770     * Used to retrieve all metadata associated with the folder.
771     *
772     * @param fields the optional fields to retrieve.
773     * @return An iterable of metadata instances associated with the folder
774     */
775    public Iterable<Metadata> getAllMetadata(String... fields) {
776        return Metadata.getAllMetadata(this, fields);
777    }
778
779    /**
780     * This method is deprecated, please use the {@link BoxSearch} class instead.
781     * Searches this folder and all descendant folders using a given queryPlease use BoxSearch Instead.
782     *
783     * @param query the search query.
784     * @return an Iterable containing the search results.
785     */
786    @Deprecated
787    public Iterable<BoxItem.Info> search(final String query) {
788        return new Iterable<BoxItem.Info>() {
789            @Override
790            public Iterator<BoxItem.Info> iterator() {
791                QueryStringBuilder builder = new QueryStringBuilder();
792                builder.appendParam("query", query);
793                builder.appendParam("ancestor_folder_ids", getID());
794
795                URL url = SEARCH_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), builder.toString());
796                return new BoxItemIterator(getAPI(), url);
797            }
798        };
799    }
800
801    @Override
802    public BoxFolder.Info setCollections(BoxCollection... collections) {
803        JsonArray jsonArray = new JsonArray();
804        for (BoxCollection collection : collections) {
805            JsonObject collectionJSON = new JsonObject();
806            collectionJSON.add("id", collection.getID());
807            jsonArray.add(collectionJSON);
808        }
809        JsonObject infoJSON = new JsonObject();
810        infoJSON.add("collections", jsonArray);
811
812        String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString();
813        URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
814        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
815        request.setBody(infoJSON.toString());
816        BoxJSONResponse response = (BoxJSONResponse) request.send();
817        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
818        return new Info(jsonObject);
819    }
820
821    /**
822     * Creates global property metadata on this folder.
823     *
824     * @param metadata the new metadata values.
825     * @return the metadata returned from the server.
826     */
827    public Metadata createMetadata(Metadata metadata) {
828        return this.createMetadata(Metadata.DEFAULT_METADATA_TYPE, metadata);
829    }
830
831    /**
832     * Creates metadata on this folder using a specified template.
833     *
834     * @param templateName the name of the metadata template.
835     * @param metadata     the new metadata values.
836     * @return the metadata returned from the server.
837     */
838    public Metadata createMetadata(String templateName, Metadata metadata) {
839        String scope = Metadata.scopeBasedOnType(templateName);
840        return this.createMetadata(templateName, scope, metadata);
841    }
842
843    /**
844     * Creates metadata on this folder using a specified scope and template.
845     *
846     * @param templateName the name of the metadata template.
847     * @param scope        the scope of the template (usually "global" or "enterprise").
848     * @param metadata     the new metadata values.
849     * @return the metadata returned from the server.
850     */
851    public Metadata createMetadata(String templateName, String scope, Metadata metadata) {
852        URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);
853        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "POST");
854        request.addHeader("Content-Type", "application/json");
855        request.setBody(metadata.toString());
856        BoxJSONResponse response = (BoxJSONResponse) request.send();
857        return new Metadata(JsonObject.readFrom(response.getJSON()));
858    }
859
860    /**
861     * Sets the provided metadata on the folder, overwriting any existing metadata keys already present.
862     *
863     * @param templateName the name of the metadata template.
864     * @param scope        the scope of the template (usually "global" or "enterprise").
865     * @param metadata     the new metadata values.
866     * @return the metadata returned from the server.
867     */
868    public Metadata setMetadata(String templateName, String scope, Metadata metadata) {
869        Metadata metadataValue = null;
870
871        try {
872            metadataValue = this.createMetadata(templateName, scope, metadata);
873        } catch (BoxAPIException e) {
874            if (e.getResponseCode() == 409) {
875                Metadata metadataToUpdate = new Metadata(scope, templateName);
876                for (JsonValue value : metadata.getOperations()) {
877                    if (value.asObject().get("value").isNumber()) {
878                        metadataToUpdate.add(value.asObject().get("path").asString(),
879                                value.asObject().get("value").asFloat());
880                    } else if (value.asObject().get("value").isString()) {
881                        metadataToUpdate.add(value.asObject().get("path").asString(),
882                                value.asObject().get("value").asString());
883                    } else if (value.asObject().get("value").isArray()) {
884                        ArrayList<String> list = new ArrayList<String>();
885                        for (JsonValue jsonValue : value.asObject().get("value").asArray()) {
886                            list.add(jsonValue.asString());
887                        }
888                        metadataToUpdate.add(value.asObject().get("path").asString(), list);
889                    }
890                }
891                metadataValue = this.updateMetadata(metadataToUpdate);
892            }
893        }
894
895        return metadataValue;
896    }
897
898    /**
899     * Gets the global properties metadata on this folder.
900     *
901     * @return the metadata returned from the server.
902     */
903    public Metadata getMetadata() {
904        return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE);
905    }
906
907    /**
908     * Gets the metadata on this folder associated with a specified template.
909     *
910     * @param templateName the metadata template type name.
911     * @return the metadata returned from the server.
912     */
913    public Metadata getMetadata(String templateName) {
914        String scope = Metadata.scopeBasedOnType(templateName);
915        return this.getMetadata(templateName, scope);
916    }
917
918    /**
919     * Gets the metadata on this folder associated with a specified scope and template.
920     *
921     * @param templateName the metadata template type name.
922     * @param scope        the scope of the template (usually "global" or "enterprise").
923     * @return the metadata returned from the server.
924     */
925    public Metadata getMetadata(String templateName, String scope) {
926        URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);
927        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
928        BoxJSONResponse response = (BoxJSONResponse) request.send();
929        return new Metadata(JsonObject.readFrom(response.getJSON()));
930    }
931
932    /**
933     * Updates the global properties metadata on this folder.
934     *
935     * @param metadata the new metadata values.
936     * @return the metadata returned from the server.
937     */
938    public Metadata updateMetadata(Metadata metadata) {
939        URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), metadata.getScope(),
940                metadata.getTemplateName());
941        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT");
942        request.addHeader("Content-Type", "application/json-patch+json");
943        request.setBody(metadata.getPatch());
944        BoxJSONResponse response = (BoxJSONResponse) request.send();
945        return new Metadata(JsonObject.readFrom(response.getJSON()));
946    }
947
948    /**
949     * Deletes the global properties metadata on this folder.
950     */
951    public void deleteMetadata() {
952        this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE);
953    }
954
955    /**
956     * Deletes the metadata on this folder associated with a specified template.
957     *
958     * @param templateName the metadata template type name.
959     */
960    public void deleteMetadata(String templateName) {
961        String scope = Metadata.scopeBasedOnType(templateName);
962        this.deleteMetadata(templateName, scope);
963    }
964
965    /**
966     * Deletes the metadata on this folder associated with a specified scope and template.
967     *
968     * @param templateName the metadata template type name.
969     * @param scope        the scope of the template (usually "global" or "enterprise").
970     */
971    public void deleteMetadata(String templateName, String scope) {
972        URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);
973        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
974        BoxAPIResponse response = request.send();
975        response.disconnect();
976    }
977
978    /**
979     * Adds a metadata classification to the specified file.
980     *
981     * @param classificationType the metadata classification type.
982     * @return the metadata classification type added to the file.
983     */
984    public String addClassification(String classificationType) {
985        Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);
986        Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,
987                "enterprise", metadata);
988
989        return classification.getString(Metadata.CLASSIFICATION_KEY);
990    }
991
992    /**
993     * Updates a metadata classification on the specified file.
994     *
995     * @param classificationType the metadata classification type.
996     * @return the new metadata classification type updated on the file.
997     */
998    public String updateClassification(String classificationType) {
999        Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY);
1000        metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);
1001        Metadata classification = this.updateMetadata(metadata);
1002
1003        return classification.getString(Metadata.CLASSIFICATION_KEY);
1004    }
1005
1006    /**
1007     * Attempts to add classification to a file. If classification already exists then do update.
1008     *
1009     * @param classificationType the metadata classification type.
1010     * @return the metadata classification type on the file.
1011     */
1012    public String setClassification(String classificationType) {
1013        Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);
1014        Metadata classification = null;
1015
1016        try {
1017            classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata);
1018        } catch (BoxAPIException e) {
1019            if (e.getResponseCode() == 409) {
1020                metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY);
1021                metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);
1022                classification = this.updateMetadata(metadata);
1023            } else {
1024                throw e;
1025            }
1026        }
1027
1028        return classification.getString("/Box__Security__Classification__Key");
1029    }
1030
1031    /**
1032     * Gets the classification type for the specified file.
1033     *
1034     * @return the metadata classification type on the file.
1035     */
1036    public String getClassification() {
1037        Metadata metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY);
1038        return metadata.getString(Metadata.CLASSIFICATION_KEY);
1039    }
1040
1041    /**
1042     * Deletes the classification on the file.
1043     */
1044    public void deleteClassification() {
1045        this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise");
1046    }
1047
1048    /**
1049     * Creates an upload session to create a new file in chunks.
1050     * This will first verify that the file can be created and then open a session for uploading pieces of the file.
1051     *
1052     * @param fileName the name of the file to be created
1053     * @param fileSize the size of the file that will be uploaded
1054     * @return the created upload session instance
1055     */
1056    public BoxFileUploadSession.Info createUploadSession(String fileName, long fileSize) {
1057
1058        URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());
1059        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
1060
1061        JsonObject body = new JsonObject();
1062        body.add("folder_id", this.getID());
1063        body.add("file_name", fileName);
1064        body.add("file_size", fileSize);
1065        request.setBody(body.toString());
1066
1067        BoxJSONResponse response = (BoxJSONResponse) request.send();
1068        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
1069
1070        String sessionId = jsonObject.get("id").asString();
1071        BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId);
1072
1073        return session.new Info(jsonObject);
1074    }
1075
1076    /**
1077     * Creates a new file.
1078     *
1079     * @param inputStream the stream instance that contains the data.
1080     * @param fileName    the name of the file to be created.
1081     * @param fileSize    the size of the file that will be uploaded.
1082     * @return the created file instance.
1083     * @throws InterruptedException when a thread execution is interrupted.
1084     * @throws IOException          when reading a stream throws exception.
1085     */
1086    public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)
1087            throws InterruptedException, IOException {
1088        URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());
1089        return new LargeFileUpload().
1090                upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);
1091    }
1092
1093    /**
1094     * Creates a new file.  Also sets file attributes.
1095     *
1096     * @param inputStream the stream instance that contains the data.
1097     * @param fileName    the name of the file to be created.
1098     * @param fileSize    the size of the file that will be uploaded.
1099     * @param fileAttributes file attributes to set
1100     * @return the created file instance.
1101     * @throws InterruptedException when a thread execution is interrupted.
1102     * @throws IOException          when reading a stream throws exception.
1103     */
1104    public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize,
1105            Map<String, String> fileAttributes)
1106            throws InterruptedException, IOException {
1107        URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());
1108        return new LargeFileUpload().
1109                upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize, fileAttributes);
1110    }
1111
1112    /**
1113     * Creates a new file using specified number of parallel http connections.
1114     *
1115     * @param inputStream          the stream instance that contains the data.
1116     * @param fileName             the name of the file to be created.
1117     * @param fileSize             the size of the file that will be uploaded.
1118     * @param nParallelConnections number of parallel http connections to use
1119     * @param timeOut              time to wait before killing the job
1120     * @param unit                 time unit for the time wait value
1121     * @return the created file instance.
1122     * @throws InterruptedException when a thread execution is interrupted.
1123     * @throws IOException          when reading a stream throws exception.
1124     */
1125    public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize,
1126                                        int nParallelConnections, long timeOut, TimeUnit unit)
1127            throws InterruptedException, IOException {
1128        URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());
1129        return new LargeFileUpload(nParallelConnections, timeOut, unit).
1130                upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);
1131    }
1132
1133    /**
1134     * Creates a new file using specified number of parallel http connections.  Also sets file attributes.
1135     *
1136     * @param inputStream          the stream instance that contains the data.
1137     * @param fileName             the name of the file to be created.
1138     * @param fileSize             the size of the file that will be uploaded.
1139     * @param nParallelConnections number of parallel http connections to use
1140     * @param timeOut              time to wait before killing the job
1141     * @param unit                 time unit for the time wait value
1142     * @param fileAttributes       file attributes to set
1143     * @return the created file instance.
1144     * @throws InterruptedException when a thread execution is interrupted.
1145     * @throws IOException          when reading a stream throws exception.
1146     */
1147    public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize,
1148                                        int nParallelConnections, long timeOut, TimeUnit unit,
1149                                        Map<String, String> fileAttributes)
1150            throws InterruptedException, IOException {
1151        URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());
1152        return new LargeFileUpload(nParallelConnections, timeOut, unit).
1153                upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize, fileAttributes);
1154    }
1155
1156    /**
1157     * Creates a new Metadata Cascade Policy on a folder.
1158     *
1159     * @param scope         the scope of the metadata cascade policy.
1160     * @param templateKey   the key of the template.
1161     * @return  information about the Metadata Cascade Policy.
1162     */
1163    public BoxMetadataCascadePolicy.Info addMetadataCascadePolicy(String scope, String templateKey) {
1164
1165        return BoxMetadataCascadePolicy.create(this.getAPI(), this.getID(), scope, templateKey);
1166    }
1167
1168    /**
1169     * Retrieves all Metadata Cascade Policies on a folder.
1170     *
1171     * @param fields            optional fields to retrieve for cascade policies.
1172     * @return  the Iterable of Box Metadata Cascade Policies in your enterprise.
1173     */
1174    public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String... fields) {
1175        Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =
1176                BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields);
1177
1178        return cascadePoliciesInfo;
1179    }
1180
1181    /**
1182     * Retrieves all Metadata Cascade Policies on a folder.
1183     *
1184     * @param enterpriseID      the ID of the enterprise to retrieve cascade policies for.
1185     * @param limit             the number of entries of cascade policies to retrieve.
1186     * @param fields            optional fields to retrieve for cascade policies.
1187     * @return  the Iterable of Box Metadata Cascade Policies in your enterprise.
1188     */
1189    public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String enterpriseID,
1190                                                                      int limit, String... fields) {
1191        Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =
1192                BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), enterpriseID, limit, fields);
1193
1194        return cascadePoliciesInfo;
1195    }
1196
1197    /**
1198     * Contains information about a BoxFolder.
1199     */
1200    public class Info extends BoxItem.Info {
1201        private BoxUploadEmail uploadEmail;
1202        private boolean hasCollaborations;
1203        private SyncState syncState;
1204        private EnumSet<Permission> permissions;
1205        private boolean canNonOwnersInvite;
1206        private boolean isWatermarked;
1207        private boolean isCollaborationRestrictedToEnterprise;
1208        private Boolean isExternallyOwned;
1209        private Map<String, Map<String, Metadata>> metadataMap;
1210        private List<String> allowedSharedLinkAccessLevels;
1211        private List<String> allowedInviteeRoles;
1212
1213        /**
1214         * Constructs an empty Info object.
1215         */
1216        public Info() {
1217            super();
1218        }
1219
1220        /**
1221         * Constructs an Info object by parsing information from a JSON string.
1222         *
1223         * @param json the JSON string to parse.
1224         */
1225        public Info(String json) {
1226            super(json);
1227        }
1228
1229        /**
1230         * Constructs an Info object using an already parsed JSON object.
1231         *
1232         * @param jsonObject the parsed JSON object.
1233         */
1234        public Info(JsonObject jsonObject) {
1235            super(jsonObject);
1236        }
1237
1238        /**
1239         * Gets the upload email for the folder.
1240         *
1241         * @return the upload email for the folder.
1242         */
1243        public BoxUploadEmail getUploadEmail() {
1244            return this.uploadEmail;
1245        }
1246
1247        /**
1248         * Sets the upload email for the folder.
1249         *
1250         * @param uploadEmail the upload email for the folder.
1251         */
1252        public void setUploadEmail(BoxUploadEmail uploadEmail) {
1253            if (this.uploadEmail == uploadEmail) {
1254                return;
1255            }
1256
1257            this.removeChildObject("folder_upload_email");
1258            this.uploadEmail = uploadEmail;
1259
1260            if (uploadEmail == null) {
1261                this.addPendingChange("folder_upload_email", (String) null);
1262            } else {
1263                this.addChildObject("folder_upload_email", uploadEmail);
1264            }
1265        }
1266
1267        /**
1268         * Gets whether or not the folder has any collaborations.
1269         *
1270         * @return true if the folder has collaborations; otherwise false.
1271         */
1272        public boolean getHasCollaborations() {
1273            return this.hasCollaborations;
1274        }
1275
1276        /**
1277         * Gets the sync state of the folder.
1278         *
1279         * @return the sync state of the folder.
1280         */
1281        public SyncState getSyncState() {
1282            return this.syncState;
1283        }
1284
1285        /**
1286         * Sets the sync state of the folder.
1287         *
1288         * @param syncState the sync state of the folder.
1289         */
1290        public void setSyncState(SyncState syncState) {
1291            this.syncState = syncState;
1292            this.addPendingChange("sync_state", syncState.toJSONValue());
1293        }
1294
1295        /**
1296         * Gets the permissions that the current user has on the folder.
1297         *
1298         * @return the permissions that the current user has on the folder.
1299         */
1300        public EnumSet<Permission> getPermissions() {
1301            return this.permissions;
1302        }
1303
1304        /**
1305         * Gets whether or not the non-owners can invite collaborators to the folder.
1306         *
1307         * @return [description]
1308         */
1309        public boolean getCanNonOwnersInvite() {
1310            return this.canNonOwnersInvite;
1311        }
1312
1313        /**
1314         * Sets whether or not non-owners can invite collaborators to the folder.
1315         *
1316         * @param canNonOwnersInvite indicates non-owners can invite collaborators to the folder.
1317         */
1318        public void setCanNonOwnersInvite(boolean canNonOwnersInvite) {
1319            this.canNonOwnersInvite = canNonOwnersInvite;
1320            this.addPendingChange("can_non_owners_invite", canNonOwnersInvite);
1321        }
1322
1323        /**
1324         * Gets whether future collaborations should be restricted to within the enterprise only.
1325         *
1326         * @return indicates whether collaboration is restricted to enterprise only.
1327         */
1328        public boolean getIsCollaborationRestrictedToEnterprise() {
1329            return this.isCollaborationRestrictedToEnterprise;
1330        }
1331
1332        /**
1333         * Sets whether future collaborations should be restricted to within the enterprise only.
1334         *
1335         * @param isRestricted indicates whether there is collaboration restriction within enterprise.
1336         */
1337        public void setIsCollaborationRestrictedToEnterprise(boolean isRestricted) {
1338            this.isCollaborationRestrictedToEnterprise = isRestricted;
1339            this.addPendingChange("is_collaboration_restricted_to_enterprise", isRestricted);
1340        }
1341
1342        /**
1343         * Retrieves the allowed roles for collaborations.
1344         *
1345         * @return the roles allowed for collaboration.
1346         */
1347        public List<String> getAllowedInviteeRoles() {
1348            return this.allowedInviteeRoles;
1349        }
1350
1351        /**
1352         * Retrieves the allowed access levels for a shared link.
1353         *
1354         * @return the allowed access levels for a shared link.
1355         */
1356        public List<String> getAllowedSharedLinkAccessLevels() {
1357            return this.allowedSharedLinkAccessLevels;
1358        }
1359
1360        /**
1361         * Gets flag indicating whether this file is Watermarked.
1362         *
1363         * @return whether the file is watermarked or not
1364         */
1365        public boolean getIsWatermarked() {
1366            return this.isWatermarked;
1367        }
1368
1369        /**
1370         * Gets the metadata on this folder associated with a specified scope and template.
1371         * Makes an attempt to get metadata that was retrieved using getInfo(String ...) method. If no result is found
1372         * then makes an API call to get metadata
1373         *
1374         * @param templateName the metadata template type name.
1375         * @param scope        the scope of the template (usually "global" or "enterprise").
1376         * @return the metadata returned from the server.
1377         */
1378        public Metadata getMetadata(String templateName, String scope) {
1379            try {
1380                return this.metadataMap.get(scope).get(templateName);
1381            } catch (NullPointerException e) {
1382                return null;
1383            }
1384        }
1385
1386        /**
1387         * Get the field is_externally_owned determining whether this folder is owned by a user outside of the
1388         * enterprise.
1389         * @return a boolean indicating whether this folder is owned by a user outside the enterprise.
1390         */
1391        public boolean getIsExternallyOwned() {
1392            return this.isExternallyOwned;
1393        }
1394
1395        @Override
1396        public BoxFolder getResource() {
1397            return BoxFolder.this;
1398        }
1399
1400        @Override
1401        protected void parseJSONMember(JsonObject.Member member) {
1402            super.parseJSONMember(member);
1403
1404            String memberName = member.getName();
1405            JsonValue value = member.getValue();
1406            try {
1407                if (memberName.equals("folder_upload_email")) {
1408                    if (this.uploadEmail == null) {
1409                        this.uploadEmail = new BoxUploadEmail(value.asObject());
1410                    } else {
1411                        this.uploadEmail.update(value.asObject());
1412                    }
1413
1414                } else if (memberName.equals("has_collaborations")) {
1415                    this.hasCollaborations = value.asBoolean();
1416
1417                } else if (memberName.equals("sync_state")) {
1418                    this.syncState = SyncState.fromJSONValue(value.asString());
1419
1420                } else if (memberName.equals("permissions")) {
1421                    this.permissions = this.parsePermissions(value.asObject());
1422
1423                } else if (memberName.equals("can_non_owners_invite")) {
1424                    this.canNonOwnersInvite = value.asBoolean();
1425                } else if (memberName.equals("allowed_shared_link_access_levels")) {
1426                    this.allowedSharedLinkAccessLevels = this.parseSharedLinkAccessLevels(value.asArray());
1427                } else if (memberName.equals("allowed_invitee_roles")) {
1428                    this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray());
1429                } else if (memberName.equals("is_collaboration_restricted_to_enterprise")) {
1430                    this.isCollaborationRestrictedToEnterprise = value.asBoolean();
1431                } else if (memberName.equals("is_externally_owned")) {
1432                    this.isExternallyOwned = value.asBoolean();
1433                } else if (memberName.equals("watermark_info")) {
1434                    JsonObject jsonObject = value.asObject();
1435                    this.isWatermarked = jsonObject.get("is_watermarked").asBoolean();
1436                } else if (memberName.equals("metadata")) {
1437                    JsonObject jsonObject = value.asObject();
1438                    this.metadataMap = Parsers.parseAndPopulateMetadataMap(jsonObject);
1439                }
1440            } catch (Exception e) {
1441                throw new BoxDeserializationException(memberName, value.toString(), e);
1442            }
1443        }
1444
1445        private EnumSet<Permission> parsePermissions(JsonObject jsonObject) {
1446            EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class);
1447            for (JsonObject.Member member : jsonObject) {
1448                JsonValue value = member.getValue();
1449                if (value.isNull() || !value.asBoolean()) {
1450                    continue;
1451                }
1452
1453                String memberName = member.getName();
1454                if (memberName.equals("can_download")) {
1455                    permissions.add(Permission.CAN_DOWNLOAD);
1456                } else if (memberName.equals("can_upload")) {
1457                    permissions.add(Permission.CAN_UPLOAD);
1458                } else if (memberName.equals("can_rename")) {
1459                    permissions.add(Permission.CAN_RENAME);
1460                } else if (memberName.equals("can_delete")) {
1461                    permissions.add(Permission.CAN_DELETE);
1462                } else if (memberName.equals("can_share")) {
1463                    permissions.add(Permission.CAN_SHARE);
1464                } else if (memberName.equals("can_invite_collaborator")) {
1465                    permissions.add(Permission.CAN_INVITE_COLLABORATOR);
1466                } else if (memberName.equals("can_set_share_access")) {
1467                    permissions.add(Permission.CAN_SET_SHARE_ACCESS);
1468                }
1469            }
1470
1471            return permissions;
1472        }
1473
1474        private List<String> parseSharedLinkAccessLevels(JsonArray jsonArray) {
1475            List<String> accessLevels = new ArrayList<String>(jsonArray.size());
1476            for (JsonValue value : jsonArray) {
1477                accessLevels.add(value.asString());
1478            }
1479
1480            return accessLevels;
1481        }
1482
1483        private List<String> parseAllowedInviteeRoles(JsonArray jsonArray) {
1484            List<String> roles = new ArrayList<String>(jsonArray.size());
1485            for (JsonValue value : jsonArray) {
1486                roles.add(value.asString());
1487            }
1488
1489            return roles;
1490        }
1491    }
1492
1493    /**
1494     * Enumerates the possible sync states that a folder can have.
1495     */
1496    public enum SyncState {
1497        /**
1498         * The folder is synced.
1499         */
1500        SYNCED("synced"),
1501
1502        /**
1503         * The folder is not synced.
1504         */
1505        NOT_SYNCED("not_synced"),
1506
1507        /**
1508         * The folder is partially synced.
1509         */
1510        PARTIALLY_SYNCED("partially_synced");
1511
1512        private final String jsonValue;
1513
1514        private SyncState(String jsonValue) {
1515            this.jsonValue = jsonValue;
1516        }
1517
1518        static SyncState fromJSONValue(String jsonValue) {
1519            return SyncState.valueOf(jsonValue.toUpperCase());
1520        }
1521
1522        String toJSONValue() {
1523            return this.jsonValue;
1524        }
1525    }
1526
1527    /**
1528     * Enumerates the possible permissions that a user can have on a folder.
1529     */
1530    public enum Permission {
1531        /**
1532         * The user can download the folder.
1533         */
1534        CAN_DOWNLOAD("can_download"),
1535
1536        /**
1537         * The user can upload to the folder.
1538         */
1539        CAN_UPLOAD("can_upload"),
1540
1541        /**
1542         * The user can rename the folder.
1543         */
1544        CAN_RENAME("can_rename"),
1545
1546        /**
1547         * The user can delete the folder.
1548         */
1549        CAN_DELETE("can_delete"),
1550
1551        /**
1552         * The user can share the folder.
1553         */
1554        CAN_SHARE("can_share"),
1555
1556        /**
1557         * The user can invite collaborators to the folder.
1558         */
1559        CAN_INVITE_COLLABORATOR("can_invite_collaborator"),
1560
1561        /**
1562         * The user can set the access level for shared links to the folder.
1563         */
1564        CAN_SET_SHARE_ACCESS("can_set_share_access");
1565
1566        private final String jsonValue;
1567
1568        private Permission(String jsonValue) {
1569            this.jsonValue = jsonValue;
1570        }
1571
1572        static Permission fromJSONValue(String jsonValue) {
1573            return Permission.valueOf(jsonValue.toUpperCase());
1574        }
1575
1576        String toJSONValue() {
1577            return this.jsonValue;
1578        }
1579    }
1580}