001package com.box.sdk;
002
003import java.net.URL;
004import java.text.ParseException;
005import java.util.Date;
006
007import com.eclipsesource.json.JsonObject;
008import com.eclipsesource.json.JsonValue;
009
010/**
011 * Represents a relationship between a user and a group.
012 *
013 * <p>Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked
014 * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error
015 * handling for errors related to the Box REST API, you should capture this exception explicitly.</p>
016 */
017@BoxResourceType("group_membership")
018public class BoxGroupMembership extends BoxResource {
019
020    /**
021     * The URL template for all group membership requests.
022     * @see #getInfo()
023     */
024    public static final URLTemplate MEMBERSHIP_URL_TEMPLATE = new URLTemplate("group_memberships/%s");
025
026    /**
027     * Constructs a BoxGroupMembership for a group membership with a given ID.
028     * @param  api the API connection to be used by the group membership.
029     * @param  id  the ID of the group membership.
030     */
031    public BoxGroupMembership(BoxAPIConnection api, String id) {
032        super(api, id);
033    }
034
035    /**
036     * Gets information about this group membership.
037     * @return info about this group membership.
038     */
039    public Info getInfo() {
040        BoxAPIConnection api = this.getAPI();
041        URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID());
042
043        BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
044        BoxJSONResponse response = (BoxJSONResponse) request.send();
045        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
046        return new Info(jsonObject);
047    }
048
049    /**
050     * Updates the information about this group membership with any info fields that have been modified locally.
051     * @param info the updated info.
052     */
053    public void updateInfo(Info info) {
054        BoxAPIConnection api = this.getAPI();
055        URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID());
056
057        BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT");
058        request.setBody(info.getPendingChanges());
059        BoxJSONResponse response = (BoxJSONResponse) request.send();
060        JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
061        info.update(jsonObject);
062    }
063
064    /**
065     * Deletes this group membership.
066     */
067    public void delete() {
068        BoxAPIConnection api = this.getAPI();
069        URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID());
070
071        BoxAPIRequest request = new BoxAPIRequest(api, url, "DELETE");
072        BoxAPIResponse response = request.send();
073        response.disconnect();
074    }
075
076    /**
077     * Contains information about a BoxGroupMembership.
078     */
079    public class Info extends BoxResource.Info {
080
081        /**
082         * @see #getUser()
083         */
084        private BoxUser.Info user;
085
086        /**
087         * @see #getGroup()
088         */
089        private BoxGroup.Info group;
090
091        /**
092         * @see #getRole()
093         */
094        private Role role;
095
096        /**
097         * @see #getCreatedAt()
098         */
099        private Date createdAt;
100
101        /**
102         * @see #getModifiedAt()
103         */
104        private Date modifiedAt;
105
106        /**
107         * Constructs an empty Info object.
108         */
109        public Info() {
110            super();
111        }
112
113        /**
114         * Constructs an Info object by parsing information from a JSON string.
115         * @param  json the JSON string to parse.
116         */
117        public Info(String json) {
118            super(json);
119        }
120
121        /**
122         * Constructs an Info object using an already parsed JSON object.
123         * @param  jsonObject the parsed JSON object.
124         */
125        Info(JsonObject jsonObject) {
126            super(jsonObject);
127        }
128
129        /**
130         * Gets the user belonging to the group.
131         *
132         * <p>Note: the BoxUser.Info returned by this method will only have the ID, name, and login fields
133         * populated.</p>
134         *
135         * @return the user belonging to the group.
136         */
137        public BoxUser.Info getUser() {
138            return this.user;
139        }
140
141        /**
142         * Gets the group the user belongs to.
143         *
144         * <p>Note: the BoxGroup.Info returned by this method will only have the ID and name fields populated.</p>
145         *
146         * @return the group the user belongs to.
147         */
148        public BoxGroup.Info getGroup() {
149            return this.group;
150        }
151
152        /**
153         * Gets the level of access the user has.
154         * @return the level of access the user has.
155         */
156        public Role getRole() {
157            return this.role;
158        }
159
160        /**
161         * Sets the level of access the user has.
162         * @param role the new level of access to give the user.
163         */
164        public void setRole(Role role) {
165            this.role = role;
166            this.addPendingChange("role", role.toJSONString());
167        }
168
169        /**
170         * Gets the time the group membership was created.
171         * @return the time the group membership was created.
172         */
173        public Date getCreatedAt() {
174            return this.createdAt;
175        }
176
177        /**
178         * Gets the time the group membership was last modified.
179         * @return the time the group membership was last modified.
180         */
181        public Date getModifiedAt() {
182            return this.modifiedAt;
183        }
184
185        /**
186         * {@inheritDoc}
187         */
188        @Override
189        public BoxGroupMembership getResource() {
190            return BoxGroupMembership.this;
191        }
192
193        /**
194         * {@inheritDoc}
195         */
196        @Override
197        protected void parseJSONMember(JsonObject.Member member) {
198            super.parseJSONMember(member);
199
200            String memberName = member.getName();
201            JsonValue value = member.getValue();
202
203            try {
204                if (memberName.equals("user")) {
205                    JsonObject userJSON = value.asObject();
206                    if (this.user == null) {
207                        String userID = userJSON.get("id").asString();
208                        BoxUser user = new BoxUser(getAPI(), userID);
209                        this.user = user.new Info(userJSON);
210                    } else {
211                        this.user.update(userJSON);
212                    }
213
214                } else if (memberName.equals("group")) {
215                    JsonObject groupJSON = value.asObject();
216                    if (this.group == null) {
217                        String userID = groupJSON.get("id").asString();
218                        BoxGroup group = new BoxGroup(getAPI(), userID);
219                        this.group = group.new Info(groupJSON);
220                    } else {
221                        this.group.update(groupJSON);
222                    }
223
224                } else if (memberName.equals("role")) {
225                    this.role = Role.fromJSONString(value.asString());
226
227                } else if (memberName.equals("created_at")) {
228                    this.createdAt = BoxDateFormat.parse(value.asString());
229
230                } else if (memberName.equals("modified_at")) {
231                    this.modifiedAt = BoxDateFormat.parse(value.asString());
232
233                }
234            } catch (ParseException e) {
235                assert false : "A ParseException indicates a bug in the SDK.";
236            }
237        }
238    }
239
240    /**
241     * Enumerates the possible roles that a user can have within a group.
242     */
243    public enum Role {
244        /**
245         * The user is an administrator in the group.
246         */
247        ADMIN ("admin"),
248
249        /**
250         * The user is a submaster in the group.
251         */
252        SUBMASTER ("submaster"),
253
254        /**
255         * The user is a regular member in the group.
256         */
257        MEMBER ("member");
258
259        /**
260         * String representation of the role.
261         */
262        private final String jsonValue;
263
264        /**
265         * Constructor.
266         * @param jsonValue srting representation of the role.
267         */
268        private Role(String jsonValue) {
269            this.jsonValue = jsonValue;
270        }
271
272        /**
273         * Creates the role from given string.
274         * @param jsonValue string to be converted to role.
275         * @return the role, created from string value.
276         */
277        static Role fromJSONString(String jsonValue) {
278            return Role.valueOf(jsonValue.toUpperCase());
279        }
280
281        /**
282         * @return string representation of the role.
283         */
284        String toJSONString() {
285            return this.jsonValue;
286        }
287    }
288}