001package com.box.sdk;
002
003import com.eclipsesource.json.Json;
004import com.eclipsesource.json.JsonArray;
005import com.eclipsesource.json.JsonObject;
006import com.eclipsesource.json.JsonValue;
007import java.io.InputStream;
008import java.net.URL;
009import java.util.ArrayList;
010import java.util.Collection;
011import java.util.HashMap;
012import java.util.Iterator;
013import java.util.List;
014import java.util.Map;
015
016/**
017 * Represents a Box user account.
018 *
019 * <p>Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked
020 * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error
021 * handling for errors related to the Box REST API, you should capture this exception explicitly.</p>
022 */
023@BoxResourceType("user")
024public class BoxUser extends BoxCollaborator {
025
026    /**
027     * An array of all possible file fields that can be requested when calling {@link #getInfo(String...)}.
028     */
029    public static final String[] ALL_FIELDS = {"type", "id", "name", "login", "created_at", "modified_at", "role",
030        "language", "timezone", "space_amount", "space_used", "max_upload_size", "tracking_codes",
031        "can_see_managed_users", "is_sync_enabled", "is_external_collab_restricted", "status", "job_title", "phone",
032        "address", "avatar_url", "is_exempt_from_device_limits", "is_exempt_from_login_verification", "enterprise",
033        "my_tags", "hostname", "is_platform_access_only", "external_app_user_id"};
034
035    /**
036     * User URL Template.
037     */
038    public static final URLTemplate USER_URL_TEMPLATE = new URLTemplate("users/%s");
039    /**
040     * Get Me URL Template.
041     */
042    public static final URLTemplate GET_ME_URL = new URLTemplate("users/me");
043    /**
044     * Users URL Template.
045     */
046    public static final URLTemplate USERS_URL_TEMPLATE = new URLTemplate("users");
047    /**
048     * User Memberships URL Template.
049     */
050    public static final URLTemplate USER_MEMBERSHIPS_URL_TEMPLATE = new URLTemplate("users/%s/memberships");
051    /**
052     * E-Mail Alias URL Template.
053     */
054    public static final URLTemplate EMAIL_ALIAS_URL_TEMPLATE = new URLTemplate("users/%s/email_aliases/%s");
055    /**
056     * E-Mail Aliases URL Template.
057     */
058    public static final URLTemplate EMAIL_ALIASES_URL_TEMPLATE = new URLTemplate("users/%s/email_aliases");
059    /**
060     * Move Folder To User Template.
061     */
062    public static final URLTemplate MOVE_FOLDER_TO_USER_TEMPLATE = new URLTemplate("users/%s/folders/%s");
063    /**
064     * User Avatar Template.
065     */
066    public static final URLTemplate USER_AVATAR_TEMPLATE = new URLTemplate("users/%s/avatar");
067
068    /**
069     * Constructs a BoxUser for a user with a given ID.
070     *
071     * @param api the API connection to be used by the user.
072     * @param id  the ID of the user.
073     */
074    public BoxUser(BoxAPIConnection api, String id) {
075        super(api, id);
076    }
077
078    /**
079     * Provisions a new app user in an enterprise using Box Developer Edition.
080     *
081     * @param api  the API connection to be used by the created user.
082     * @param name the name of the user.
083     * @return the created user's info.
084     */
085    public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {
086        return createAppUser(api, name, new CreateUserParams());
087    }
088
089    /**
090     * Provisions a new app user in an enterprise with additional user information using Box Developer Edition.
091     *
092     * @param api    the API connection to be used by the created user.
093     * @param name   the name of the user.
094     * @param params additional user information.
095     * @return the created user's info.
096     */
097    public static BoxUser.Info createAppUser(BoxAPIConnection api, String name,
098                                             CreateUserParams params) {
099
100        params.setIsPlatformAccessOnly(true);
101        return createEnterpriseUser(api, null, name, params);
102    }
103
104    /**
105     * Provisions a new user in an enterprise.
106     *
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     * @return the created user's info.
111     */
112    public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {
113        return createEnterpriseUser(api, login, name, null);
114    }
115
116    /**
117     * Provisions a new user in an enterprise with additional user information.
118     *
119     * @param api    the API connection to be used by the created user.
120     * @param login  the email address the user will use to login.
121     * @param name   the name of the user.
122     * @param params additional user information.
123     * @return the created user's info.
124     */
125    public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name,
126                                                    CreateUserParams params) {
127
128        JsonObject requestJSON = new JsonObject();
129        requestJSON.add("login", login);
130        requestJSON.add("name", name);
131
132        if (params != null) {
133            if (params.getRole() != null) {
134                requestJSON.add("role", params.getRole().toJSONValue());
135            }
136
137            if (params.getStatus() != null) {
138                requestJSON.add("status", params.getStatus().toJSONValue());
139            }
140
141            requestJSON.add("language", params.getLanguage());
142            requestJSON.add("is_sync_enabled", params.getIsSyncEnabled());
143            requestJSON.add("job_title", params.getJobTitle());
144            requestJSON.add("phone", params.getPhone());
145            requestJSON.add("address", params.getAddress());
146            requestJSON.add("space_amount", params.getSpaceAmount());
147            requestJSON.add("can_see_managed_users", params.getCanSeeManagedUsers());
148            requestJSON.add("timezone", params.getTimezone());
149            requestJSON.add("is_exempt_from_device_limits", params.getIsExemptFromDeviceLimits());
150            requestJSON.add("is_exempt_from_login_verification", params.getIsExemptFromLoginVerification());
151            requestJSON.add("is_platform_access_only", params.getIsPlatformAccessOnly());
152            requestJSON.add("external_app_user_id", params.getExternalAppUserId());
153            requestJSON.add("is_external_collab_restricted", params.getIsExternalCollabRestricted());
154            if (params.getTrackingCodes() != null) {
155                requestJSON.add("tracking_codes", toTrackingCodesJson(params.getTrackingCodes()));
156            }
157        }
158
159        URL url = USERS_URL_TEMPLATE.build(api.getBaseURL());
160        BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
161        request.setBody(requestJSON.toString());
162        BoxJSONResponse response = (BoxJSONResponse) request.send();
163        JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
164
165        BoxUser createdUser = new BoxUser(api, responseJSON.get("id").asString());
166        return createdUser.new Info(responseJSON);
167    }
168
169    /**
170     * Gets the current user.
171     *
172     * @param api the API connection of the current user.
173     * @return the current user.
174     */
175    public static BoxUser getCurrentUser(BoxAPIConnection api) {
176        URL url = GET_ME_URL.build(api.getBaseURL());
177        BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
178        BoxJSONResponse response = (BoxJSONResponse) request.send();
179        JsonObject jsonObject = Json.parse(response.getJSON()).asObject();
180        return new BoxUser(api, jsonObject.get("id").asString());
181    }
182
183    /**
184     * Returns an iterable containing all the enterprise users.
185     *
186     * @param api the API connection to be used when retrieving the users.
187     * @return an iterable containing all the enterprise users.
188     */
189    public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api) {
190        return getAllEnterpriseUsers(api, false, null);
191    }
192
193
194    /**
195     * Returns an iterable containing all the enterprise users. Uses marker based pagination.
196     *
197     * @param api       the API connection to be used when retrieving the users.
198     * @param usemarker Boolean that determines whether to use marker based pagination.
199     * @param marker    The marker at which the iterator will begin.
200     * @return an iterable containing all the enterprise users.
201     */
202    public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api, final boolean usemarker,
203                                                               final String marker) {
204        return getUsersInfoForType(api, null, null, null, usemarker, marker);
205    }
206
207    /**
208     * Returns an iterable containing all the enterprise users that matches the filter and specifies which child fields
209     * to retrieve from the API.
210     *
211     * @param api        the API connection to be used when retrieving the users.
212     * @param filterTerm used to filter the results to only users starting with this string in either the name or the
213     *                   login. Can be null to not filter the results.
214     * @param fields     the fields to retrieve. Leave this out for the standard fields.
215     * @return an iterable containing all the enterprise users that matches the filter.
216     */
217    public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api, final String filterTerm,
218                                                               final String... fields) {
219        return getUsersInfoForType(api, filterTerm, null, null, false, null, fields);
220    }
221
222    /**
223     * Returns an iterable containing all the enterprise users that matches the filter and specifies which child fields
224     * to retrieve from the API. Uses marker based pagination.
225     *
226     * @param api        the API connection to be used when retrieving the users.
227     * @param filterTerm used to filter the results to only users starting with this string in either the name or the
228     *                   login. Can be null to not filter the results.
229     * @param usemarker  Boolean that determines whether to use marker based pagination.
230     * @param marker     The marker at which the iterator will begin.
231     * @param fields     the fields to retrieve. Leave this out for the standard fields.
232     * @return an iterable containing all the enterprise users that matches the filter.
233     */
234    public static Iterable<BoxUser.Info> getAllEnterpriseUsers(
235        final BoxAPIConnection api,
236        final String filterTerm,
237        final boolean usemarker,
238        final String marker,
239        final String... fields
240    ) {
241        return getUsersInfoForType(api, filterTerm, null, null, usemarker, marker, fields);
242    }
243
244    /**
245     * Gets a limited set of information about an external user. (A user collaborating
246     * on content owned by the enterprise). Note: Only fields the user has permission to
247     * see will be returned with values. Other fields will return a value of null.
248     *
249     * @param api        the API connection to be used when retrieving the users.
250     * @param filterTerm used to filter the results to only users matching the given login.
251     *                   This does exact match only, so if no filter term is passed in, nothing
252     *                   will be returned.
253     * @param fields     the fields to retrieve. Leave this out for the standard fields.
254     * @return an iterable containing external users matching the given email
255     */
256    public static Iterable<BoxUser.Info> getExternalUsers(final BoxAPIConnection api, final String filterTerm,
257                                                          final String... fields) {
258        return getUsersInfoForType(api, filterTerm, "external", null, false, null, fields);
259    }
260
261    /**
262     * Gets a limited set of information about an external user. (A user collaborating
263     * on content owned by the enterprise). Note: Only fields the user has permission to
264     * see will be returned with values. Other fields will return a value of null. Uses marker based pagination.
265     *
266     * @param api        the API connection to be used when retrieving the users.
267     * @param filterTerm used to filter the results to only users matching the given login.
268     *                   This does exact match only, so if no filter term is passed in, nothing
269     *                   will be returned.
270     * @param usemarker  Boolean that determines whether to use marker based pagination.
271     * @param marker     The marker at which the iterator will begin.
272     * @param fields     the fields to retrieve. Leave this out for the standard fields.
273     * @return an iterable containing external users matching the given email
274     */
275    public static Iterable<BoxUser.Info> getExternalUsers(
276        final BoxAPIConnection api,
277        final String filterTerm,
278        final boolean usemarker,
279        final String marker,
280        final String... fields
281    ) {
282        return getUsersInfoForType(api, filterTerm, "external", null, usemarker, marker, fields);
283    }
284
285    /**
286     * Gets any managed users that match the filter term as well as any external users that
287     * match the filter term. For managed users it matches any users names or emails that
288     * start with the term. For external, it only does full match on email. This method
289     * is ideal to use in the case where you have a full email for a user and you don't
290     * know if they're managed or external.
291     *
292     * @param api        the API connection to be used when retrieving the users.
293     * @param filterTerm The filter term to lookup users by (login for external, login or name for managed)
294     * @param fields     the fields to retrieve. Leave this out for the standard fields.
295     * @return an iterable containing users matching the given email
296     */
297    public static Iterable<BoxUser.Info> getAllEnterpriseOrExternalUsers(
298        final BoxAPIConnection api,
299        final String filterTerm,
300        final String... fields
301    ) {
302        return getUsersInfoForType(api, filterTerm, "all", null, false, null, fields);
303    }
304
305    /**
306     * Gets any managed users that match the filter term as well as any external users that
307     * match the filter term. For managed users it matches any users names or emails that
308     * start with the term. For external, it only does full match on email. This method
309     * is ideal to use in the case where you have a full email for a user and you don't
310     * know if they're managed or external. Uses marker based pagination.
311     *
312     * @param api        the API connection to be used when retrieving the users.
313     * @param filterTerm The filter term to lookup users by (login for external, login or name for managed)
314     * @param usemarker  Boolean that determines whether to use marker based pagination.
315     * @param marker     The marker at which the iterator will begin.
316     * @param fields     the fields to retrieve. Leave this out for the standard fields.
317     * @return an iterable containing users matching the given email
318     */
319    public static Iterable<BoxUser.Info> getAllEnterpriseOrExternalUsers(
320        final BoxAPIConnection api,
321        final String filterTerm,
322        final boolean usemarker,
323        final String marker,
324        final String... fields
325    ) {
326        return getUsersInfoForType(api, filterTerm, "all", null, usemarker, marker, fields);
327    }
328
329    /**
330     * Gets any app users that has an exact match with the externalAppUserId term.
331     *
332     * @param api               the API connection to be used when retrieving the users.
333     * @param externalAppUserId the external app user id that has been set for app user
334     * @param fields            the fields to retrieve. Leave this out for the standard fields.
335     * @return an iterable containing users matching the given email
336     */
337    public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(
338        final BoxAPIConnection api,
339        final String externalAppUserId,
340        final String... fields
341    ) {
342        return getUsersInfoForType(api, null, null, externalAppUserId, false, null, fields);
343    }
344
345    /**
346     * Gets any app users that has an exact match with the externalAppUserId term using marker based pagination.
347     *
348     * @param api               the API connection to be used when retrieving the users.
349     * @param externalAppUserId the external app user id that has been set for app user
350     * @param usemarker         Boolean that determines whether to use marker based pagination.
351     * @param marker            The marker at which the iterator will begin.
352     * @param fields            the fields to retrieve. Leave this out for the standard fields.
353     * @return an iterable containing users matching the given email
354     */
355    public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(
356        final BoxAPIConnection api,
357        final String externalAppUserId,
358        final boolean usemarker,
359        String marker,
360        final String... fields
361    ) {
362        return getUsersInfoForType(api, null, null, externalAppUserId, usemarker, marker, fields);
363    }
364
365    /**
366     * Helper method to abstract out the common logic from the various users methods.
367     *
368     * @param api               the API connection to be used when retrieving the users.
369     * @param filterTerm        The filter term to lookup users by (login for external, login or name for managed)
370     * @param userType          The type of users we want to search with this request.
371     *                          Valid values are 'managed' (enterprise users), 'external' or 'all'
372     * @param externalAppUserId the external app user id that has been set for an app user
373     * @param usemarker         Boolean that determines whether to use marker based pagination.
374     * @param marker            The marker at which the iterator will begin.
375     * @param fields            the fields to retrieve. Leave this out for the standard fields.
376     * @return An iterator over the selected users.
377     */
378    private static Iterable<BoxUser.Info> getUsersInfoForType(
379        final BoxAPIConnection api,
380        final String filterTerm,
381        final String userType,
382        final String externalAppUserId,
383        final boolean usemarker,
384        final String marker,
385        final String... fields
386    ) {
387
388        final QueryStringBuilder builder = new QueryStringBuilder();
389        if (filterTerm != null) {
390            builder.appendParam("filter_term", filterTerm);
391        }
392        if (userType != null) {
393            builder.appendParam("user_type", userType);
394        }
395        if (externalAppUserId != null) {
396            builder.appendParam("external_app_user_id", externalAppUserId);
397        }
398        if (usemarker) {
399            builder.appendParam("usemarker", "true");
400        }
401        if (fields.length > 0) {
402            builder.appendParam("fields", fields);
403        }
404        final URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
405
406        if (usemarker) {
407            return new BoxResourceIterable<BoxUser.Info>(api, url, 100, null, marker) {
408                @Override
409                protected BoxUser.Info factory(JsonObject jsonObject) {
410                    BoxUser user = new BoxUser(api, jsonObject.get("id").asString());
411                    return user.new Info(jsonObject);
412                }
413            };
414        } else {
415            return new Iterable<BoxUser.Info>() {
416                public Iterator<BoxUser.Info> iterator() {
417                    return new BoxUserIterator(api, url);
418                }
419            };
420        }
421    }
422
423    private static JsonArray toTrackingCodesJson(Map<String, String> trackingCodes) {
424        JsonArray trackingCodesJsonArray = new JsonArray();
425        for (String attrKey : trackingCodes.keySet()) {
426            JsonObject trackingCode = new JsonObject();
427            trackingCode.set("type", "tracking_code");
428            trackingCode.set("name", attrKey);
429            trackingCode.set("value", trackingCodes.get(attrKey));
430            trackingCodesJsonArray.add(trackingCode);
431        }
432        return trackingCodesJsonArray;
433    }
434
435    /**
436     * Gets information about this user.
437     *
438     * @param fields the optional fields to retrieve.
439     * @return info about this user.
440     */
441    public BoxUser.Info getInfo(String... fields) {
442        URL url;
443        if (fields.length > 0) {
444            String queryString = new QueryStringBuilder().appendParam("fields", fields).toString();
445            url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
446        } else {
447            url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
448        }
449        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
450        BoxJSONResponse response = (BoxJSONResponse) request.send();
451        JsonObject jsonObject = Json.parse(response.getJSON()).asObject();
452        return new Info(jsonObject);
453    }
454
455    /**
456     * Gets information about all of the group memberships for this user.
457     * Does not support paging.
458     *
459     * <p>Note: This method is only available to enterprise admins.</p>
460     *
461     * @return a collection of information about the group memberships for this user.
462     */
463    public Collection<BoxGroupMembership.Info> getMemberships() {
464        BoxAPIConnection api = this.getAPI();
465        URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
466
467        BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
468        BoxJSONResponse response = (BoxJSONResponse) request.send();
469        JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
470
471        int entriesCount = responseJSON.get("total_count").asInt();
472        Collection<BoxGroupMembership.Info> memberships = new ArrayList<>(entriesCount);
473        JsonArray entries = responseJSON.get("entries").asArray();
474        for (JsonValue entry : entries) {
475            JsonObject entryObject = entry.asObject();
476            BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get("id").asString());
477            BoxGroupMembership.Info info = membership.new Info(entryObject);
478            memberships.add(info);
479        }
480
481        return memberships;
482    }
483
484    /**
485     * Gets information about all of the group memberships for this user as iterable with paging support.
486     *
487     * @param fields the fields to retrieve.
488     * @return an iterable with information about the group memberships for this user.
489     */
490    public Iterable<BoxGroupMembership.Info> getAllMemberships(String... fields) {
491        final QueryStringBuilder builder = new QueryStringBuilder();
492        if (fields.length > 0) {
493            builder.appendParam("fields", fields);
494        }
495        return new Iterable<BoxGroupMembership.Info>() {
496            public Iterator<BoxGroupMembership.Info> iterator() {
497                URL url = USER_MEMBERSHIPS_URL_TEMPLATE.buildWithQuery(
498                    BoxUser.this.getAPI().getBaseURL(), builder.toString(), BoxUser.this.getID());
499                return new BoxGroupMembershipIterator(BoxUser.this.getAPI(), url);
500            }
501        };
502    }
503
504    /**
505     * Adds a new email alias to this user's account.
506     *
507     * @param email the email address to add as an alias.
508     * @return the newly created email alias.
509     */
510    public EmailAlias addEmailAlias(String email) {
511        return this.addEmailAlias(email, false);
512    }
513
514    /**
515     * Adds a new email alias to this user's account and confirms it without user interaction.
516     * This functionality is only available for enterprise admins.
517     *
518     * @param email       the email address to add as an alias.
519     * @param isConfirmed whether or not the email alias should be automatically confirmed.
520     * @return the newly created email alias.
521     */
522    public EmailAlias addEmailAlias(String email, boolean isConfirmed) {
523        URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
524        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
525
526        JsonObject requestJSON = new JsonObject()
527            .add("email", email);
528
529        if (isConfirmed) {
530            requestJSON.add("is_confirmed", isConfirmed);
531        }
532
533        request.setBody(requestJSON.toString());
534        BoxJSONResponse response = (BoxJSONResponse) request.send();
535        JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
536        return new EmailAlias(responseJSON);
537    }
538
539    /**
540     * Deletes an email alias from this user's account.
541     *
542     * <p>The IDs of the user's email aliases can be found by calling {@link #getEmailAliases}.</p>
543     *
544     * @param emailAliasID the ID of the email alias to delete.
545     */
546    public void deleteEmailAlias(String emailAliasID) {
547        URL url = EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID);
548        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
549        BoxAPIResponse response = request.send();
550        response.disconnect();
551    }
552
553    /**
554     * Gets a collection of all the email aliases for this user.
555     *
556     * <p>Note that the user's primary login email is not included in the collection of email aliases.</p>
557     *
558     * @return a collection of all the email aliases for this user.
559     */
560    public Collection<EmailAlias> getEmailAliases() {
561        URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
562        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
563        BoxJSONResponse response = (BoxJSONResponse) request.send();
564        JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
565
566        int totalCount = responseJSON.get("total_count").asInt();
567        Collection<EmailAlias> emailAliases = new ArrayList<>(totalCount);
568        JsonArray entries = responseJSON.get("entries").asArray();
569        for (JsonValue value : entries) {
570            JsonObject emailAliasJSON = value.asObject();
571            emailAliases.add(new EmailAlias(emailAliasJSON));
572        }
573
574        return emailAliases;
575    }
576
577    /**
578     * Deletes a user from an enterprise account.
579     *
580     * @param notifyUser whether or not to send an email notification to the user that their account has been deleted.
581     * @param force      whether or not this user should be deleted even if they still own files.
582     */
583    public void delete(boolean notifyUser, boolean force) {
584        String queryString = new QueryStringBuilder()
585            .appendParam("notify", String.valueOf(notifyUser))
586            .appendParam("force", String.valueOf(force))
587            .toString();
588
589        URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
590        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
591        BoxAPIResponse response = request.send();
592        response.disconnect();
593    }
594
595    /**
596     * Updates the information about this user with any info fields that have been modified locally.
597     *
598     * <p>Note: This method is only available to enterprise admins.</p>
599     *
600     * @param info info the updated info.
601     */
602    public void updateInfo(BoxUser.Info info) {
603        URL url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
604        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
605        request.setBody(info.getPendingChanges());
606        BoxJSONResponse response = (BoxJSONResponse) request.send();
607        JsonObject jsonObject = Json.parse(response.getJSON()).asObject();
608        info.update(jsonObject);
609    }
610
611    /**
612     * @param sourceUserID the user id of the user whose files will be the source for this operation
613     * @return info for the newly created folder
614     * @deprecated As of release 2.22.0, replaced by {@link #transferContent(String)} ()}
615     * <p>
616     * Moves all of the owned content from within one user’s folder into a new folder in another user's account.
617     * You can move folders across users as long as the you have administrative permissions and the 'source'
618     * user owns the folders. Per the documentation at the link below, this will move everything from the root
619     * folder, as this is currently the only mode of operation supported.
620     * <p>
621     * See also https://developer.box.com/en/reference/put-users-id-folders-id/
622     */
623    @Deprecated
624    public BoxFolder.Info moveFolderToUser(String sourceUserID) {
625        // Currently the API only supports moving of the root folder (0), hence the hard coded "0"
626        URL url = MOVE_FOLDER_TO_USER_TEMPLATE.build(this.getAPI().getBaseURL(), sourceUserID, "0");
627        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
628        JsonObject idValue = new JsonObject();
629        idValue.add("id", this.getID());
630        JsonObject ownedBy = new JsonObject();
631        ownedBy.add("owned_by", idValue);
632        request.setBody(ownedBy.toString());
633        BoxJSONResponse response = (BoxJSONResponse) request.send();
634        JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
635        BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
636
637        return movedFolder.new Info(responseJSON);
638    }
639
640    /**
641     * Moves all of the owned content from within one user’s folder into a new folder in another user's account.
642     * You can move folders across users as long as the you have administrative permissions and the 'source'
643     * user owns the folders. Per the documentation at the link below, this will move everything from the root
644     * folder, as this is currently the only mode of operation supported.
645     * <p>
646     * See also https://developer.box.com/en/reference/put-users-id-folders-id/
647     *
648     * @param destinationUserID the user id of the user that you wish to transfer content to.
649     * @return info for the newly created folder.
650     */
651    public BoxFolder.Info transferContent(String destinationUserID) {
652        URL url = MOVE_FOLDER_TO_USER_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), "0");
653        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT");
654        JsonObject destinationUser = new JsonObject();
655        destinationUser.add("id", destinationUserID);
656        JsonObject ownedBy = new JsonObject();
657        ownedBy.add("owned_by", destinationUser);
658        request.setBody(ownedBy.toString());
659        BoxJSONResponse response = (BoxJSONResponse) request.send();
660        JsonObject responseJSON = Json.parse(response.getJSON()).asObject();
661        BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString());
662
663        return movedFolder.new Info(responseJSON);
664    }
665
666    /**
667     * Retrieves the avatar of a user as an InputStream.
668     *
669     * @return InputStream representing the user avater.
670     */
671    public InputStream getAvatar() {
672        URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
673        BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
674        BoxAPIResponse response = request.send();
675
676        return response.getBody();
677    }
678
679    /**
680     * Enumerates the possible roles that a user can have within an enterprise.
681     */
682    public enum Role {
683        /**
684         * The user is an administrator of their enterprise.
685         */
686        ADMIN("admin"),
687
688        /**
689         * The user is a co-administrator of their enterprise.
690         */
691        COADMIN("coadmin"),
692
693        /**
694         * The user is a regular user within their enterprise.
695         */
696        USER("user");
697
698        private final String jsonValue;
699
700        Role(String jsonValue) {
701            this.jsonValue = jsonValue;
702        }
703
704        static Role fromJSONValue(String jsonValue) {
705            return Role.valueOf(jsonValue.toUpperCase());
706        }
707
708        String toJSONValue() {
709            return this.jsonValue;
710        }
711    }
712
713    /**
714     * Enumerates the possible statuses that a user's account can have.
715     */
716    public enum Status {
717        /**
718         * The user's account is active.
719         */
720        ACTIVE("active"),
721
722        /**
723         * The user's account is inactive.
724         */
725        INACTIVE("inactive"),
726
727        /**
728         * The user's account cannot delete or edit content.
729         */
730        CANNOT_DELETE_EDIT("cannot_delete_edit"),
731
732        /**
733         * The user's account cannot delete, edit, or upload content.
734         */
735        CANNOT_DELETE_EDIT_UPLOAD("cannot_delete_edit_upload");
736
737        private final String jsonValue;
738
739        Status(String jsonValue) {
740            this.jsonValue = jsonValue;
741        }
742
743        static Status fromJSONValue(String jsonValue) {
744            return Status.valueOf(jsonValue.toUpperCase());
745        }
746
747        String toJSONValue() {
748            return this.jsonValue;
749        }
750    }
751
752    /**
753     * Contains information about a BoxUser.
754     */
755    public class Info extends BoxCollaborator.Info {
756        private String login;
757        private Role role;
758        private String language;
759        private String timezone;
760        private long spaceAmount;
761        private long spaceUsed;
762        private long maxUploadSize;
763        private boolean canSeeManagedUsers;
764        private boolean isSyncEnabled;
765        private boolean isExternalCollabRestricted;
766        private Status status;
767        private String jobTitle;
768        private String phone;
769        private String address;
770        private String avatarURL;
771        private boolean isExemptFromDeviceLimits;
772        private boolean isExemptFromLoginVerification;
773        private boolean isPasswordResetRequired;
774        private boolean isPlatformAccessOnly;
775        private String externalAppUserId;
776        private BoxEnterprise enterprise;
777        private List<String> myTags;
778        private String hostname;
779        private Map<String, String> trackingCodes;
780
781        /**
782         * Constructs an empty Info object.
783         */
784        public Info() {
785            super();
786        }
787
788        /**
789         * Constructs an Info object by parsing information from a JSON string.
790         *
791         * @param json the JSON string to parse.
792         */
793        public Info(String json) {
794            super(json);
795        }
796
797        Info(JsonObject jsonObject) {
798            super(jsonObject);
799        }
800
801        @Override
802        public BoxUser getResource() {
803            return BoxUser.this;
804        }
805
806        /**
807         * Gets the email address the user uses to login.
808         *
809         * @return the email address the user uses to login.
810         */
811        public String getLogin() {
812            return this.login;
813        }
814
815        /**
816         * Sets the email address the user uses to login. The new login must be one of the user's already confirmed
817         * email aliases.
818         *
819         * @param login one of the user's confirmed email aliases.
820         */
821        public void setLogin(String login) {
822            this.login = login;
823            this.addPendingChange("login", login);
824        }
825
826        /**
827         * Gets the user's enterprise role.
828         *
829         * @return the user's enterprise role.
830         */
831        public Role getRole() {
832            return this.role;
833        }
834
835        /**
836         * Sets the user's role in their enterprise.
837         *
838         * @param role the user's new role in their enterprise.
839         */
840        public void setRole(Role role) {
841            this.role = role;
842            this.addPendingChange("role", role.name().toLowerCase());
843        }
844
845        /**
846         * Gets the language of the user.
847         *
848         * @return the language of the user.
849         */
850        public String getLanguage() {
851            return this.language;
852        }
853
854        /**
855         * Sets the language of the user.
856         *
857         * @param language the new language of the user.
858         */
859        public void setLanguage(String language) {
860            this.language = language;
861            this.addPendingChange("language", language);
862        }
863
864        /**
865         * Gets the timezone of the user.
866         *
867         * @return the timezone of the user.
868         */
869        public String getTimezone() {
870            return this.timezone;
871        }
872
873        /**
874         * Sets the timezone of the user.
875         *
876         * @param timezone the new timezone of the user.
877         */
878        public void setTimezone(String timezone) {
879            this.timezone = timezone;
880            this.addPendingChange("timezone", timezone);
881        }
882
883        /**
884         * Gets the user's total available space in bytes.
885         *
886         * @return the user's total available space in bytes.
887         */
888        public long getSpaceAmount() {
889            return this.spaceAmount;
890        }
891
892        /**
893         * Sets the user's total available space in bytes.
894         *
895         * @param spaceAmount the new amount of space available to the user in bytes, or -1 for unlimited storage.
896         */
897        public void setSpaceAmount(long spaceAmount) {
898            this.spaceAmount = spaceAmount;
899            this.addPendingChange("space_amount", spaceAmount);
900        }
901
902        /**
903         * Gets the amount of space the user has used in bytes.
904         *
905         * @return the amount of space the user has used in bytes.
906         */
907        public long getSpaceUsed() {
908            return this.spaceUsed;
909        }
910
911        /**
912         * Gets the maximum individual file size in bytes the user can have.
913         *
914         * @return the maximum individual file size in bytes the user can have.
915         */
916        public long getMaxUploadSize() {
917            return this.maxUploadSize;
918        }
919
920        /**
921         * Gets the user's current account status.
922         *
923         * @return the user's current account status.
924         */
925        public Status getStatus() {
926            return this.status;
927        }
928
929        /**
930         * Sets the user's current account status.
931         *
932         * @param status the user's new account status.
933         */
934        public void setStatus(Status status) {
935            this.status = status;
936            this.addPendingChange("status", status.name().toLowerCase());
937        }
938
939        /**
940         * Gets the job title of the user.
941         *
942         * @return the job title of the user.
943         */
944        public String getJobTitle() {
945            return this.jobTitle;
946        }
947
948        /**
949         * Sets the job title of the user.
950         *
951         * @param jobTitle the new job title of the user.
952         */
953        public void setJobTitle(String jobTitle) {
954            this.jobTitle = jobTitle;
955            this.addPendingChange("job_title", jobTitle);
956        }
957
958        /**
959         * Gets the phone number of the user.
960         *
961         * @return the phone number of the user.
962         */
963        public String getPhone() {
964            return this.phone;
965        }
966
967        /**
968         * Sets the phone number of the user.
969         *
970         * @param phone the new phone number of the user.
971         */
972        public void setPhone(String phone) {
973            this.phone = phone;
974            this.addPendingChange("phone", phone);
975        }
976
977        /**
978         * Gets the address of the user.
979         *
980         * @return the address of the user.
981         */
982        public String getAddress() {
983            return this.address;
984        }
985
986        /**
987         * Sets the address of the user.
988         *
989         * @param address the new address of the user.
990         */
991        public void setAddress(String address) {
992            this.address = address;
993            this.addPendingChange("address", address);
994        }
995
996        /**
997         * Gets the URL of the user's avatar.
998         *
999         * @return the URL of the user's avatar.
1000         */
1001        public String getAvatarURL() {
1002            return this.avatarURL;
1003        }
1004
1005        /**
1006         * Gets the enterprise that the user belongs to.
1007         *
1008         * @return the enterprise that the user belongs to.
1009         */
1010        public BoxEnterprise getEnterprise() {
1011            return this.enterprise;
1012        }
1013
1014        /**
1015         * Removes the user from their enterprise and converts them to a standalone free user.
1016         */
1017        public void removeEnterprise() {
1018            this.removeChildObject("enterprise");
1019            this.enterprise = null;
1020            this.addChildObject("enterprise", null);
1021        }
1022
1023        /**
1024         * Gets whether or not the user can use Box Sync.
1025         *
1026         * @return true if the user can use Box Sync; otherwise false.
1027         */
1028        public boolean getIsSyncEnabled() {
1029            return this.isSyncEnabled;
1030        }
1031
1032        /**
1033         * Sets whether or not the user can use Box Sync.
1034         *
1035         * @param enabled whether or not the user can use Box Sync.
1036         */
1037        public void setIsSyncEnabled(boolean enabled) {
1038            this.isSyncEnabled = enabled;
1039            this.addPendingChange("is_sync_enabled", enabled);
1040        }
1041
1042        /**
1043         * Gets whether this user is allowed or not to collaborate with users outside their enterprise.
1044         *
1045         * @return true if this user is not allowed to collaborate with users outside their enterprise; otherwise false.
1046         */
1047        public boolean getIsExternalCollabRestricted() {
1048            return this.isExternalCollabRestricted;
1049        }
1050
1051        /**
1052         * Sets whether this user is allowed or not to collaborate with users outside their enterprise.
1053         *
1054         * @param isExternalCollabRestricted whether the user is allowed to collaborate outside their enterprise.
1055         */
1056        public void setIsExternalCollabRestricted(boolean isExternalCollabRestricted) {
1057            this.isExternalCollabRestricted = isExternalCollabRestricted;
1058            this.addPendingChange("is_external_collab_restricted", isExternalCollabRestricted);
1059        }
1060
1061        /**
1062         * Gets whether or not the user can see other enterprise users in their contact list.
1063         *
1064         * @return true if the user can see other enterprise users in their contact list; otherwise false.
1065         */
1066        public boolean getCanSeeManagedUsers() {
1067            return this.canSeeManagedUsers;
1068        }
1069
1070        /**
1071         * Sets whether or not the user can see other enterprise users in their contact list.
1072         *
1073         * @param canSeeManagedUsers whether or not the user can see other enterprise users in their contact list.
1074         */
1075        public void setCanSeeManagedUsers(boolean canSeeManagedUsers) {
1076            this.canSeeManagedUsers = canSeeManagedUsers;
1077            this.addPendingChange("can_see_managed_users", canSeeManagedUsers);
1078        }
1079
1080        /**
1081         * Gets whether or not the user is exempt from enterprise device limits.
1082         *
1083         * @return true if the user is exempt from enterprise device limits; otherwise false.
1084         */
1085        public boolean getIsExemptFromDeviceLimits() {
1086            return this.isExemptFromDeviceLimits;
1087        }
1088
1089        /**
1090         * Sets whether or not the user is exempt from enterprise device limits.
1091         *
1092         * @param isExemptFromDeviceLimits whether or not the user is exempt from enterprise device limits.
1093         */
1094        public void setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLimits) {
1095            this.isExemptFromDeviceLimits = isExemptFromDeviceLimits;
1096            this.addPendingChange("is_exempt_from_device_limits", isExemptFromDeviceLimits);
1097        }
1098
1099        /**
1100         * Gets whether or not the user must use two-factor authentication.
1101         *
1102         * @return true if the user must use two-factor authentication; otherwise false.
1103         */
1104        public boolean getIsExemptFromLoginVerification() {
1105            return this.isExemptFromLoginVerification;
1106        }
1107
1108        /**
1109         * Sets whether or not the user must use two-factor authentication.
1110         *
1111         * @param isExemptFromLoginVerification whether or not the user must use two-factor authentication.
1112         */
1113        public void setIsExemptFromLoginVerification(boolean isExemptFromLoginVerification) {
1114            this.isExemptFromLoginVerification = isExemptFromLoginVerification;
1115            this.addPendingChange("is_exempt_from_login_verification", isExemptFromLoginVerification);
1116        }
1117
1118        /**
1119         * Gets whether or not the user is required to reset password.
1120         *
1121         * @return true if the user is required to reset password; otherwise false.
1122         */
1123        public boolean getIsPasswordResetRequired() {
1124            return this.isPasswordResetRequired;
1125        }
1126
1127        /**
1128         * Sets whether or not the user is required to reset password.
1129         *
1130         * @param isPasswordResetRequired whether or not the user is required to reset password.
1131         */
1132        public void setIsPasswordResetRequired(boolean isPasswordResetRequired) {
1133            this.isPasswordResetRequired = isPasswordResetRequired;
1134            this.addPendingChange("is_password_reset_required", isPasswordResetRequired);
1135        }
1136
1137        /**
1138         * Gets whether or not the user we are creating is an app user with Box Developer Edition.
1139         *
1140         * @return true if the new user is an app user for Box Developer Addition; otherwise false.
1141         */
1142        public boolean getIsPlatformAccessOnly() {
1143            return this.isPlatformAccessOnly;
1144        }
1145
1146        /**
1147         * Gets the external app user id that has been set for the app user.
1148         *
1149         * @return the external app user id.
1150         */
1151        public String getExternalAppUserId() {
1152            return this.externalAppUserId;
1153        }
1154
1155        /**
1156         * Sets the external app user id.
1157         *
1158         * @param externalAppUserId external app user id.
1159         */
1160        public void setExternalAppUserId(String externalAppUserId) {
1161            this.externalAppUserId = externalAppUserId;
1162            this.addPendingChange("external_app_user_id", externalAppUserId);
1163        }
1164
1165        /**
1166         * Gets the tags for all files and folders owned by this user.
1167         *
1168         * @return the tags for all files and folders owned by this user.
1169         */
1170        public List<String> getMyTags() {
1171            return this.myTags;
1172        }
1173
1174        /**
1175         * Gets the root (protocol, subdomain, domain) of any links that need to be generated for this user.
1176         *
1177         * @return the root (protocol, subdomain, domain) of any links that need to be generated for this user.
1178         */
1179        public String getHostname() {
1180            return this.hostname;
1181        }
1182
1183        /**
1184         * Gets the tracking defined for each entity.
1185         *
1186         * @return a Map with tracking codes.
1187         */
1188        public Map<String, String> getTrackingCodes() {
1189            return this.trackingCodes;
1190        }
1191
1192        /**
1193         * Allows admin to set attributes specific for a group of users.
1194         *
1195         * @param trackingCodes a Map representing the user's new tracking codes
1196         */
1197        public void setTrackingCodes(Map<String, String> trackingCodes) {
1198            this.trackingCodes = trackingCodes;
1199            this.addPendingChange("tracking_codes", toTrackingCodesJson(this.trackingCodes));
1200        }
1201
1202        /**
1203         * Allows the admin to append new tracking codes to the previous existing list.
1204         *
1205         * @param name  the name or `key` of the attribute to set.
1206         * @param value the value of the attribute to set.
1207         */
1208        public void appendTrackingCodes(String name, String value) {
1209            this.getTrackingCodes().put(name, value);
1210            this.addPendingChange("tracking_codes", toTrackingCodesJson(this.trackingCodes));
1211        }
1212
1213        @Override
1214        protected void parseJSONMember(JsonObject.Member member) {
1215            super.parseJSONMember(member);
1216
1217            JsonValue value = member.getValue();
1218            String memberName = member.getName();
1219            try {
1220                if (memberName.equals("login")) {
1221                    this.login = value.asString();
1222                } else if (memberName.equals("role")) {
1223                    this.role = Role.fromJSONValue(value.asString());
1224                } else if (memberName.equals("language")) {
1225                    this.language = value.asString();
1226                } else if (memberName.equals("timezone")) {
1227                    this.timezone = value.asString();
1228                } else if (memberName.equals("space_amount")) {
1229                    this.spaceAmount = Double.valueOf(value.toString()).longValue();
1230                } else if (memberName.equals("space_used")) {
1231                    this.spaceUsed = Double.valueOf(value.toString()).longValue();
1232                } else if (memberName.equals("max_upload_size")) {
1233                    this.maxUploadSize = Double.valueOf(value.toString()).longValue();
1234                } else if (memberName.equals("status")) {
1235                    this.status = Status.fromJSONValue(value.asString());
1236                } else if (memberName.equals("job_title")) {
1237                    this.jobTitle = value.asString();
1238                } else if (memberName.equals("phone")) {
1239                    this.phone = value.asString();
1240                } else if (memberName.equals("address")) {
1241                    this.address = value.asString();
1242                } else if (memberName.equals("avatar_url")) {
1243                    this.avatarURL = value.asString();
1244                } else if (memberName.equals("can_see_managed_users")) {
1245                    this.canSeeManagedUsers = value.asBoolean();
1246                } else if (memberName.equals("is_sync_enabled")) {
1247                    this.isSyncEnabled = value.asBoolean();
1248                } else if (memberName.equals("is_external_collab_restricted")) {
1249                    this.isExternalCollabRestricted = value.asBoolean();
1250                } else if (memberName.equals("is_exempt_from_device_limits")) {
1251                    this.isExemptFromDeviceLimits = value.asBoolean();
1252                } else if (memberName.equals("is_exempt_from_login_verification")) {
1253                    this.isExemptFromLoginVerification = value.asBoolean();
1254                } else if (memberName.equals("is_password_reset_required")) {
1255                    this.isPasswordResetRequired = value.asBoolean();
1256                } else if (memberName.equals("is_platform_access_only")) {
1257                    this.isPlatformAccessOnly = value.asBoolean();
1258                } else if (memberName.equals("external_app_user_id")) {
1259                    this.externalAppUserId = value.asString();
1260                } else if (memberName.equals("enterprise")) {
1261                    JsonObject jsonObject = value.asObject();
1262                    if (this.enterprise == null) {
1263                        this.enterprise = new BoxEnterprise(jsonObject);
1264                    } else {
1265                        this.enterprise.update(jsonObject);
1266                    }
1267                } else if (memberName.equals("my_tags")) {
1268                    this.myTags = this.parseMyTags(value.asArray());
1269                } else if (memberName.equals("hostname")) {
1270                    this.hostname = value.asString();
1271                } else if (memberName.equals("tracking_codes")) {
1272                    this.trackingCodes = this.parseTrackingCodes(value.asArray());
1273                }
1274            } catch (Exception e) {
1275                throw new BoxDeserializationException(memberName, value.toString(), e);
1276            }
1277
1278        }
1279
1280        private List<String> parseMyTags(JsonArray jsonArray) {
1281            List<String> myTags = new ArrayList<>(jsonArray.size());
1282            for (JsonValue value : jsonArray) {
1283                myTags.add(value.asString());
1284            }
1285
1286            return myTags;
1287        }
1288
1289        private Map<String, String> parseTrackingCodes(JsonArray jsonArray) {
1290            Map<String, String> result = new HashMap<>();
1291            if (jsonArray == null) {
1292                return null;
1293            }
1294            List<JsonValue> valuesList = jsonArray.values();
1295            for (JsonValue jsonValue : valuesList) {
1296                JsonObject object = jsonValue.asObject();
1297                result.put(object.get("name").asString(), object.get("value").asString());
1298            }
1299            return result;
1300        }
1301    }
1302}