001package com.box.sdk;
002
003import java.net.URL;
004import java.util.ArrayList;
005import java.util.Collection;
006import java.util.Iterator;
007import java.util.List;
008
009import com.eclipsesource.json.JsonArray;
010import com.eclipsesource.json.JsonObject;
011import com.eclipsesource.json.JsonValue;
012
013/**
014 * Represents a Box user account.
015 *
016 * <p>Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked
017 * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error
018 * handling for errors related to the Box REST API, you should capture this exception explicitly.</p>
019 */
020@BoxResourceType("user")
021public class BoxUser extends BoxCollaborator {
022
023    /**
024     * An array of all possible file fields that can be requested when calling {@link #getInfo(String...)}.
025     */
026    public static final String[] ALL_FIELDS = {"type", "id", "name", "login", "created_at", "modified_at", "role",
027        "language", "timezone", "space_amount", "space_used", "max_upload_size", "tracking_codes",
028        "can_see_managed_users", "is_sync_enabled", "is_external_collab_restricted", "status", "job_title", "phone",
029        "address", "avatar_url", "is_exempt_from_device_limits", "is_exempt_from_login_verification", "enterprise",
030        "my_tags", "hostname", "is_platform_access_only", "external_app_user_id"};
031
032    /**
033     * User URL Template.
034     */
035    public static final URLTemplate USER_URL_TEMPLATE = new URLTemplate("users/%s");
036    /**
037     * Get Me URL Template.
038     */
039    public static final URLTemplate GET_ME_URL = new URLTemplate("users/me");
040    /**
041     * Users URL Template.
042     */
043    public static final URLTemplate USERS_URL_TEMPLATE = new URLTemplate("users");
044    /**
045     * User Memberships URL Template.
046     */
047    public static final URLTemplate USER_MEMBERSHIPS_URL_TEMPLATE = new URLTemplate("users/%s/memberships");
048    /**
049     * E-Mail Alias URL Template.
050     */
051    public static final URLTemplate EMAIL_ALIAS_URL_TEMPLATE = new URLTemplate("users/%s/email_aliases/%s");
052    /**
053     * E-Mail Aliases URL Template.
054     */
055    public static final URLTemplate EMAIL_ALIASES_URL_TEMPLATE = new URLTemplate("users/%s/email_aliases");
056    /**
057     * Move Folder To User Template.
058     */
059    public static final URLTemplate MOVE_FOLDER_TO_USER_TEMPLATE = new URLTemplate("users/%s/folders/%s");
060
061    /**
062     * Constructs a BoxUser for a user with a given ID.
063     * @param  api the API connection to be used by the user.
064     * @param  id  the ID of the user.
065     */
066    public BoxUser(BoxAPIConnection api, String id) {
067        super(api, id);
068    }
069
070    /**
071     * Provisions a new app user in an enterprise using Box Developer Edition.
072     * @param  api   the API connection to be used by the created user.
073     * @param  name  the name of the user.
074     * @return       the created user's info.
075     */
076    public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {
077        return createAppUser(api, name, new CreateUserParams());
078    }
079
080    /**
081     * Provisions a new app user in an enterprise with additional user information using Box Developer Edition.
082     * @param  api    the API connection to be used by the created user.
083     * @param  name   the name of the user.
084     * @param  params additional user information.
085     * @return        the created user's info.
086     */
087    public static BoxUser.Info createAppUser(BoxAPIConnection api, String name,
088        CreateUserParams params) {
089
090        params.setIsPlatformAccessOnly(true);
091        return createEnterpriseUser(api, null, name, params);
092    }
093
094    /**
095     * Provisions a new user in an enterprise.
096     * @param  api   the API connection to be used by the created user.
097     * @param  login the email address the user will use to login.
098     * @param  name  the name of the user.
099     * @return       the created user's info.
100     */
101    public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {
102        return createEnterpriseUser(api, login, name, null);
103    }
104
105    /**
106     * Provisions a new user in an enterprise with additional user information.
107     * @param  api    the API connection to be used by the created user.
108     * @param  login  the email address the user will use to login.
109     * @param  name   the name of the user.
110     * @param  params additional user information.
111     * @return        the created user's info.
112     */
113    public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name,
114        CreateUserParams params) {
115
116        JsonObject requestJSON = new JsonObject();
117        requestJSON.add("login", login);
118        requestJSON.add("name", name);
119
120        if (params != null) {
121            if (params.getRole() != null) {
122                requestJSON.add("role", params.getRole().toJSONValue());
123            }
124
125            if (params.getStatus() != null) {
126                requestJSON.add("status", params.getStatus().toJSONValue());
127            }
128
129            requestJSON.add("language", params.getLanguage());
130            requestJSON.add("is_sync_enabled", params.getIsSyncEnabled());
131            requestJSON.add("job_title", params.getJobTitle());
132            requestJSON.add("phone", params.getPhone());
133            requestJSON.add("address", params.getAddress());
134            requestJSON.add("space_amount", params.getSpaceAmount());
135            requestJSON.add("can_see_managed_users", params.getCanSeeManagedUsers());
136            requestJSON.add("timezone", params.getTimezone());
137            requestJSON.add("is_exempt_from_device_limits", params.getIsExemptFromDeviceLimits());
138            requestJSON.add("is_exempt_from_login_verification", params.getIsExemptFromLoginVerification());
139            requestJSON.add("is_platform_access_only", params.getIsPlatformAccessOnly());
140            requestJSON.add("external_app_user_id", params.getExternalAppUserId());
141        }
142
143        URL url = USERS_URL_TEMPLATE.build(api.getBaseURL());
144        BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
145        request.setBody(requestJSON.toString());
146        BoxJSONResponse response = (BoxJSONResponse) request.send();
147        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
148
149        BoxUser createdUser = new BoxUser(api, responseJSON.get("id").asString());
150        return createdUser.new Info(responseJSON);
151    }
152
153    /**
154     * Gets the current user.
155     * @param  api the API connection of the current user.
156     * @return     the current user.
157     */
158    public static BoxUser getCurrentUser(BoxAPIConnection api) {
159        URL url = GET_ME_URL.build(api.getBaseURL());
160        BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
161        BoxJSONResponse response = (BoxJSONResponse) request.send();
162        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
163        return new BoxUser(api, jsonObject.get("id").asString());
164    }
165
166    /**
167     * Returns an iterable containing all the enterprise users.
168     * @param  api the API connection to be used when retrieving the users.
169     * @return     an iterable containing all the enterprise users.
170     */
171    public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api) {
172        return getAllEnterpriseUsers(api, null);
173    }
174
175    /**
176     * Returns an iterable containing all the enterprise users that matches the filter and specifies which child fields
177     * to retrieve from the API.
178     * @param  api        the API connection to be used when retrieving the users.
179     * @param  filterTerm used to filter the results to only users starting with this string in either the name or the
180     *                    login. Can be null to not filter the results.
181     * @param  fields     the fields to retrieve. Leave this out for the standard fields.
182     * @return            an iterable containing all the enterprise users that matches the filter.
183     */
184    public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api, final String filterTerm,
185            final String... fields) {
186        return getUsersInfoForType(api, filterTerm, null, null, fields);
187    }
188
189    /**
190     * Gets a limited set of information about an external user. (A user collaborating
191     * on content owned by the enterprise). Note: Only fields the user has permission to
192     * see will be returned with values. Other fields will return a value of null.
193     * @param  api        the API connection to be used when retrieving the users.
194     * @param  filterTerm used to filter the results to only users matching the given login.
195     *                    This does exact match only, so if no filter term is passed in, nothing
196     *                    will be returned.
197     * @param  fields     the fields to retrieve. Leave this out for the standard fields.
198     * @return an iterable containing external users matching the given email
199     */
200    public static Iterable<BoxUser.Info> getExternalUsers(final BoxAPIConnection api, final String filterTerm,
201          final String... fields) {
202        return getUsersInfoForType(api, filterTerm, "external", null, fields);
203    }
204
205    /**
206     * Gets any managed users that match the filter term as well as any external users that
207     * match the filter term. For managed users it matches any users names or emails that
208     * start with the term. For external, it only does full match on email. This method
209     * is ideal to use in the case where you have a full email for a user and you don't
210     * know if they're managed or external.
211     * @param  api        the API connection to be used when retrieving the users.
212     * @param filterTerm    The filter term to lookup users by (login for external, login or name for managed)
213     * @param fields        the fields to retrieve. Leave this out for the standard fields.
214     * @return an iterable containing users matching the given email
215     */
216    public static Iterable<BoxUser.Info> getAllEnterpriseOrExternalUsers(final BoxAPIConnection api,
217           final String filterTerm, final String... fields) {
218        return getUsersInfoForType(api, filterTerm, "all", null, fields);
219    }
220
221    /**
222     * Gets any app users that has an exact match with the externalAppUserId term.
223     * @param api                 the API connection to be used when retrieving the users.
224     * @param externalAppUserId    the external app user id that has been set for app user
225     * @param fields               the fields to retrieve. Leave this out for the standard fields.
226     * @return an iterable containing users matching the given email
227     */
228    public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api,
229           final String externalAppUserId, final String... fields) {
230        return getUsersInfoForType(api, null, null, externalAppUserId, fields);
231    }
232
233    /**
234     * Helper method to abstract out the common logic from the various users methods.
235     *
236     * @param api               the API connection to be used when retrieving the users.
237     * @param filterTerm        The filter term to lookup users by (login for external, login or name for managed)
238     * @param userType          The type of users we want to search with this request.
239     *                          Valid values are 'managed' (enterprise users), 'external' or 'all'
240     * @param externalAppUserId the external app user id that has been set for an app user
241     * @param fields            the fields to retrieve. Leave this out for the standard fields.
242     * @return                  An iterator over the selected users.
243     */
244    private static Iterable<BoxUser.Info> getUsersInfoForType(final BoxAPIConnection api,
245          final String filterTerm, final String userType, final String externalAppUserId, final String... fields) {
246        return new Iterable<BoxUser.Info>() {
247            public Iterator<BoxUser.Info> iterator() {
248                QueryStringBuilder builder = new QueryStringBuilder();
249                if (filterTerm != null) {
250                    builder.appendParam("filter_term", filterTerm);
251                }
252                if (userType != null) {
253                    builder.appendParam("user_type", userType);
254                }
255                if (externalAppUserId != null) {
256                    builder.appendParam("external_app_user_id", externalAppUserId);
257                }
258                if (fields.length > 0) {
259                    builder.appendParam("fields", fields);
260                }
261                URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
262                return new BoxUserIterator(api, url);
263            }
264        };
265    }
266
267    /**
268     * Gets information about this user.
269     * @param  fields the optional fields to retrieve.
270     * @return        info about this user.
271     */
272    public BoxUser.Info getInfo(String... fields) {
273        URL url;
274        if (fields.length > 0) {
275            String queryString = new QueryStringBuilder().appendParam("fields", fields).toString();
276            url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
277        } else {
278            url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
279        }
280        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
281        BoxJSONResponse response = (BoxJSONResponse) request.send();
282        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
283        return new Info(jsonObject);
284    }
285
286    /**
287     * Gets information about all of the group memberships for this user.
288     * Does not support paging.
289     *
290     * <p>Note: This method is only available to enterprise admins.</p>
291     *
292     * @return a collection of information about the group memberships for this user.
293     */
294    public Collection<BoxGroupMembership.Info> getMemberships() {
295        BoxAPIConnection api = this.getAPI();
296        URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
297
298        BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
299        BoxJSONResponse response = (BoxJSONResponse) request.send();
300        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
301
302        int entriesCount = responseJSON.get("total_count").asInt();
303        Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);
304        JsonArray entries = responseJSON.get("entries").asArray();
305        for (JsonValue entry : entries) {
306            JsonObject entryObject = entry.asObject();
307            BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get("id").asString());
308            BoxGroupMembership.Info info = membership.new Info(entryObject);
309            memberships.add(info);
310        }
311
312        return memberships;
313    }
314
315    /**
316     * Gets information about all of the group memberships for this user as iterable with paging support.
317     * @param fields the fields to retrieve.
318     * @return an iterable with information about the group memberships for this user.
319     */
320    public Iterable<BoxGroupMembership.Info> getAllMemberships(String ... fields) {
321        final QueryStringBuilder builder = new QueryStringBuilder();
322        if (fields.length > 0) {
323            builder.appendParam("fields", fields);
324        }
325        return new Iterable<BoxGroupMembership.Info>() {
326            public Iterator<BoxGroupMembership.Info> iterator() {
327                URL url = USER_MEMBERSHIPS_URL_TEMPLATE.buildWithQuery(
328                        BoxUser.this.getAPI().getBaseURL(), builder.toString(), BoxUser.this.getID());
329                return new BoxGroupMembershipIterator(BoxUser.this.getAPI(), url);
330            }
331        };
332    }
333
334    /**
335     * Adds a new email alias to this user's account.
336     * @param  email the email address to add as an alias.
337     * @return       the newly created email alias.
338     */
339    public EmailAlias addEmailAlias(String email) {
340        URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
341        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
342
343        JsonObject requestJSON = new JsonObject()
344            .add("email", email);
345        request.setBody(requestJSON.toString());
346        BoxJSONResponse response = (BoxJSONResponse) request.send();
347        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
348        return new EmailAlias(responseJSON);
349    }
350
351    /**
352     * Deletes an email alias from this user's account.
353     *
354     * <p>The IDs of the user's email aliases can be found by calling {@link #getEmailAliases}.</p>
355     *
356     * @param emailAliasID the ID of the email alias to delete.
357     */
358    public void deleteEmailAlias(String emailAliasID) {
359        URL url = EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID);
360        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
361        BoxAPIResponse response = request.send();
362        response.disconnect();
363    }
364
365    /**
366     * Gets a collection of all the email aliases for this user.
367     *
368     * <p>Note that the user's primary login email is not included in the collection of email aliases.</p>
369     *
370     * @return a collection of all the email aliases for this user.
371     */
372    public Collection<EmailAlias> getEmailAliases() {
373        URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
374        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
375        BoxJSONResponse response = (BoxJSONResponse) request.send();
376        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
377
378        int totalCount = responseJSON.get("total_count").asInt();
379        Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);
380        JsonArray entries = responseJSON.get("entries").asArray();
381        for (JsonValue value : entries) {
382            JsonObject emailAliasJSON = value.asObject();
383            emailAliases.add(new EmailAlias(emailAliasJSON));
384        }
385
386        return emailAliases;
387    }
388
389    /**
390     * Deletes a user from an enterprise account.
391     * @param notifyUser whether or not to send an email notification to the user that their account has been deleted.
392     * @param force      whether or not this user should be deleted even if they still own files.
393     */
394    public void delete(boolean notifyUser, boolean force) {
395        String queryString = new QueryStringBuilder()
396            .appendParam("notify", String.valueOf(notifyUser))
397            .appendParam("force", String.valueOf(force))
398            .toString();
399
400        URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
401        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
402        BoxAPIResponse response = request.send();
403        response.disconnect();
404    }
405
406    /**
407     * Updates the information about this user with any info fields that have been modified locally.
408     *
409     * <p>Note: This method is only available to enterprise admins.</p>
410     *
411     * @param info info the updated info.
412     */
413    public void updateInfo(BoxUser.Info info) {
414        URL url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
415        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
416        request.setBody(info.getPendingChanges());
417        BoxJSONResponse response = (BoxJSONResponse) request.send();
418        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
419        info.update(jsonObject);
420    }
421
422    /**
423     * Moves all of the owned content from within one user’s folder into a new folder in another user's account.
424     * You can move folders across users as long as the you have administrative permissions and the 'source'
425     * user owns the folders. Per the documentation at the link below, this will move everything from the root
426     * folder, as this is currently the only mode of operation supported.
427     *
428     * See also https://box-content.readme.io/reference#move-folder-into-another-users-folder
429     *
430     * @param sourceUserID the user id of the user whose files will be the source for this operation
431     * @return info for the newly created folder
432     */
433    public BoxFolder.Info moveFolderToUser(String sourceUserID) {
434        // Currently the API only supports moving of the root folder (0), hence the hard coded "0"
435        URL url = MOVE_FOLDER_TO_USER_TEMPLATE.build(this.getAPI().getBaseURL(), sourceUserID, "0");
436        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
437        JsonObject idValue = new JsonObject();
438        idValue.add("id", this.getID());
439        JsonObject ownedBy = new JsonObject();
440        ownedBy.add("owned_by", idValue);
441        request.setBody(ownedBy.toString());
442        BoxJSONResponse response = (BoxJSONResponse) request.send();
443        JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
444        BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
445        response.disconnect();
446
447        return movedFolder.new Info(responseJSON);
448    }
449
450    /**
451     * Enumerates the possible roles that a user can have within an enterprise.
452     */
453    public enum Role {
454        /**
455         * The user is an administrator of their enterprise.
456         */
457        ADMIN ("admin"),
458
459        /**
460         * The user is a co-administrator of their enterprise.
461         */
462        COADMIN ("coadmin"),
463
464        /**
465         * The user is a regular user within their enterprise.
466         */
467        USER ("user");
468
469        private final String jsonValue;
470
471        private Role(String jsonValue) {
472            this.jsonValue = jsonValue;
473        }
474
475        static Role fromJSONValue(String jsonValue) {
476            return Role.valueOf(jsonValue.toUpperCase());
477        }
478
479        String toJSONValue() {
480            return this.jsonValue;
481        }
482    }
483
484    /**
485     * Enumerates the possible statuses that a user's account can have.
486     */
487    public enum Status {
488        /**
489         * The user's account is active.
490         */
491        ACTIVE ("active"),
492
493        /**
494         * The user's account is inactive.
495         */
496        INACTIVE ("inactive"),
497
498        /**
499         * The user's account cannot delete or edit content.
500         */
501        CANNOT_DELETE_EDIT ("cannot_delete_edit"),
502
503        /**
504         * The user's account cannot delete, edit, or upload content.
505         */
506        CANNOT_DELETE_EDIT_UPLOAD ("cannot_delete_edit_upload");
507
508        private final String jsonValue;
509
510        private Status(String jsonValue) {
511            this.jsonValue = jsonValue;
512        }
513
514        static Status fromJSONValue(String jsonValue) {
515            return Status.valueOf(jsonValue.toUpperCase());
516        }
517
518        String toJSONValue() {
519            return this.jsonValue;
520        }
521    }
522
523    /**
524     * Contains information about a BoxUser.
525     */
526    public class Info extends BoxCollaborator.Info {
527        private String login;
528        private Role role;
529        private String language;
530        private String timezone;
531        private long spaceAmount;
532        private long spaceUsed;
533        private long maxUploadSize;
534        private boolean canSeeManagedUsers;
535        private boolean isSyncEnabled;
536        private boolean isExternalCollabRestricted;
537        private Status status;
538        private String jobTitle;
539        private String phone;
540        private String address;
541        private String avatarURL;
542        private boolean isExemptFromDeviceLimits;
543        private boolean isExemptFromLoginVerification;
544        private boolean isPasswordResetRequired;
545        private boolean isPlatformAccessOnly;
546        private String externalAppUserId;
547        private BoxEnterprise enterprise;
548        private List<String> myTags;
549        private String hostname;
550
551        /**
552         * Constructs an empty Info object.
553         */
554        public Info() {
555            super();
556        }
557
558        Info(JsonObject jsonObject) {
559            super(jsonObject);
560        }
561
562        @Override
563        public BoxUser getResource() {
564            return BoxUser.this;
565        }
566
567        /**
568         * Gets the email address the user uses to login.
569         * @return the email address the user uses to login.
570         */
571        public String getLogin() {
572            return this.login;
573        }
574
575        /**
576         * Sets the email address the user uses to login. The new login must be one of the user's already confirmed
577         * email aliases.
578         * @param  login one of the user's confirmed email aliases.
579         */
580        public void setLogin(String login) {
581            this.login = login;
582            this.addPendingChange("login", login);
583        }
584
585        /**
586         * Gets the user's enterprise role.
587         * @return the user's enterprise role.
588         */
589        public Role getRole() {
590            return this.role;
591        }
592
593        /**
594         * Sets the user's role in their enterprise.
595         * @param role the user's new role in their enterprise.
596         */
597        public void setRole(Role role) {
598            this.role = role;
599            this.addPendingChange("role", role.name().toLowerCase());
600        }
601
602        /**
603         * Gets the language of the user.
604         * @return the language of the user.
605         */
606        public String getLanguage() {
607            return this.language;
608        }
609
610        /**
611         * Sets the language of the user.
612         * @param language the new language of the user.
613         */
614        public void setLanguage(String language) {
615            this.language = language;
616            this.addPendingChange("language", language);
617        }
618
619        /**
620         * Gets the timezone of the user.
621         * @return the timezone of the user.
622         */
623        public String getTimezone() {
624            return this.timezone;
625        }
626
627        /**
628         * Sets the timezone of the user.
629         * @param timezone the new timezone of the user.
630         */
631        public void setTimezone(String timezone) {
632            this.timezone = timezone;
633            this.addPendingChange("timezone", timezone);
634        }
635
636        /**
637         * Gets the user's total available space in bytes.
638         * @return the user's total available space in bytes.
639         */
640        public long getSpaceAmount() {
641            return this.spaceAmount;
642        }
643
644        /**
645         * Sets the user's total available space in bytes.
646         * @param spaceAmount the new amount of space available to the user in bytes, or -1 for unlimited storage.
647         */
648        public void setSpaceAmount(long spaceAmount) {
649            this.spaceAmount = spaceAmount;
650            this.addPendingChange("space_amount", spaceAmount);
651        }
652
653        /**
654         * Gets the amount of space the user has used in bytes.
655         * @return the amount of space the user has used in bytes.
656         */
657        public long getSpaceUsed() {
658            return this.spaceUsed;
659        }
660
661        /**
662         * Gets the maximum individual file size in bytes the user can have.
663         * @return the maximum individual file size in bytes the user can have.
664         */
665        public long getMaxUploadSize() {
666            return this.maxUploadSize;
667        }
668
669        /**
670         * Gets the user's current account status.
671         * @return the user's current account status.
672         */
673        public Status getStatus() {
674            return this.status;
675        }
676
677        /**
678         * Sets the user's current account status.
679         * @param status the user's new account status.
680         */
681        public void setStatus(Status status) {
682            this.status = status;
683            this.addPendingChange("status", status.name().toLowerCase());
684        }
685
686        /**
687         * Gets the job title of the user.
688         * @return the job title of the user.
689         */
690        public String getJobTitle() {
691            return this.jobTitle;
692        }
693
694        /**
695         * Sets the job title of the user.
696         * @param jobTitle the new job title of the user.
697         */
698        public void setJobTitle(String jobTitle) {
699            this.jobTitle = jobTitle;
700            this.addPendingChange("job_title", jobTitle);
701        }
702
703        /**
704         * Gets the phone number of the user.
705         * @return the phone number of the user.
706         */
707        public String getPhone() {
708            return this.phone;
709        }
710
711        /**
712         * Sets the phone number of the user.
713         * @param phone the new phone number of the user.
714         */
715        public void setPhone(String phone) {
716            this.phone = phone;
717            this.addPendingChange("phone", phone);
718        }
719
720        /**
721         * Gets the address of the user.
722         * @return the address of the user.
723         */
724        public String getAddress() {
725            return this.address;
726        }
727
728        /**
729         * Sets the address of the user.
730         * @param address the new address of the user.
731         */
732        public void setAddress(String address) {
733            this.address = address;
734            this.addPendingChange("address", address);
735        }
736
737        /**
738         * Gets the URL of the user's avatar.
739         * @return the URL of the user's avatar.
740         */
741        public String getAvatarURL() {
742            return this.avatarURL;
743        }
744
745        /**
746         * Gets the enterprise that the user belongs to.
747         * @return the enterprise that the user belongs to.
748         */
749        public BoxEnterprise getEnterprise() {
750            return this.enterprise;
751        }
752
753        /**
754         * Removes the user from their enterprise and converts them to a standalone free user.
755         */
756        public void removeEnterprise() {
757            this.removeChildObject("enterprise");
758            this.enterprise = null;
759            this.addChildObject("enterprise", null);
760        }
761
762        /**
763         * Gets whether or not the user can use Box Sync.
764         * @return true if the user can use Box Sync; otherwise false.
765         */
766        public boolean getIsSyncEnabled() {
767            return this.isSyncEnabled;
768        }
769
770        /**
771         * Gets whether this user is allowed to collaborate with users outside their enterprise.
772         * @return true if this user is allowed to collaborate with users outside their enterprise; otherwise false.
773         */
774        public boolean getIsExternalCollabRestricted() {
775            return this.isExternalCollabRestricted;
776        }
777
778        /**
779         * Sets whether or not the user can use Box Sync.
780         * @param enabled whether or not the user can use Box Sync.
781         */
782        public void setIsSyncEnabled(boolean enabled) {
783            this.isSyncEnabled = enabled;
784            this.addPendingChange("is_sync_enabled", enabled);
785        }
786
787        /**
788         * Gets whether or not the user can see other enterprise users in their contact list.
789         * @return true if the user can see other enterprise users in their contact list; otherwise false.
790         */
791        public boolean getCanSeeManagedUsers() {
792            return this.canSeeManagedUsers;
793        }
794
795        /**
796         * Sets whether or not the user can see other enterprise users in their contact list.
797         * @param canSeeManagedUsers whether or not the user can see other enterprise users in their contact list.
798         */
799        public void setCanSeeManagedUsers(boolean canSeeManagedUsers) {
800            this.canSeeManagedUsers = canSeeManagedUsers;
801            this.addPendingChange("can_see_managed_users", canSeeManagedUsers);
802        }
803
804        /**
805         * Gets whether or not the user is exempt from enterprise device limits.
806         * @return true if the user is exempt from enterprise device limits; otherwise false.
807         */
808        public boolean getIsExemptFromDeviceLimits() {
809            return this.isExemptFromDeviceLimits;
810        }
811
812        /**
813         * Sets whether or not the user is exempt from enterprise device limits.
814         * @param isExemptFromDeviceLimits whether or not the user is exempt from enterprise device limits.
815         */
816        public void setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLimits) {
817            this.isExemptFromDeviceLimits = isExemptFromDeviceLimits;
818            this.addPendingChange("is_exempt_from_device_limits", isExemptFromDeviceLimits);
819        }
820
821        /**
822         * Gets whether or not the user must use two-factor authentication.
823         * @return true if the user must use two-factor authentication; otherwise false.
824         */
825        public boolean getIsExemptFromLoginVerification() {
826            return this.isExemptFromLoginVerification;
827        }
828
829        /**
830         * Sets whether or not the user must use two-factor authentication.
831         * @param isExemptFromLoginVerification whether or not the user must use two-factor authentication.
832         */
833        public void setIsExemptFromLoginVerification(boolean isExemptFromLoginVerification) {
834            this.isExemptFromLoginVerification = isExemptFromLoginVerification;
835            this.addPendingChange("is_exempt_from_login_verification", isExemptFromLoginVerification);
836        }
837
838        /**
839         * Gets whether or not the user is required to reset password.
840         * @return true if the user is required to reset password; otherwise false.
841         */
842        public boolean getIsPasswordResetRequired() {
843            return this.isPasswordResetRequired;
844        }
845
846        /**
847         * Sets whether or not the user is required to reset password.
848         * @param isPasswordResetRequired whether or not the user is required to reset password.
849         */
850        public void setIsPasswordResetRequired(boolean isPasswordResetRequired) {
851            this.isPasswordResetRequired = isPasswordResetRequired;
852            this.addPendingChange("is_password_reset_required", isPasswordResetRequired);
853        }
854
855        /**
856         * Gets whether or not the user we are creating is an app user with Box Developer Edition.
857         * @return true if the new user is an app user for Box Developer Addition; otherwise false.
858         */
859        public boolean getIsPlatformAccessOnly() {
860            return this.isPlatformAccessOnly;
861        }
862
863        /**
864         * Gets the external app user id that has been set for the app user.
865         * @return the external app user id.
866         */
867        public String getExternalAppUserId() {
868            return this.externalAppUserId;
869        }
870
871        /**
872         * Sets the external app user id.
873         * @param externalAppUserId external app user id.
874         */
875        public void setExternalAppUserId(String externalAppUserId) {
876            this.externalAppUserId = externalAppUserId;
877            this.addPendingChange("external_app_user_id", externalAppUserId);
878        }
879
880        /**
881         * Gets the tags for all files and folders owned by this user.
882         * @return the tags for all files and folders owned by this user.
883         */
884        public List<String> getMyTags() {
885            return this.myTags;
886        }
887
888        /**
889         * Gets the root (protocol, subdomain, domain) of any links that need to be generated for this user.
890         * @return the root (protocol, subdomain, domain) of any links that need to be generated for this user.
891         */
892        public String getHostname() {
893            return this.hostname;
894        }
895
896        @Override
897        protected void parseJSONMember(JsonObject.Member member) {
898            super.parseJSONMember(member);
899
900            JsonValue value = member.getValue();
901            String memberName = member.getName();
902            if (memberName.equals("login")) {
903                this.login = value.asString();
904            } else if (memberName.equals("role")) {
905                this.role = Role.fromJSONValue(value.asString());
906            } else if (memberName.equals("language")) {
907                this.language = value.asString();
908            } else if (memberName.equals("timezone")) {
909                this.timezone = value.asString();
910            } else if (memberName.equals("space_amount")) {
911                this.spaceAmount = Double.valueOf(value.toString()).longValue();
912            } else if (memberName.equals("space_used")) {
913                this.spaceUsed = Double.valueOf(value.toString()).longValue();
914            } else if (memberName.equals("max_upload_size")) {
915                this.maxUploadSize = Double.valueOf(value.toString()).longValue();
916            } else if (memberName.equals("status")) {
917                this.status = Status.fromJSONValue(value.asString());
918            } else if (memberName.equals("job_title")) {
919                this.jobTitle = value.asString();
920            } else if (memberName.equals("phone")) {
921                this.phone = value.asString();
922            } else if (memberName.equals("address")) {
923                this.address = value.asString();
924            } else if (memberName.equals("avatar_url")) {
925                this.avatarURL = value.asString();
926            } else if (memberName.equals("can_see_managed_users")) {
927                this.canSeeManagedUsers = value.asBoolean();
928            } else if (memberName.equals("is_sync_enabled")) {
929                this.isSyncEnabled = value.asBoolean();
930            } else if (memberName.equals("is_external_collab_restricted")) {
931                this.isExternalCollabRestricted = value.asBoolean();
932            } else if (memberName.equals("is_exempt_from_device_limits")) {
933                this.isExemptFromDeviceLimits = value.asBoolean();
934            } else if (memberName.equals("is_exempt_from_login_verification")) {
935                this.isExemptFromLoginVerification = value.asBoolean();
936            } else if (memberName.equals("is_password_reset_required")) {
937                this.isPasswordResetRequired = value.asBoolean();
938            } else if (memberName.equals("is_platform_access_only")) {
939                this.isPlatformAccessOnly = value.asBoolean();
940            } else if (memberName.equals("external_app_user_id")) {
941                this.externalAppUserId = value.asString();
942            } else if (memberName.equals("enterprise")) {
943                JsonObject jsonObject = value.asObject();
944                if (this.enterprise == null) {
945                    this.enterprise = new BoxEnterprise(jsonObject);
946                } else {
947                    this.enterprise.update(jsonObject);
948                }
949            } else if (memberName.equals("my_tags")) {
950                this.myTags = this.parseMyTags(value.asArray());
951            } else if (memberName.equals("hostname")) {
952                this.hostname = value.asString();
953            }
954        }
955
956        private List<String> parseMyTags(JsonArray jsonArray) {
957            List<String> myTags = new ArrayList<String>(jsonArray.size());
958            for (JsonValue value : jsonArray) {
959                myTags.add(value.asString());
960            }
961
962            return myTags;
963        }
964    }
965}