001package com.box.sdk; 002 003import java.io.ByteArrayOutputStream; 004import java.io.IOException; 005import java.io.InputStream; 006import java.io.OutputStream; 007import java.net.MalformedURLException; 008import java.net.URL; 009import java.util.ArrayList; 010import java.util.Arrays; 011import java.util.Collection; 012import java.util.Date; 013import java.util.EnumSet; 014import java.util.HashSet; 015import java.util.List; 016import java.util.Map; 017import java.util.Set; 018import java.util.concurrent.TimeUnit; 019 020import com.box.sdk.http.HttpMethod; 021import com.box.sdk.internal.utils.Parsers; 022import com.eclipsesource.json.JsonArray; 023import com.eclipsesource.json.JsonObject; 024import com.eclipsesource.json.JsonValue; 025 026 027/** 028 * Represents an individual file on Box. This class can be used to download a file's contents, upload new versions, and 029 * perform other common file operations (move, copy, delete, etc.). 030 * 031 * <p>Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked 032 * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error 033 * handling for errors related to the Box REST API, you should capture this exception explicitly. 034 */ 035@BoxResourceType("file") 036public class BoxFile extends BoxItem { 037 038 /** 039 * An array of all possible file fields that can be requested when calling {@link #getInfo()}. 040 */ 041 public static final String[] ALL_FIELDS = {"type", "id", "sequence_id", "etag", "sha1", "name", 042 "description", "size", "path_collection", "created_at", "modified_at", 043 "trashed_at", "purged_at", "content_created_at", "content_modified_at", 044 "created_by", "modified_by", "owned_by", "shared_link", "parent", 045 "item_status", "version_number", "comment_count", "permissions", "tags", 046 "lock", "extension", "is_package", "file_version", "collections", 047 "watermark_info", "metadata", "representations", 048 "is_external_only", "expiring_embed_link", "allowed_invitee_roles", 049 "has_collaborations"}; 050 051 /** 052 * Used to specify what filetype to request for a file thumbnail. 053 */ 054 public enum ThumbnailFileType { 055 /** 056 * PNG image format. 057 */ 058 PNG, 059 060 /** 061 * JPG image format. 062 */ 063 JPG 064 } 065 066 /** 067 * File URL Template. 068 */ 069 public static final URLTemplate FILE_URL_TEMPLATE = new URLTemplate("files/%s"); 070 /** 071 * Content URL Template. 072 */ 073 public static final URLTemplate CONTENT_URL_TEMPLATE = new URLTemplate("files/%s/content"); 074 /** 075 * Versions URL Template. 076 */ 077 public static final URLTemplate VERSIONS_URL_TEMPLATE = new URLTemplate("files/%s/versions"); 078 /** 079 * Copy URL Template. 080 */ 081 public static final URLTemplate COPY_URL_TEMPLATE = new URLTemplate("files/%s/copy"); 082 /** 083 * Add Comment URL Template. 084 */ 085 public static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); 086 /** 087 * Get Comments URL Template. 088 */ 089 public static final URLTemplate GET_COMMENTS_URL_TEMPLATE = new URLTemplate("files/%s/comments"); 090 /** 091 * Metadata URL Template. 092 */ 093 public static final URLTemplate METADATA_URL_TEMPLATE = new URLTemplate("files/%s/metadata/%s/%s"); 094 /** 095 * Add Task URL Template. 096 */ 097 public static final URLTemplate ADD_TASK_URL_TEMPLATE = new URLTemplate("tasks"); 098 /** 099 * Get Tasks URL Template. 100 */ 101 public static final URLTemplate GET_TASKS_URL_TEMPLATE = new URLTemplate("files/%s/tasks"); 102 /** 103 * Get Thumbnail PNG Template. 104 */ 105 public static final URLTemplate GET_THUMBNAIL_PNG_TEMPLATE = new URLTemplate("files/%s/thumbnail.png"); 106 /** 107 * Get Thumbnail JPG Template. 108 */ 109 public static final URLTemplate GET_THUMBNAIL_JPG_TEMPLATE = new URLTemplate("files/%s/thumbnail.jpg"); 110 /** 111 * Upload Session URL Template. 112 */ 113 public static final URLTemplate UPLOAD_SESSION_URL_TEMPLATE = new URLTemplate("files/%s/upload_sessions"); 114 /** 115 * Upload Session Status URL Template. 116 */ 117 public static final URLTemplate UPLOAD_SESSION_STATUS_URL_TEMPLATE = new URLTemplate( 118 "files/upload_sessions/%s/status"); 119 /** 120 * Abort Upload Session URL Template. 121 */ 122 public static final URLTemplate ABORT_UPLOAD_SESSION_URL_TEMPLATE = new URLTemplate("files/upload_sessions/%s"); 123 /** 124 * Add Collaborations URL Template. 125 */ 126 public static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations"); 127 /** 128 * Get All File Collaborations URL Template. 129 */ 130 public static final URLTemplate GET_ALL_FILE_COLLABORATIONS_URL = new URLTemplate("files/%s/collaborations"); 131 private static final int BUFFER_SIZE = 8192; 132 private static final int GET_COLLABORATORS_PAGE_SIZE = 1000; 133 134 /** 135 * Constructs a BoxFile for a file with a given ID. 136 * 137 * @param api the API connection to be used by the file. 138 * @param id the ID of the file. 139 */ 140 public BoxFile(BoxAPIConnection api, String id) { 141 super(api, id); 142 } 143 144 /** 145 * {@inheritDoc} 146 */ 147 @Override 148 protected URL getItemURL() { 149 return FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 150 } 151 152 @Override 153 public BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate, 154 BoxSharedLink.Permissions permissions) { 155 156 BoxSharedLink sharedLink = new BoxSharedLink(access, unshareDate, permissions); 157 Info info = new Info(); 158 info.setSharedLink(sharedLink); 159 160 this.updateInfo(info); 161 return info.getSharedLink(); 162 } 163 164 /** 165 * Creates new SharedLink for a BoxFile with a password. 166 * 167 * @param access The access level of the shared link. 168 * @param unshareDate A specified date to unshare the Box file. 169 * @param permissions The permissions to set on the shared link for the Box file. 170 * @param password Password set on the shared link to give access to the Box file. 171 * @return information about the newly created shared link. 172 */ 173 public BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate, 174 BoxSharedLink.Permissions permissions, String password) { 175 176 BoxSharedLink sharedLink = new BoxSharedLink(access, unshareDate, permissions, password); 177 Info info = new Info(); 178 info.setSharedLink(sharedLink); 179 180 this.updateInfo(info); 181 return info.getSharedLink(); 182 } 183 184 /** 185 * Adds new {@link BoxWebHook} to this {@link BoxFile}. 186 * 187 * @param address {@link BoxWebHook.Info#getAddress()} 188 * @param triggers {@link BoxWebHook.Info#getTriggers()} 189 * @return created {@link BoxWebHook.Info} 190 */ 191 public BoxWebHook.Info addWebHook(URL address, BoxWebHook.Trigger... triggers) { 192 return BoxWebHook.create(this, address, triggers); 193 } 194 195 /** 196 * Adds a comment to this file. The message can contain @mentions by using the string @[userid:username] anywhere 197 * within the message, where userid and username are the ID and username of the person being mentioned. 198 * 199 * @param message the comment's message. 200 * @return information about the newly added comment. 201 * @see <a href="https://developers.box.com/docs/#comments-add-a-comment-to-an-item">the tagged_message field 202 * for including @mentions.</a> 203 */ 204 public BoxComment.Info addComment(String message) { 205 JsonObject itemJSON = new JsonObject(); 206 itemJSON.add("type", "file"); 207 itemJSON.add("id", this.getID()); 208 209 JsonObject requestJSON = new JsonObject(); 210 requestJSON.add("item", itemJSON); 211 if (BoxComment.messageContainsMention(message)) { 212 requestJSON.add("tagged_message", message); 213 } else { 214 requestJSON.add("message", message); 215 } 216 217 URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); 218 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); 219 request.setBody(requestJSON.toString()); 220 BoxJSONResponse response = (BoxJSONResponse) request.send(); 221 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 222 223 BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); 224 return addedComment.new Info(responseJSON); 225 } 226 227 /** 228 * Adds a new task to this file. The task can have an optional message to include, and a due date. 229 * 230 * @param action the action the task assignee will be prompted to do. 231 * @param message an optional message to include with the task. 232 * @param dueAt the day at which this task is due. 233 * @return information about the newly added task. 234 */ 235 public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) { 236 return this.addTask(action, message, dueAt, null); 237 } 238 239 /** 240 * Adds a new task to this file. The task can have an optional message to include, due date, 241 * and task completion rule. 242 * 243 * @param action the action the task assignee will be prompted to do. 244 * @param message an optional message to include with the task. 245 * @param dueAt the day at which this task is due. 246 * @param completionRule the rule for completing the task. 247 * @return information about the newly added task. 248 */ 249 public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt, 250 BoxTask.CompletionRule completionRule) { 251 JsonObject itemJSON = new JsonObject(); 252 itemJSON.add("type", "file"); 253 itemJSON.add("id", this.getID()); 254 255 JsonObject requestJSON = new JsonObject(); 256 requestJSON.add("item", itemJSON); 257 requestJSON.add("action", action.toJSONString()); 258 259 if (message != null && !message.isEmpty()) { 260 requestJSON.add("message", message); 261 } 262 263 if (dueAt != null) { 264 requestJSON.add("due_at", BoxDateFormat.format(dueAt)); 265 } 266 267 if (completionRule != null) { 268 requestJSON.add("completion_rule", completionRule.toJSONString()); 269 } 270 271 URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL()); 272 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); 273 request.setBody(requestJSON.toString()); 274 BoxJSONResponse response = (BoxJSONResponse) request.send(); 275 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 276 277 BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get("id").asString()); 278 return addedTask.new Info(responseJSON); 279 } 280 281 /** 282 * Gets an expiring URL for downloading a file directly from Box. This can be user, 283 * for example, for sending as a redirect to a browser to cause the browser 284 * to download the file directly from Box. 285 * 286 * @return the temporary download URL 287 */ 288 public URL getDownloadURL() { 289 URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 290 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 291 request.setFollowRedirects(false); 292 293 BoxRedirectResponse response = (BoxRedirectResponse) request.send(); 294 295 return response.getRedirectURL(); 296 } 297 298 /** 299 * Downloads the contents of this file to a given OutputStream. 300 * 301 * @param output the stream to where the file will be written. 302 */ 303 public void download(OutputStream output) { 304 this.download(output, null); 305 } 306 307 /** 308 * Downloads the contents of this file to a given OutputStream while reporting the progress to a ProgressListener. 309 * 310 * @param output the stream to where the file will be written. 311 * @param listener a listener for monitoring the download's progress. 312 */ 313 public void download(OutputStream output, ProgressListener listener) { 314 URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 315 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 316 BoxAPIResponse response = request.send(); 317 InputStream input = response.getBody(listener); 318 319 byte[] buffer = new byte[BUFFER_SIZE]; 320 try { 321 int n = input.read(buffer); 322 while (n != -1) { 323 output.write(buffer, 0, n); 324 n = input.read(buffer); 325 } 326 } catch (IOException e) { 327 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 328 } finally { 329 response.disconnect(); 330 } 331 } 332 333 /** 334 * Downloads a part of this file's contents, starting at specified byte offset. 335 * 336 * @param output the stream to where the file will be written. 337 * @param offset the byte offset at which to start the download. 338 */ 339 public void downloadRange(OutputStream output, long offset) { 340 this.downloadRange(output, offset, -1); 341 } 342 343 /** 344 * Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd. 345 * 346 * @param output the stream to where the file will be written. 347 * @param rangeStart the byte offset at which to start the download. 348 * @param rangeEnd the byte offset at which to stop the download. 349 */ 350 public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) { 351 this.downloadRange(output, rangeStart, rangeEnd, null); 352 } 353 354 /** 355 * Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd, while reporting the 356 * progress to a ProgressListener. 357 * 358 * @param output the stream to where the file will be written. 359 * @param rangeStart the byte offset at which to start the download. 360 * @param rangeEnd the byte offset at which to stop the download. 361 * @param listener a listener for monitoring the download's progress. 362 */ 363 public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) { 364 URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 365 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 366 if (rangeEnd > 0) { 367 request.addHeader("Range", String.format("bytes=%s-%s", Long.toString(rangeStart), 368 Long.toString(rangeEnd))); 369 } else { 370 request.addHeader("Range", String.format("bytes=%s-", Long.toString(rangeStart))); 371 } 372 373 BoxAPIResponse response = request.send(); 374 InputStream input = response.getBody(listener); 375 376 byte[] buffer = new byte[BUFFER_SIZE]; 377 try { 378 int n = input.read(buffer); 379 while (n != -1) { 380 output.write(buffer, 0, n); 381 n = input.read(buffer); 382 } 383 } catch (IOException e) { 384 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 385 } finally { 386 response.disconnect(); 387 } 388 } 389 390 @Override 391 public BoxFile.Info copy(BoxFolder destination) { 392 return this.copy(destination, null); 393 } 394 395 @Override 396 public BoxFile.Info copy(BoxFolder destination, String newName) { 397 URL url = COPY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 398 399 JsonObject parent = new JsonObject(); 400 parent.add("id", destination.getID()); 401 402 JsonObject copyInfo = new JsonObject(); 403 copyInfo.add("parent", parent); 404 if (newName != null) { 405 copyInfo.add("name", newName); 406 } 407 408 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); 409 request.setBody(copyInfo.toString()); 410 BoxJSONResponse response = (BoxJSONResponse) request.send(); 411 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 412 BoxFile copiedFile = new BoxFile(this.getAPI(), responseJSON.get("id").asString()); 413 return copiedFile.new Info(responseJSON); 414 } 415 416 /** 417 * Deletes this file by moving it to the trash. 418 */ 419 public void delete() { 420 URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 421 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); 422 BoxAPIResponse response = request.send(); 423 response.disconnect(); 424 } 425 426 @Override 427 public BoxItem.Info move(BoxFolder destination) { 428 return this.move(destination, null); 429 } 430 431 @Override 432 public BoxItem.Info move(BoxFolder destination, String newName) { 433 URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 434 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); 435 436 JsonObject parent = new JsonObject(); 437 parent.add("id", destination.getID()); 438 439 JsonObject updateInfo = new JsonObject(); 440 updateInfo.add("parent", parent); 441 if (newName != null) { 442 updateInfo.add("name", newName); 443 } 444 445 request.setBody(updateInfo.toString()); 446 BoxJSONResponse response = (BoxJSONResponse) request.send(); 447 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 448 BoxFile movedFile = new BoxFile(this.getAPI(), responseJSON.get("id").asString()); 449 return movedFile.new Info(responseJSON); 450 } 451 452 /** 453 * Renames this file. 454 * 455 * @param newName the new name of the file. 456 */ 457 public void rename(String newName) { 458 URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 459 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); 460 461 JsonObject updateInfo = new JsonObject(); 462 updateInfo.add("name", newName); 463 464 request.setBody(updateInfo.toString()); 465 BoxJSONResponse response = (BoxJSONResponse) request.send(); 466 response.getJSON(); 467 } 468 469 @Override 470 public BoxFile.Info getInfo() { 471 URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 472 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 473 BoxJSONResponse response = (BoxJSONResponse) request.send(); 474 return new Info(response.getJSON()); 475 } 476 477 @Override 478 public BoxFile.Info getInfo(String... fields) { 479 String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); 480 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 481 482 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 483 BoxJSONResponse response = (BoxJSONResponse) request.send(); 484 return new Info(response.getJSON()); 485 } 486 487 /** 488 * Gets information about this item including a specified set of representations. 489 * @see <a href=https://developer.box.com/reference#section-x-rep-hints-header>X-Rep-Hints Header</a> 490 * 491 * @param representationHints hints for representations to be retrieved 492 * @param fields the fields to retrieve. 493 * @return info about this item containing only the specified fields, including representations. 494 */ 495 public BoxFile.Info getInfoWithRepresentations(String representationHints, String... fields) { 496 if (representationHints.matches(Representation.X_REP_HINTS_PATTERN)) { 497 //Since the user intends to get representations, add it to fields, even if user has missed it 498 Set<String> fieldsSet = new HashSet<String>(Arrays.asList(fields)); 499 fieldsSet.add("representations"); 500 String queryString = new QueryStringBuilder().appendParam("fields", 501 fieldsSet.toArray(new String[fieldsSet.size()])).toString(); 502 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 503 504 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 505 request.addHeader("X-Rep-Hints", representationHints); 506 BoxJSONResponse response = (BoxJSONResponse) request.send(); 507 return new Info(response.getJSON()); 508 } else { 509 throw new BoxAPIException("Represention hints is not valid." 510 + " Refer documention on how to construct X-Rep-Hints Header"); 511 } 512 } 513 514 /** 515 * Fetches the contents of a file representation and writes them to the provided output stream. 516 * @see <a href=https://developer.box.com/reference#section-x-rep-hints-header>X-Rep-Hints Header</a> 517 * @param representationHint the X-Rep-Hints query for the representation to fetch. 518 * @param output the output stream to write the contents to. 519 */ 520 public void getRepresentationContent(String representationHint, OutputStream output) { 521 522 this.getRepresentationContent(representationHint, "", output); 523 } 524 525 /** 526 * Fetches the contents of a file representation with asset path and writes them to the provided output stream. 527 * @see <a href=https://developer.box.com/reference#section-x-rep-hints-header>X-Rep-Hints Header</a> 528 * @param representationHint the X-Rep-Hints query for the representation to fetch. 529 * @param assetPath the path of the asset for representations containing multiple files. 530 * @param output the output stream to write the contents to. 531 */ 532 public void getRepresentationContent(String representationHint, String assetPath, OutputStream output) { 533 534 List<Representation> reps = this.getInfoWithRepresentations(representationHint).getRepresentations(); 535 if (reps.size() < 1) { 536 throw new BoxAPIException("No matching representations found"); 537 } 538 Representation representation = reps.get(0); 539 String repState = representation.getStatus().getState(); 540 541 if (repState.equals("viewable") || repState.equals("success")) { 542 543 this.makeRepresentationContentRequest(representation.getContent().getUrlTemplate(), 544 assetPath, output); 545 return; 546 } else if (repState.equals("pending") || repState.equals("none")) { 547 548 String repContentURLString = null; 549 while (repContentURLString == null) { 550 repContentURLString = this.pollRepInfo(representation.getInfo().getUrl()); 551 } 552 553 this.makeRepresentationContentRequest(repContentURLString, assetPath, output); 554 return; 555 556 } else if (repState.equals("error")) { 557 558 throw new BoxAPIException("Representation had error status"); 559 } else { 560 561 throw new BoxAPIException("Representation had unknown status"); 562 } 563 564 } 565 566 private String pollRepInfo(URL infoURL) { 567 568 BoxAPIRequest infoRequest = new BoxAPIRequest(this.getAPI(), infoURL, HttpMethod.GET); 569 BoxJSONResponse infoResponse = (BoxJSONResponse) infoRequest.send(); 570 JsonObject response = infoResponse.getJsonObject(); 571 572 Representation rep = new Representation(response); 573 574 String repState = rep.getStatus().getState(); 575 576 if (repState.equals("viewable") || repState.equals("success")) { 577 578 return rep.getContent().getUrlTemplate(); 579 } else if (repState.equals("pending") || repState.equals("none")) { 580 581 return null; 582 583 } else if (repState.equals("error")) { 584 585 throw new BoxAPIException("Representation had error status"); 586 } else { 587 588 throw new BoxAPIException("Representation had unknown status"); 589 } 590 } 591 592 private void makeRepresentationContentRequest(String representationURLTemplate, String assetPath, 593 OutputStream output) { 594 595 try { 596 597 URL repURL = new URL(representationURLTemplate.replace("{+asset_path}", assetPath)); 598 BoxAPIRequest repContentReq = new BoxAPIRequest(this.getAPI(), repURL, HttpMethod.GET); 599 600 BoxAPIResponse contentResponse = repContentReq.send(); 601 602 InputStream input = contentResponse.getBody(); 603 604 byte[] buffer = new byte[BUFFER_SIZE]; 605 try { 606 int n = input.read(buffer); 607 while (n != -1) { 608 output.write(buffer, 0, n); 609 n = input.read(buffer); 610 } 611 } catch (IOException e) { 612 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 613 } finally { 614 contentResponse.disconnect(); 615 } 616 } catch (MalformedURLException ex) { 617 618 throw new BoxAPIException("Could not generate representation content URL"); 619 } 620 } 621 622 /** 623 * Updates the information about this file with any info fields that have been modified locally. 624 * 625 * <p>The only fields that will be updated are the ones that have been modified locally. For example, the following 626 * code won't update any information (or even send a network request) since none of the info's fields were 627 * changed:</p> 628 * 629 * <pre>BoxFile file = new File(api, id); 630 * BoxFile.Info info = file.getInfo(); 631 * file.updateInfo(info);</pre> 632 * 633 * @param info the updated info. 634 */ 635 public void updateInfo(BoxFile.Info info) { 636 URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 637 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); 638 request.setBody(info.getPendingChanges()); 639 BoxJSONResponse response = (BoxJSONResponse) request.send(); 640 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 641 info.update(jsonObject); 642 } 643 644 /** 645 * Gets any previous versions of this file. Note that only users with premium accounts will be able to retrieve 646 * previous versions of their files. 647 * 648 * @return a list of previous file versions. 649 */ 650 public Collection<BoxFileVersion> getVersions() { 651 URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 652 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 653 BoxJSONResponse response = (BoxJSONResponse) request.send(); 654 655 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 656 JsonArray entries = jsonObject.get("entries").asArray(); 657 Collection<BoxFileVersion> versions = new ArrayList<BoxFileVersion>(); 658 for (JsonValue entry : entries) { 659 versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID())); 660 } 661 662 return versions; 663 } 664 665 /** 666 * Checks if the file can be successfully uploaded by using the preflight check. 667 * 668 * @param name the name to give the uploaded file or null to use existing name. 669 * @param fileSize the size of the file used for account capacity calculations. 670 * @param parentID the ID of the parent folder that the new version is being uploaded to. 671 * @deprecated This method will be removed in future versions of the SDK; use canUploadVersion(String, long) instead 672 */ 673 @Deprecated 674 public void canUploadVersion(String name, long fileSize, String parentID) { 675 URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 676 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS"); 677 678 JsonObject parent = new JsonObject(); 679 parent.add("id", parentID); 680 681 JsonObject preflightInfo = new JsonObject(); 682 preflightInfo.add("parent", parent); 683 if (name != null) { 684 preflightInfo.add("name", name); 685 } 686 687 preflightInfo.add("size", fileSize); 688 689 request.setBody(preflightInfo.toString()); 690 BoxAPIResponse response = request.send(); 691 response.disconnect(); 692 } 693 694 /** 695 * Checks if a new version of the file can be uploaded with the specified name. 696 * @param name the new name for the file. 697 * @return whether or not the file version can be uploaded. 698 */ 699 public boolean canUploadVersion(String name) { 700 return this.canUploadVersion(name, 0); 701 } 702 703 /** 704 * Checks if a new version of the file can be uploaded with the specified name and size. 705 * @param name the new name for the file. 706 * @param fileSize the size of the new version content in bytes. 707 * @return whether or not the file version can be uploaded. 708 */ 709 public boolean canUploadVersion(String name, long fileSize) { 710 711 URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 712 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS"); 713 714 JsonObject preflightInfo = new JsonObject(); 715 if (name != null) { 716 preflightInfo.add("name", name); 717 } 718 719 preflightInfo.add("size", fileSize); 720 721 request.setBody(preflightInfo.toString()); 722 try { 723 BoxAPIResponse response = request.send(); 724 725 return response.getResponseCode() == 200; 726 } catch (BoxAPIException ex) { 727 728 if (ex.getResponseCode() >= 400 && ex.getResponseCode() < 500) { 729 // This looks like an error response, meaning the upload would fail 730 return false; 731 } else { 732 // This looks like a network error or server error, rethrow exception 733 throw ex; 734 } 735 } 736 } 737 738 /** 739 * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts 740 * will be able to view and recover previous versions of the file. 741 * 742 * @param fileContent a stream containing the new file contents. 743 * @deprecated use uploadNewVersion() instead. 744 */ 745 @Deprecated 746 public void uploadVersion(InputStream fileContent) { 747 this.uploadVersion(fileContent, null); 748 } 749 750 /** 751 * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts 752 * will be able to view and recover previous versions of the file. 753 * 754 * @param fileContent a stream containing the new file contents. 755 * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. 756 * @deprecated use uploadNewVersion() instead. 757 */ 758 @Deprecated 759 public void uploadVersion(InputStream fileContent, String fileContentSHA1) { 760 this.uploadVersion(fileContent, fileContentSHA1, null); 761 } 762 763 /** 764 * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts 765 * will be able to view and recover previous versions of the file. 766 * 767 * @param fileContent a stream containing the new file contents. 768 * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. 769 * @param modified the date that the new version was modified. 770 * @deprecated use uploadNewVersion() instead. 771 */ 772 @Deprecated 773 public void uploadVersion(InputStream fileContent, String fileContentSHA1, Date modified) { 774 this.uploadVersion(fileContent, fileContentSHA1, modified, 0, null); 775 } 776 777 /** 778 * Uploads a new version of this file, replacing the current version, while reporting the progress to a 779 * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions 780 * of the file. 781 * 782 * @param fileContent a stream containing the new file contents. 783 * @param modified the date that the new version was modified. 784 * @param fileSize the size of the file used for determining the progress of the upload. 785 * @param listener a listener for monitoring the upload's progress. 786 * @deprecated use uploadNewVersion() instead. 787 */ 788 @Deprecated 789 public void uploadVersion(InputStream fileContent, Date modified, long fileSize, ProgressListener listener) { 790 this.uploadVersion(fileContent, null, modified, fileSize, listener); 791 } 792 793 /** 794 * Uploads a new version of this file, replacing the current version, while reporting the progress to a 795 * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions 796 * of the file. 797 * 798 * @param fileContent a stream containing the new file contents. 799 * @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the Content-MD5 header 800 * @param modified the date that the new version was modified. 801 * @param fileSize the size of the file used for determining the progress of the upload. 802 * @param listener a listener for monitoring the upload's progress. 803 * @deprecated use uploadNewVersion() instead. 804 */ 805 @Deprecated 806 public void uploadVersion(InputStream fileContent, String fileContentSHA1, Date modified, long fileSize, 807 ProgressListener listener) { 808 this.uploadNewVersion(fileContent, fileContentSHA1, modified, fileSize, listener); 809 return; 810 } 811 812 /** 813 * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts 814 * will be able to view and recover previous versions of the file. 815 * 816 * @param fileContent a stream containing the new file contents. 817 * @return the uploaded file version. 818 */ 819 public BoxFile.Info uploadNewVersion(InputStream fileContent) { 820 return this.uploadNewVersion(fileContent, null); 821 } 822 823 /** 824 * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts 825 * will be able to view and recover previous versions of the file. 826 * 827 * @param fileContent a stream containing the new file contents. 828 * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. 829 * @return the uploaded file version. 830 */ 831 public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1) { 832 return this.uploadNewVersion(fileContent, fileContentSHA1, null); 833 } 834 835 /** 836 * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts 837 * will be able to view and recover previous versions of the file. 838 * 839 * @param fileContent a stream containing the new file contents. 840 * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. 841 * @param modified the date that the new version was modified. 842 * @return the uploaded file version. 843 */ 844 public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified) { 845 return this.uploadNewVersion(fileContent, fileContentSHA1, modified, 0, null); 846 } 847 848 /** 849 * Uploads a new version of this file, replacing the current version, while reporting the progress to a 850 * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions 851 * of the file. 852 * 853 * @param fileContent a stream containing the new file contents. 854 * @param modified the date that the new version was modified. 855 * @param fileSize the size of the file used for determining the progress of the upload. 856 * @param listener a listener for monitoring the upload's progress. 857 * @return the uploaded file version. 858 */ 859 public BoxFile.Info uploadNewVersion(InputStream fileContent, Date modified, long fileSize, 860 ProgressListener listener) { 861 return this.uploadNewVersion(fileContent, null, modified, fileSize, listener); 862 } 863 864 /** 865 * Uploads a new version of this file, replacing the current version, while reporting the progress to a 866 * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions 867 * of the file. 868 * 869 * @param fileContent a stream containing the new file contents. 870 * @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the Content-MD5 header 871 * @param modified the date that the new version was modified. 872 * @param fileSize the size of the file used for determining the progress of the upload. 873 * @param listener a listener for monitoring the upload's progress. 874 * @return the uploaded file version. 875 */ 876 public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified, long fileSize, 877 ProgressListener listener) { 878 URL uploadURL = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 879 BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL); 880 881 if (fileSize > 0) { 882 request.setFile(fileContent, "", fileSize); 883 } else { 884 request.setFile(fileContent, ""); 885 } 886 887 if (fileContentSHA1 != null) { 888 request.setContentSHA1(fileContentSHA1); 889 } 890 891 if (modified != null) { 892 request.putField("content_modified_at", modified); 893 } 894 895 BoxJSONResponse response; 896 if (listener == null) { 897 response = (BoxJSONResponse) request.send(); 898 } else { 899 response = (BoxJSONResponse) request.send(listener); 900 } 901 902 String fileJSON = response.getJsonObject().get("entries").asArray().get(0).toString(); 903 904 return new BoxFile.Info(fileJSON); 905 } 906 907 /** 908 * Gets an expiring URL for creating an embedded preview session. The URL will expire after 60 seconds and the 909 * preview session will expire after 60 minutes. 910 * 911 * @return the expiring preview link 912 */ 913 public URL getPreviewLink() { 914 BoxFile.Info info = this.getInfo("expiring_embed_link"); 915 916 return info.getPreviewLink(); 917 } 918 919 920 /** 921 * Retrieves a thumbnail, or smaller image representation, of this file. Sizes of 32x32, 64x64, 128x128, 922 * and 256x256 can be returned in the .png format and sizes of 32x32, 94x94, 160x160, and 320x320 can be returned 923 * in the .jpg format. 924 * 925 * @param fileType either PNG of JPG 926 * @param minWidth minimum width 927 * @param minHeight minimum height 928 * @param maxWidth maximum width 929 * @param maxHeight maximum height 930 * @return the byte array of the thumbnail image 931 */ 932 public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) { 933 QueryStringBuilder builder = new QueryStringBuilder(); 934 builder.appendParam("min_width", minWidth); 935 builder.appendParam("min_height", minHeight); 936 builder.appendParam("max_width", maxWidth); 937 builder.appendParam("max_height", maxHeight); 938 939 URLTemplate template; 940 if (fileType == ThumbnailFileType.PNG) { 941 template = GET_THUMBNAIL_PNG_TEMPLATE; 942 } else if (fileType == ThumbnailFileType.JPG) { 943 template = GET_THUMBNAIL_JPG_TEMPLATE; 944 } else { 945 throw new BoxAPIException("Unsupported thumbnail file type"); 946 } 947 URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); 948 949 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 950 BoxAPIResponse response = request.send(); 951 952 ByteArrayOutputStream thumbOut = new ByteArrayOutputStream(); 953 InputStream body = response.getBody(); 954 byte[] buffer = new byte[BUFFER_SIZE]; 955 try { 956 int n = body.read(buffer); 957 while (n != -1) { 958 thumbOut.write(buffer, 0, n); 959 n = body.read(buffer); 960 } 961 } catch (IOException e) { 962 throw new BoxAPIException("Error reading thumbnail bytes from response body", e); 963 } finally { 964 response.disconnect(); 965 } 966 967 return thumbOut.toByteArray(); 968 } 969 970 /** 971 * Gets a list of any comments on this file. 972 * 973 * @return a list of comments on this file. 974 */ 975 public List<BoxComment.Info> getComments() { 976 URL url = GET_COMMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); 977 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 978 BoxJSONResponse response = (BoxJSONResponse) request.send(); 979 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 980 981 int totalCount = responseJSON.get("total_count").asInt(); 982 List<BoxComment.Info> comments = new ArrayList<BoxComment.Info>(totalCount); 983 JsonArray entries = responseJSON.get("entries").asArray(); 984 for (JsonValue value : entries) { 985 JsonObject commentJSON = value.asObject(); 986 BoxComment comment = new BoxComment(this.getAPI(), commentJSON.get("id").asString()); 987 BoxComment.Info info = comment.new Info(commentJSON); 988 comments.add(info); 989 } 990 991 return comments; 992 } 993 994 /** 995 * Gets a list of any tasks on this file with requested fields. 996 * 997 * @param fields optional fields to retrieve for this task. 998 * @return a list of tasks on this file. 999 */ 1000 public List<BoxTask.Info> getTasks(String... fields) { 1001 QueryStringBuilder builder = new QueryStringBuilder(); 1002 if (fields.length > 0) { 1003 builder.appendParam("fields", fields).toString(); 1004 } 1005 URL url = GET_TASKS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); 1006 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 1007 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1008 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 1009 1010 int totalCount = responseJSON.get("total_count").asInt(); 1011 List<BoxTask.Info> tasks = new ArrayList<BoxTask.Info>(totalCount); 1012 JsonArray entries = responseJSON.get("entries").asArray(); 1013 for (JsonValue value : entries) { 1014 JsonObject taskJSON = value.asObject(); 1015 BoxTask task = new BoxTask(this.getAPI(), taskJSON.get("id").asString()); 1016 BoxTask.Info info = task.new Info(taskJSON); 1017 tasks.add(info); 1018 } 1019 1020 return tasks; 1021 } 1022 1023 /** 1024 * Creates metadata on this file in the global properties template. 1025 * 1026 * @param metadata The new metadata values. 1027 * @return the metadata returned from the server. 1028 */ 1029 public Metadata createMetadata(Metadata metadata) { 1030 return this.createMetadata(Metadata.DEFAULT_METADATA_TYPE, metadata); 1031 } 1032 1033 /** 1034 * Creates metadata on this file in the specified template type. 1035 * 1036 * @param typeName the metadata template type name. 1037 * @param metadata the new metadata values. 1038 * @return the metadata returned from the server. 1039 */ 1040 public Metadata createMetadata(String typeName, Metadata metadata) { 1041 String scope = Metadata.scopeBasedOnType(typeName); 1042 return this.createMetadata(typeName, scope, metadata); 1043 } 1044 1045 /** 1046 * Creates metadata on this file in the specified template type. 1047 * 1048 * @param typeName the metadata template type name. 1049 * @param scope the metadata scope (global or enterprise). 1050 * @param metadata the new metadata values. 1051 * @return the metadata returned from the server. 1052 */ 1053 public Metadata createMetadata(String typeName, String scope, Metadata metadata) { 1054 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); 1055 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "POST"); 1056 request.addHeader("Content-Type", "application/json"); 1057 request.setBody(metadata.toString()); 1058 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1059 return new Metadata(JsonObject.readFrom(response.getJSON())); 1060 } 1061 1062 /** 1063 * Sets the provided metadata on the file, overwriting any existing metadata keys already present. 1064 * 1065 * @param templateName the name of the metadata template. 1066 * @param scope the scope of the template (usually "global" or "enterprise"). 1067 * @param metadata the new metadata values. 1068 * @return the metadata returned from the server. 1069 */ 1070 public Metadata setMetadata(String templateName, String scope, Metadata metadata) { 1071 Metadata metadataValue = null; 1072 1073 try { 1074 metadataValue = this.createMetadata(templateName, scope, metadata); 1075 } catch (BoxAPIException e) { 1076 if (e.getResponseCode() == 409) { 1077 Metadata metadataToUpdate = new Metadata(scope, templateName); 1078 for (JsonValue value : metadata.getOperations()) { 1079 if (value.asObject().get("value").isNumber()) { 1080 metadataToUpdate.add(value.asObject().get("path").asString(), 1081 value.asObject().get("value").asFloat()); 1082 } else if (value.asObject().get("value").isString()) { 1083 metadataToUpdate.add(value.asObject().get("path").asString(), 1084 value.asObject().get("value").asString()); 1085 } else if (value.asObject().get("value").isArray()) { 1086 ArrayList<String> list = new ArrayList<String>(); 1087 for (JsonValue jsonValue : value.asObject().get("value").asArray()) { 1088 list.add(jsonValue.asString()); 1089 } 1090 metadataToUpdate.add(value.asObject().get("path").asString(), list); 1091 } 1092 } 1093 metadataValue = this.updateMetadata(metadataToUpdate); 1094 } else { 1095 throw e; 1096 } 1097 } 1098 1099 return metadataValue; 1100 } 1101 1102 /** 1103 * Adds a metadata classification to the specified file. 1104 * 1105 * @param classificationType the metadata classification type. 1106 * @return the metadata classification type added to the file. 1107 */ 1108 public String addClassification(String classificationType) { 1109 Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); 1110 Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, 1111 "enterprise", metadata); 1112 1113 return classification.getString(Metadata.CLASSIFICATION_KEY); 1114 } 1115 1116 /** 1117 * Updates a metadata classification on the specified file. 1118 * 1119 * @param classificationType the metadata classification type. 1120 * @return the new metadata classification type updated on the file. 1121 */ 1122 public String updateClassification(String classificationType) { 1123 Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); 1124 metadata.add("/Box__Security__Classification__Key", classificationType); 1125 Metadata classification = this.updateMetadata(metadata); 1126 1127 return classification.getString(Metadata.CLASSIFICATION_KEY); 1128 } 1129 1130 /** 1131 * Attempts to add classification to a file. If classification already exists then do update. 1132 * 1133 * @param classificationType the metadata classification type. 1134 * @return the metadata classification type on the file. 1135 */ 1136 public String setClassification(String classificationType) { 1137 Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); 1138 Metadata classification = null; 1139 1140 try { 1141 classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); 1142 } catch (BoxAPIException e) { 1143 if (e.getResponseCode() == 409) { 1144 metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); 1145 metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); 1146 classification = this.updateMetadata(metadata); 1147 } else { 1148 throw e; 1149 } 1150 } 1151 1152 return classification.getString(Metadata.CLASSIFICATION_KEY); 1153 } 1154 1155 /** 1156 * Gets the classification type for the specified file. 1157 * 1158 * @return the metadata classification type on the file. 1159 */ 1160 public String getClassification() { 1161 Metadata metadata; 1162 try { 1163 metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); 1164 1165 } catch (BoxAPIException e) { 1166 JsonObject responseObject = JsonObject.readFrom(e.getResponse()); 1167 String code = responseObject.get("code").asString(); 1168 1169 if (e.getResponseCode() == 404 && code.equals("instance_not_found")) { 1170 return null; 1171 } else { 1172 throw e; 1173 } 1174 } 1175 1176 return metadata.getString(Metadata.CLASSIFICATION_KEY); 1177 } 1178 1179 /** 1180 * Deletes the classification on the file. 1181 */ 1182 public void deleteClassification() { 1183 this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise"); 1184 } 1185 1186 /** 1187 * Locks a file. 1188 * 1189 * @return the lock returned from the server. 1190 */ 1191 public BoxLock lock() { 1192 return this.lock(null, false); 1193 } 1194 1195 /** 1196 * Locks a file. 1197 * 1198 * @param isDownloadPrevented is downloading of file prevented when locked. 1199 * @return the lock returned from the server. 1200 */ 1201 public BoxLock lock(boolean isDownloadPrevented) { 1202 return this.lock(null, isDownloadPrevented); 1203 } 1204 1205 /** 1206 * Locks a file. 1207 * 1208 * @param expiresAt expiration date of the lock. 1209 * @return the lock returned from the server. 1210 */ 1211 public BoxLock lock(Date expiresAt) { 1212 return this.lock(expiresAt, false); 1213 } 1214 1215 /** 1216 * Locks a file. 1217 * 1218 * @param expiresAt expiration date of the lock. 1219 * @param isDownloadPrevented is downloading of file prevented when locked. 1220 * @return the lock returned from the server. 1221 */ 1222 public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) { 1223 String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); 1224 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 1225 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); 1226 1227 JsonObject lockConfig = new JsonObject(); 1228 lockConfig.add("type", "lock"); 1229 if (expiresAt != null) { 1230 lockConfig.add("expires_at", BoxDateFormat.format(expiresAt)); 1231 } 1232 lockConfig.add("is_download_prevented", isDownloadPrevented); 1233 1234 JsonObject requestJSON = new JsonObject(); 1235 requestJSON.add("lock", lockConfig); 1236 request.setBody(requestJSON.toString()); 1237 1238 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1239 1240 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 1241 JsonValue lockValue = responseJSON.get("lock"); 1242 JsonObject lockJSON = JsonObject.readFrom(lockValue.toString()); 1243 1244 return new BoxLock(lockJSON, this.getAPI()); 1245 } 1246 1247 /** 1248 * Unlocks a file. 1249 */ 1250 public void unlock() { 1251 String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); 1252 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 1253 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); 1254 1255 JsonObject lockObject = new JsonObject(); 1256 lockObject.add("lock", JsonObject.NULL); 1257 1258 request.setBody(lockObject.toString()); 1259 request.send(); 1260 } 1261 1262 /** 1263 * Used to retrieve all metadata associated with the file. 1264 * 1265 * @param fields the optional fields to retrieve. 1266 * @return An iterable of metadata instances associated with the file. 1267 */ 1268 public Iterable<Metadata> getAllMetadata(String... fields) { 1269 return Metadata.getAllMetadata(this, fields); 1270 } 1271 1272 /** 1273 * Gets the file properties metadata. 1274 * 1275 * @return the metadata returned from the server. 1276 */ 1277 public Metadata getMetadata() { 1278 return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE); 1279 } 1280 1281 /** 1282 * Gets the file metadata of specified template type. 1283 * 1284 * @param typeName the metadata template type name. 1285 * @return the metadata returned from the server. 1286 */ 1287 public Metadata getMetadata(String typeName) { 1288 String scope = Metadata.scopeBasedOnType(typeName); 1289 return this.getMetadata(typeName, scope); 1290 } 1291 1292 /** 1293 * Gets the file metadata of specified template type. 1294 * 1295 * @param typeName the metadata template type name. 1296 * @param scope the metadata scope (global or enterprise). 1297 * @return the metadata returned from the server. 1298 */ 1299 public Metadata getMetadata(String typeName, String scope) { 1300 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); 1301 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 1302 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1303 return new Metadata(JsonObject.readFrom(response.getJSON())); 1304 } 1305 1306 /** 1307 * Updates the file metadata. 1308 * 1309 * @param metadata the new metadata values. 1310 * @return the metadata returned from the server. 1311 */ 1312 public Metadata updateMetadata(Metadata metadata) { 1313 String scope; 1314 if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) { 1315 scope = Metadata.GLOBAL_METADATA_SCOPE; 1316 } else { 1317 scope = Metadata.ENTERPRISE_METADATA_SCOPE; 1318 } 1319 1320 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), 1321 scope, metadata.getTemplateName()); 1322 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); 1323 request.addHeader("Content-Type", "application/json-patch+json"); 1324 request.setBody(metadata.getPatch()); 1325 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1326 return new Metadata(JsonObject.readFrom(response.getJSON())); 1327 } 1328 1329 /** 1330 * Deletes the file properties metadata. 1331 */ 1332 public void deleteMetadata() { 1333 this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE); 1334 } 1335 1336 /** 1337 * Deletes the file metadata of specified template type. 1338 * 1339 * @param typeName the metadata template type name. 1340 */ 1341 public void deleteMetadata(String typeName) { 1342 String scope = Metadata.scopeBasedOnType(typeName); 1343 this.deleteMetadata(typeName, scope); 1344 } 1345 1346 /** 1347 * Deletes the file metadata of specified template type. 1348 * 1349 * @param typeName the metadata template type name. 1350 * @param scope the metadata scope (global or enterprise). 1351 */ 1352 public void deleteMetadata(String typeName, String scope) { 1353 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); 1354 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); 1355 request.send(); 1356 } 1357 1358 /** 1359 * Used to retrieve the watermark for the file. 1360 * If the file does not have a watermark applied to it, a 404 Not Found will be returned by API. 1361 * 1362 * @param fields the fields to retrieve. 1363 * @return the watermark associated with the file. 1364 */ 1365 public BoxWatermark getWatermark(String... fields) { 1366 return this.getWatermark(FILE_URL_TEMPLATE, fields); 1367 } 1368 1369 /** 1370 * Used to apply or update the watermark for the file. 1371 * 1372 * @return the watermark associated with the file. 1373 */ 1374 public BoxWatermark applyWatermark() { 1375 return this.applyWatermark(FILE_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT); 1376 } 1377 1378 /** 1379 * Removes a watermark from the file. 1380 * If the file did not have a watermark applied to it, a 404 Not Found will be returned by API. 1381 */ 1382 public void removeWatermark() { 1383 this.removeWatermark(FILE_URL_TEMPLATE); 1384 } 1385 1386 /** 1387 * {@inheritDoc} 1388 */ 1389 @Override 1390 public BoxFile.Info setCollections(BoxCollection... collections) { 1391 JsonArray jsonArray = new JsonArray(); 1392 for (BoxCollection collection : collections) { 1393 JsonObject collectionJSON = new JsonObject(); 1394 collectionJSON.add("id", collection.getID()); 1395 jsonArray.add(collectionJSON); 1396 } 1397 JsonObject infoJSON = new JsonObject(); 1398 infoJSON.add("collections", jsonArray); 1399 1400 String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); 1401 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 1402 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); 1403 request.setBody(infoJSON.toString()); 1404 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1405 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 1406 return new Info(jsonObject); 1407 } 1408 1409 /** 1410 * Creates an upload session to create a new version of a file in chunks. 1411 * This will first verify that the version can be created and then open a session for uploading pieces of the file. 1412 * @param fileSize the size of the file that will be uploaded. 1413 * @return the created upload session instance. 1414 */ 1415 public BoxFileUploadSession.Info createUploadSession(long fileSize) { 1416 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1417 1418 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); 1419 request.addHeader("Content-Type", "application/json"); 1420 1421 JsonObject body = new JsonObject(); 1422 body.add("file_size", fileSize); 1423 request.setBody(body.toString()); 1424 1425 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1426 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 1427 1428 String sessionId = jsonObject.get("id").asString(); 1429 BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId); 1430 return session.new Info(jsonObject); 1431 } 1432 1433 /** 1434 * Creates a new version of a file. 1435 * @param inputStream the stream instance that contains the data. 1436 * @param fileSize the size of the file that will be uploaded. 1437 * @return the created file instance. 1438 * @throws InterruptedException when a thread execution is interrupted. 1439 * @throws IOException when reading a stream throws exception. 1440 */ 1441 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize) 1442 throws InterruptedException, IOException { 1443 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1444 return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize); 1445 } 1446 1447 /** 1448 * Creates a new version of a file. Also sets file attributes. 1449 * @param inputStream the stream instance that contains the data. 1450 * @param fileSize the size of the file that will be uploaded. 1451 * @param fileAttributes file attributes to set 1452 * @return the created file instance. 1453 * @throws InterruptedException when a thread execution is interrupted. 1454 * @throws IOException when reading a stream throws exception. 1455 */ 1456 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, Map<String, String> fileAttributes) 1457 throws InterruptedException, IOException { 1458 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1459 return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); 1460 } 1461 1462 /** 1463 * Creates a new version of a file using specified number of parallel http connections. 1464 * @param inputStream the stream instance that contains the data. 1465 * @param fileSize the size of the file that will be uploaded. 1466 * @param nParallelConnections number of parallel http connections to use 1467 * @param timeOut time to wait before killing the job 1468 * @param unit time unit for the time wait value 1469 * @return the created file instance. 1470 * @throws InterruptedException when a thread execution is interrupted. 1471 * @throws IOException when reading a stream throws exception. 1472 */ 1473 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, 1474 int nParallelConnections, long timeOut, TimeUnit unit) 1475 throws InterruptedException, IOException { 1476 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1477 return new LargeFileUpload(nParallelConnections, timeOut, unit) 1478 .upload(this.getAPI(), inputStream, url, fileSize); 1479 } 1480 1481 /** 1482 * Creates a new version of a file using specified number of parallel http connections. Also sets file attributes. 1483 * @param inputStream the stream instance that contains the data. 1484 * @param fileSize the size of the file that will be uploaded. 1485 * @param nParallelConnections number of parallel http connections to use 1486 * @param timeOut time to wait before killing the job 1487 * @param unit time unit for the time wait value 1488 * @param fileAttributes file attributes to set 1489 * @return the created file instance. 1490 * @throws InterruptedException when a thread execution is interrupted. 1491 * @throws IOException when reading a stream throws exception. 1492 */ 1493 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, 1494 int nParallelConnections, long timeOut, TimeUnit unit, 1495 Map<String, String> fileAttributes) 1496 throws InterruptedException, IOException { 1497 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1498 return new LargeFileUpload(nParallelConnections, timeOut, unit) 1499 .upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); 1500 } 1501 1502 private BoxCollaboration.Info collaborate(JsonObject accessibleByField, BoxCollaboration.Role role, 1503 Boolean notify, Boolean canViewPath) { 1504 1505 JsonObject itemField = new JsonObject(); 1506 itemField.add("id", this.getID()); 1507 itemField.add("type", "file"); 1508 1509 return BoxCollaboration.create(this.getAPI(), accessibleByField, itemField, role, notify, canViewPath); 1510 } 1511 1512 /** 1513 * Adds a collaborator to this file. 1514 * 1515 * @param collaborator the collaborator to add. 1516 * @param role the role of the collaborator. 1517 * @param notify determines if the user (or all the users in the group) will receive email notifications. 1518 * @param canViewPath whether view path collaboration feature is enabled or not. 1519 * @return info about the new collaboration. 1520 */ 1521 public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role, 1522 Boolean notify, Boolean canViewPath) { 1523 JsonObject accessibleByField = new JsonObject(); 1524 accessibleByField.add("id", collaborator.getID()); 1525 1526 if (collaborator instanceof BoxUser) { 1527 accessibleByField.add("type", "user"); 1528 } else if (collaborator instanceof BoxGroup) { 1529 accessibleByField.add("type", "group"); 1530 } else { 1531 throw new IllegalArgumentException("The given collaborator is of an unknown type."); 1532 } 1533 return this.collaborate(accessibleByField, role, notify, canViewPath); 1534 } 1535 1536 1537 /** 1538 * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box 1539 * account. 1540 * 1541 * @param email the email address of the collaborator to add. 1542 * @param role the role of the collaborator. 1543 * @param notify determines if the user (or all the users in the group) will receive email notifications. 1544 * @param canViewPath whether view path collaboration feature is enabled or not. 1545 * @return info about the new collaboration. 1546 */ 1547 public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role, 1548 Boolean notify, Boolean canViewPath) { 1549 JsonObject accessibleByField = new JsonObject(); 1550 accessibleByField.add("login", email); 1551 accessibleByField.add("type", "user"); 1552 1553 return this.collaborate(accessibleByField, role, notify, canViewPath); 1554 } 1555 1556 /** 1557 * Used to retrieve all collaborations associated with the item. 1558 * 1559 * @param fields the optional fields to retrieve. 1560 * @return An iterable of metadata instances associated with the item. 1561 */ 1562 public BoxResourceIterable<BoxCollaboration.Info> getAllFileCollaborations(String... fields) { 1563 return BoxCollaboration.getAllFileCollaborations(this.getAPI(), this.getID(), 1564 GET_COLLABORATORS_PAGE_SIZE, fields); 1565 1566 } 1567 1568 /** 1569 * Contains information about a BoxFile. 1570 */ 1571 public class Info extends BoxItem.Info { 1572 private String sha1; 1573 private String versionNumber; 1574 private long commentCount; 1575 private EnumSet<Permission> permissions; 1576 private String extension; 1577 private boolean isPackage; 1578 private BoxFileVersion version; 1579 private URL previewLink; 1580 private BoxLock lock; 1581 private boolean isWatermarked; 1582 private Boolean isExternallyOwned; 1583 private JsonObject metadata; 1584 private Map<String, Map<String, Metadata>> metadataMap; 1585 private List<Representation> representations; 1586 private List<String> allowedInviteeRoles; 1587 private Boolean hasCollaborations; 1588 1589 /** 1590 * Constructs an empty Info object. 1591 */ 1592 public Info() { 1593 super(); 1594 } 1595 1596 /** 1597 * Constructs an Info object by parsing information from a JSON string. 1598 * 1599 * @param json the JSON string to parse. 1600 */ 1601 public Info(String json) { 1602 super(json); 1603 } 1604 1605 /** 1606 * Constructs an Info object using an already parsed JSON object. 1607 * 1608 * @param jsonObject the parsed JSON object. 1609 */ 1610 public Info(JsonObject jsonObject) { 1611 super(jsonObject); 1612 } 1613 1614 @Override 1615 public BoxFile getResource() { 1616 return BoxFile.this; 1617 } 1618 1619 /** 1620 * Gets the SHA1 hash of the file. 1621 * 1622 * @return the SHA1 hash of the file. 1623 */ 1624 public String getSha1() { 1625 return this.sha1; 1626 } 1627 1628 /** 1629 * Gets the lock of the file. 1630 * 1631 * @return the lock of the file. 1632 */ 1633 public BoxLock getLock() { 1634 return this.lock; 1635 } 1636 1637 /** 1638 * Gets the current version number of the file. 1639 * 1640 * @return the current version number of the file. 1641 */ 1642 public String getVersionNumber() { 1643 return this.versionNumber; 1644 } 1645 1646 /** 1647 * Gets the number of comments on the file. 1648 * 1649 * @return the number of comments on the file. 1650 */ 1651 public long getCommentCount() { 1652 return this.commentCount; 1653 } 1654 1655 /** 1656 * Gets the permissions that the current user has on the file. 1657 * 1658 * @return the permissions that the current user has on the file. 1659 */ 1660 public EnumSet<Permission> getPermissions() { 1661 return this.permissions; 1662 } 1663 1664 /** 1665 * Gets the extension suffix of the file, excluding the dot. 1666 * 1667 * @return the extension of the file. 1668 */ 1669 public String getExtension() { 1670 return this.extension; 1671 } 1672 1673 /** 1674 * Gets whether or not the file is an OSX package. 1675 * 1676 * @return true if the file is an OSX package; otherwise false. 1677 */ 1678 public boolean getIsPackage() { 1679 return this.isPackage; 1680 } 1681 1682 /** 1683 * Gets the current version details of the file. 1684 * 1685 * @return the current version details of the file. 1686 */ 1687 public BoxFileVersion getVersion() { 1688 return this.version; 1689 } 1690 1691 /** 1692 * Gets the current expiring preview link. 1693 * 1694 * @return the expiring preview link 1695 */ 1696 public URL getPreviewLink() { 1697 return this.previewLink; 1698 } 1699 1700 /** 1701 * Gets flag indicating whether this file is Watermarked. 1702 * 1703 * @return whether the file is watermarked or not 1704 */ 1705 public boolean getIsWatermarked() { 1706 return this.isWatermarked; 1707 } 1708 1709 /** 1710 * Returns the allowed invitee roles for this file item. 1711 * 1712 * @return the list of roles allowed for invited collaborators. 1713 */ 1714 public List<String> getAllowedInviteeRoles() { 1715 return this.allowedInviteeRoles; 1716 } 1717 1718 /** 1719 * Returns the indicator for whether this file item has collaborations. 1720 * 1721 * @return indicator for whether this file item has collaborations. 1722 */ 1723 public Boolean getHasCollaborations() { 1724 return this.hasCollaborations; 1725 } 1726 1727 /** 1728 * Gets the metadata on this file associated with a specified scope and template. 1729 * Makes an attempt to get metadata that was retrieved using getInfo(String ...) method. If no result is found 1730 * then makes an API call to get metadata 1731 * @param templateName the metadata template type name. 1732 * @param scope the scope of the template (usually "global" or "enterprise"). 1733 * @return the metadata returned from the server. 1734 */ 1735 public Metadata getMetadata(String templateName, String scope) { 1736 try { 1737 return this.metadataMap.get(scope).get(templateName); 1738 } catch (NullPointerException e) { 1739 return null; 1740 } 1741 } 1742 1743 /** 1744 * Returns the field for indicating whether a file is owned by a user outside the enterprise. 1745 * @return indicator for whether or not the file is owned by a user outside the enterprise. 1746 */ 1747 public boolean getIsExternallyOwned() { 1748 return this.isExternallyOwned; 1749 } 1750 1751 /** 1752 * Get file's representations. 1753 * @return list of representations 1754 */ 1755 public List<Representation> getRepresentations() { 1756 return this.representations; 1757 } 1758 1759 @Override 1760 protected void parseJSONMember(JsonObject.Member member) { 1761 super.parseJSONMember(member); 1762 1763 String memberName = member.getName(); 1764 JsonValue value = member.getValue(); 1765 try { 1766 if (memberName.equals("sha1")) { 1767 this.sha1 = value.asString(); 1768 } else if (memberName.equals("version_number")) { 1769 this.versionNumber = value.asString(); 1770 } else if (memberName.equals("comment_count")) { 1771 this.commentCount = value.asLong(); 1772 } else if (memberName.equals("permissions")) { 1773 this.permissions = this.parsePermissions(value.asObject()); 1774 } else if (memberName.equals("extension")) { 1775 this.extension = value.asString(); 1776 } else if (memberName.equals("is_package")) { 1777 this.isPackage = value.asBoolean(); 1778 } else if (memberName.equals("has_collaborations")) { 1779 this.hasCollaborations = value.asBoolean(); 1780 } else if (memberName.equals("is_externally_owned")) { 1781 this.isExternallyOwned = value.asBoolean(); 1782 } else if (memberName.equals("file_version")) { 1783 this.version = this.parseFileVersion(value.asObject()); 1784 } else if (memberName.equals("allowed_invitee_roles")) { 1785 this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray()); 1786 } else if (memberName.equals("expiring_embed_link")) { 1787 try { 1788 String urlString = member.getValue().asObject().get("url").asString(); 1789 this.previewLink = new URL(urlString); 1790 } catch (MalformedURLException e) { 1791 throw new BoxAPIException("Couldn't parse expiring_embed_link/url for file", e); 1792 } 1793 } else if (memberName.equals("lock")) { 1794 if (value.isNull()) { 1795 this.lock = null; 1796 } else { 1797 this.lock = new BoxLock(value.asObject(), BoxFile.this.getAPI()); 1798 } 1799 } else if (memberName.equals("watermark_info")) { 1800 JsonObject jsonObject = value.asObject(); 1801 this.isWatermarked = jsonObject.get("is_watermarked").asBoolean(); 1802 } else if (memberName.equals("metadata")) { 1803 JsonObject jsonObject = value.asObject(); 1804 this.metadataMap = Parsers.parseAndPopulateMetadataMap(jsonObject); 1805 } else if (memberName.equals("representations")) { 1806 JsonObject jsonObject = value.asObject(); 1807 this.representations = Parsers.parseRepresentations(jsonObject); 1808 } 1809 } catch (Exception e) { 1810 throw new BoxDeserializationException(memberName, value.toString(), e); 1811 } 1812 } 1813 1814 private EnumSet<Permission> parsePermissions(JsonObject jsonObject) { 1815 EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class); 1816 for (JsonObject.Member member : jsonObject) { 1817 JsonValue value = member.getValue(); 1818 if (value.isNull() || !value.asBoolean()) { 1819 continue; 1820 } 1821 1822 String memberName = member.getName(); 1823 if (memberName.equals("can_download")) { 1824 permissions.add(Permission.CAN_DOWNLOAD); 1825 } else if (memberName.equals("can_upload")) { 1826 permissions.add(Permission.CAN_UPLOAD); 1827 } else if (memberName.equals("can_rename")) { 1828 permissions.add(Permission.CAN_RENAME); 1829 } else if (memberName.equals("can_delete")) { 1830 permissions.add(Permission.CAN_DELETE); 1831 } else if (memberName.equals("can_share")) { 1832 permissions.add(Permission.CAN_SHARE); 1833 } else if (memberName.equals("can_set_share_access")) { 1834 permissions.add(Permission.CAN_SET_SHARE_ACCESS); 1835 } else if (memberName.equals("can_preview")) { 1836 permissions.add(Permission.CAN_PREVIEW); 1837 } else if (memberName.equals("can_comment")) { 1838 permissions.add(Permission.CAN_COMMENT); 1839 } 1840 } 1841 1842 return permissions; 1843 } 1844 1845 private BoxFileVersion parseFileVersion(JsonObject jsonObject) { 1846 return new BoxFileVersion(BoxFile.this.getAPI(), jsonObject, BoxFile.this.getID()); 1847 } 1848 1849 private List<String> parseAllowedInviteeRoles(JsonArray jsonArray) { 1850 List<String> roles = new ArrayList<String>(jsonArray.size()); 1851 for (JsonValue value : jsonArray) { 1852 roles.add(value.asString()); 1853 } 1854 1855 return roles; 1856 } 1857 } 1858 1859 /** 1860 * Enumerates the possible permissions that a user can have on a file. 1861 */ 1862 public enum Permission { 1863 /** 1864 * The user can download the file. 1865 */ 1866 CAN_DOWNLOAD("can_download"), 1867 1868 /** 1869 * The user can upload new versions of the file. 1870 */ 1871 CAN_UPLOAD("can_upload"), 1872 1873 /** 1874 * The user can rename the file. 1875 */ 1876 CAN_RENAME("can_rename"), 1877 1878 /** 1879 * The user can delete the file. 1880 */ 1881 CAN_DELETE("can_delete"), 1882 1883 /** 1884 * The user can share the file. 1885 */ 1886 CAN_SHARE("can_share"), 1887 1888 /** 1889 * The user can set the access level for shared links to the file. 1890 */ 1891 CAN_SET_SHARE_ACCESS("can_set_share_access"), 1892 1893 /** 1894 * The user can preview the file. 1895 */ 1896 CAN_PREVIEW("can_preview"), 1897 1898 /** 1899 * The user can comment on the file. 1900 */ 1901 CAN_COMMENT("can_comment"); 1902 1903 private final String jsonValue; 1904 1905 private Permission(String jsonValue) { 1906 this.jsonValue = jsonValue; 1907 } 1908 1909 static Permission fromJSONValue(String jsonValue) { 1910 return Permission.valueOf(jsonValue.toUpperCase()); 1911 } 1912 1913 String toJSONValue() { 1914 return this.jsonValue; 1915 } 1916 } 1917 1918}