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 BoxAPIResponse response = request.send(); 466 response.disconnect(); 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, menaing 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 } 1095 } 1096 1097 return metadataValue; 1098 } 1099 1100 /** 1101 * Adds a metadata classification to the specified file. 1102 * 1103 * @param classificationType the metadata classification type. 1104 * @return the metadata classification type added to the file. 1105 */ 1106 public String addClassification(String classificationType) { 1107 Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); 1108 Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, 1109 "enterprise", metadata); 1110 1111 return classification.getString(Metadata.CLASSIFICATION_KEY); 1112 } 1113 1114 /** 1115 * Updates a metadata classification on the specified file. 1116 * 1117 * @param classificationType the metadata classification type. 1118 * @return the new metadata classification type updated on the file. 1119 */ 1120 public String updateClassification(String classificationType) { 1121 Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); 1122 metadata.add("/Box__Security__Classification__Key", classificationType); 1123 Metadata classification = this.updateMetadata(metadata); 1124 1125 return classification.getString(Metadata.CLASSIFICATION_KEY); 1126 } 1127 1128 /** 1129 * Attempts to add classification to a file. If classification already exists then do update. 1130 * 1131 * @param classificationType the metadata classification type. 1132 * @return the metadata classification type on the file. 1133 */ 1134 public String setClassification(String classificationType) { 1135 Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); 1136 Metadata classification = null; 1137 1138 try { 1139 classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); 1140 } catch (BoxAPIException e) { 1141 if (e.getResponseCode() == 409) { 1142 metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); 1143 metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); 1144 classification = this.updateMetadata(metadata); 1145 } else { 1146 throw e; 1147 } 1148 } 1149 1150 return classification.getString(Metadata.CLASSIFICATION_KEY); 1151 } 1152 1153 /** 1154 * Gets the classification type for the specified file. 1155 * 1156 * @return the metadata classification type on the file. 1157 */ 1158 public String getClassification() { 1159 Metadata metadata; 1160 try { 1161 metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); 1162 1163 } catch (BoxAPIException e) { 1164 JsonObject responseObject = JsonObject.readFrom(e.getResponse()); 1165 String code = responseObject.get("code").asString(); 1166 1167 if (e.getResponseCode() == 404 && code.equals("instance_not_found")) { 1168 return null; 1169 } else { 1170 throw e; 1171 } 1172 } 1173 1174 return metadata.getString(Metadata.CLASSIFICATION_KEY); 1175 } 1176 1177 /** 1178 * Deletes the classification on the file. 1179 */ 1180 public void deleteClassification() { 1181 this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise"); 1182 } 1183 1184 /** 1185 * Locks a file. 1186 * 1187 * @return the lock returned from the server. 1188 */ 1189 public BoxLock lock() { 1190 return this.lock(null, false); 1191 } 1192 1193 /** 1194 * Locks a file. 1195 * 1196 * @param isDownloadPrevented is downloading of file prevented when locked. 1197 * @return the lock returned from the server. 1198 */ 1199 public BoxLock lock(boolean isDownloadPrevented) { 1200 return this.lock(null, isDownloadPrevented); 1201 } 1202 1203 /** 1204 * Locks a file. 1205 * 1206 * @param expiresAt expiration date of the lock. 1207 * @return the lock returned from the server. 1208 */ 1209 public BoxLock lock(Date expiresAt) { 1210 return this.lock(expiresAt, false); 1211 } 1212 1213 /** 1214 * Locks a file. 1215 * 1216 * @param expiresAt expiration date of the lock. 1217 * @param isDownloadPrevented is downloading of file prevented when locked. 1218 * @return the lock returned from the server. 1219 */ 1220 public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) { 1221 String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); 1222 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 1223 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); 1224 1225 JsonObject lockConfig = new JsonObject(); 1226 lockConfig.add("type", "lock"); 1227 if (expiresAt != null) { 1228 lockConfig.add("expires_at", BoxDateFormat.format(expiresAt)); 1229 } 1230 lockConfig.add("is_download_prevented", isDownloadPrevented); 1231 1232 JsonObject requestJSON = new JsonObject(); 1233 requestJSON.add("lock", lockConfig); 1234 request.setBody(requestJSON.toString()); 1235 1236 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1237 1238 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 1239 JsonValue lockValue = responseJSON.get("lock"); 1240 JsonObject lockJSON = JsonObject.readFrom(lockValue.toString()); 1241 1242 return new BoxLock(lockJSON, this.getAPI()); 1243 } 1244 1245 /** 1246 * Unlocks a file. 1247 */ 1248 public void unlock() { 1249 String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); 1250 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 1251 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); 1252 1253 JsonObject lockObject = new JsonObject(); 1254 lockObject.add("lock", JsonObject.NULL); 1255 1256 request.setBody(lockObject.toString()); 1257 request.send(); 1258 } 1259 1260 /** 1261 * Used to retrieve all metadata associated with the file. 1262 * 1263 * @param fields the optional fields to retrieve. 1264 * @return An iterable of metadata instances associated with the file. 1265 */ 1266 public Iterable<Metadata> getAllMetadata(String... fields) { 1267 return Metadata.getAllMetadata(this, fields); 1268 } 1269 1270 /** 1271 * Gets the file properties metadata. 1272 * 1273 * @return the metadata returned from the server. 1274 */ 1275 public Metadata getMetadata() { 1276 return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE); 1277 } 1278 1279 /** 1280 * Gets the file metadata of specified template type. 1281 * 1282 * @param typeName the metadata template type name. 1283 * @return the metadata returned from the server. 1284 */ 1285 public Metadata getMetadata(String typeName) { 1286 String scope = Metadata.scopeBasedOnType(typeName); 1287 return this.getMetadata(typeName, scope); 1288 } 1289 1290 /** 1291 * Gets the file metadata of specified template type. 1292 * 1293 * @param typeName the metadata template type name. 1294 * @param scope the metadata scope (global or enterprise). 1295 * @return the metadata returned from the server. 1296 */ 1297 public Metadata getMetadata(String typeName, String scope) { 1298 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); 1299 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 1300 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1301 return new Metadata(JsonObject.readFrom(response.getJSON())); 1302 } 1303 1304 /** 1305 * Updates the file metadata. 1306 * 1307 * @param metadata the new metadata values. 1308 * @return the metadata returned from the server. 1309 */ 1310 public Metadata updateMetadata(Metadata metadata) { 1311 String scope; 1312 if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) { 1313 scope = Metadata.GLOBAL_METADATA_SCOPE; 1314 } else { 1315 scope = Metadata.ENTERPRISE_METADATA_SCOPE; 1316 } 1317 1318 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), 1319 scope, metadata.getTemplateName()); 1320 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); 1321 request.addHeader("Content-Type", "application/json-patch+json"); 1322 request.setBody(metadata.getPatch()); 1323 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1324 return new Metadata(JsonObject.readFrom(response.getJSON())); 1325 } 1326 1327 /** 1328 * Deletes the file properties metadata. 1329 */ 1330 public void deleteMetadata() { 1331 this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE); 1332 } 1333 1334 /** 1335 * Deletes the file metadata of specified template type. 1336 * 1337 * @param typeName the metadata template type name. 1338 */ 1339 public void deleteMetadata(String typeName) { 1340 String scope = Metadata.scopeBasedOnType(typeName); 1341 this.deleteMetadata(typeName, scope); 1342 } 1343 1344 /** 1345 * Deletes the file metadata of specified template type. 1346 * 1347 * @param typeName the metadata template type name. 1348 * @param scope the metadata scope (global or enterprise). 1349 */ 1350 public void deleteMetadata(String typeName, String scope) { 1351 URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); 1352 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); 1353 request.send(); 1354 } 1355 1356 /** 1357 * Used to retrieve the watermark for the file. 1358 * If the file does not have a watermark applied to it, a 404 Not Found will be returned by API. 1359 * 1360 * @param fields the fields to retrieve. 1361 * @return the watermark associated with the file. 1362 */ 1363 public BoxWatermark getWatermark(String... fields) { 1364 return this.getWatermark(FILE_URL_TEMPLATE, fields); 1365 } 1366 1367 /** 1368 * Used to apply or update the watermark for the file. 1369 * 1370 * @return the watermark associated with the file. 1371 */ 1372 public BoxWatermark applyWatermark() { 1373 return this.applyWatermark(FILE_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT); 1374 } 1375 1376 /** 1377 * Removes a watermark from the file. 1378 * If the file did not have a watermark applied to it, a 404 Not Found will be returned by API. 1379 */ 1380 public void removeWatermark() { 1381 this.removeWatermark(FILE_URL_TEMPLATE); 1382 } 1383 1384 /** 1385 * {@inheritDoc} 1386 */ 1387 @Override 1388 public BoxFile.Info setCollections(BoxCollection... collections) { 1389 JsonArray jsonArray = new JsonArray(); 1390 for (BoxCollection collection : collections) { 1391 JsonObject collectionJSON = new JsonObject(); 1392 collectionJSON.add("id", collection.getID()); 1393 jsonArray.add(collectionJSON); 1394 } 1395 JsonObject infoJSON = new JsonObject(); 1396 infoJSON.add("collections", jsonArray); 1397 1398 String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); 1399 URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); 1400 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); 1401 request.setBody(infoJSON.toString()); 1402 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1403 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 1404 return new Info(jsonObject); 1405 } 1406 1407 /** 1408 * Creates an upload session to create a new version of a file in chunks. 1409 * This will first verify that the version can be created and then open a session for uploading pieces of the file. 1410 * @param fileSize the size of the file that will be uploaded. 1411 * @return the created upload session instance. 1412 */ 1413 public BoxFileUploadSession.Info createUploadSession(long fileSize) { 1414 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1415 1416 BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); 1417 request.addHeader("Content-Type", "application/json"); 1418 1419 JsonObject body = new JsonObject(); 1420 body.add("file_size", fileSize); 1421 request.setBody(body.toString()); 1422 1423 BoxJSONResponse response = (BoxJSONResponse) request.send(); 1424 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 1425 1426 String sessionId = jsonObject.get("id").asString(); 1427 BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId); 1428 return session.new Info(jsonObject); 1429 } 1430 1431 /** 1432 * Creates a new version of a file. 1433 * @param inputStream the stream instance that contains the data. 1434 * @param fileSize the size of the file that will be uploaded. 1435 * @return the created file instance. 1436 * @throws InterruptedException when a thread execution is interrupted. 1437 * @throws IOException when reading a stream throws exception. 1438 */ 1439 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize) 1440 throws InterruptedException, IOException { 1441 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1442 return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize); 1443 } 1444 1445 /** 1446 * Creates a new version of a file. Also sets file attributes. 1447 * @param inputStream the stream instance that contains the data. 1448 * @param fileSize the size of the file that will be uploaded. 1449 * @param fileAttributes file attributes to set 1450 * @return the created file instance. 1451 * @throws InterruptedException when a thread execution is interrupted. 1452 * @throws IOException when reading a stream throws exception. 1453 */ 1454 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, Map<String, String> fileAttributes) 1455 throws InterruptedException, IOException { 1456 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1457 return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); 1458 } 1459 1460 /** 1461 * Creates a new version of a file using specified number of parallel http connections. 1462 * @param inputStream the stream instance that contains the data. 1463 * @param fileSize the size of the file that will be uploaded. 1464 * @param nParallelConnections number of parallel http connections to use 1465 * @param timeOut time to wait before killing the job 1466 * @param unit time unit for the time wait value 1467 * @return the created file instance. 1468 * @throws InterruptedException when a thread execution is interrupted. 1469 * @throws IOException when reading a stream throws exception. 1470 */ 1471 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, 1472 int nParallelConnections, long timeOut, TimeUnit unit) 1473 throws InterruptedException, IOException { 1474 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1475 return new LargeFileUpload(nParallelConnections, timeOut, unit) 1476 .upload(this.getAPI(), inputStream, url, fileSize); 1477 } 1478 1479 /** 1480 * Creates a new version of a file using specified number of parallel http connections. Also sets file attributes. 1481 * @param inputStream the stream instance that contains the data. 1482 * @param fileSize the size of the file that will be uploaded. 1483 * @param nParallelConnections number of parallel http connections to use 1484 * @param timeOut time to wait before killing the job 1485 * @param unit time unit for the time wait value 1486 * @param fileAttributes file attributes to set 1487 * @return the created file instance. 1488 * @throws InterruptedException when a thread execution is interrupted. 1489 * @throws IOException when reading a stream throws exception. 1490 */ 1491 public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, 1492 int nParallelConnections, long timeOut, TimeUnit unit, 1493 Map<String, String> fileAttributes) 1494 throws InterruptedException, IOException { 1495 URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); 1496 return new LargeFileUpload(nParallelConnections, timeOut, unit) 1497 .upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); 1498 } 1499 1500 private BoxCollaboration.Info collaborate(JsonObject accessibleByField, BoxCollaboration.Role role, 1501 Boolean notify, Boolean canViewPath) { 1502 1503 JsonObject itemField = new JsonObject(); 1504 itemField.add("id", this.getID()); 1505 itemField.add("type", "file"); 1506 1507 return BoxCollaboration.create(this.getAPI(), accessibleByField, itemField, role, notify, canViewPath); 1508 } 1509 1510 /** 1511 * Adds a collaborator to this file. 1512 * 1513 * @param collaborator the collaborator to add. 1514 * @param role the role of the collaborator. 1515 * @param notify determines if the user (or all the users in the group) will receive email notifications. 1516 * @param canViewPath whether view path collaboration feature is enabled or not. 1517 * @return info about the new collaboration. 1518 */ 1519 public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role, 1520 Boolean notify, Boolean canViewPath) { 1521 JsonObject accessibleByField = new JsonObject(); 1522 accessibleByField.add("id", collaborator.getID()); 1523 1524 if (collaborator instanceof BoxUser) { 1525 accessibleByField.add("type", "user"); 1526 } else if (collaborator instanceof BoxGroup) { 1527 accessibleByField.add("type", "group"); 1528 } else { 1529 throw new IllegalArgumentException("The given collaborator is of an unknown type."); 1530 } 1531 return this.collaborate(accessibleByField, role, notify, canViewPath); 1532 } 1533 1534 1535 /** 1536 * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box 1537 * account. 1538 * 1539 * @param email the email address of the collaborator to add. 1540 * @param role the role of the collaborator. 1541 * @param notify determines if the user (or all the users in the group) will receive email notifications. 1542 * @param canViewPath whether view path collaboration feature is enabled or not. 1543 * @return info about the new collaboration. 1544 */ 1545 public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role, 1546 Boolean notify, Boolean canViewPath) { 1547 JsonObject accessibleByField = new JsonObject(); 1548 accessibleByField.add("login", email); 1549 accessibleByField.add("type", "user"); 1550 1551 return this.collaborate(accessibleByField, role, notify, canViewPath); 1552 } 1553 1554 /** 1555 * Used to retrieve all collaborations associated with the item. 1556 * 1557 * @param fields the optional fields to retrieve. 1558 * @return An iterable of metadata instances associated with the item. 1559 */ 1560 public BoxResourceIterable<BoxCollaboration.Info> getAllFileCollaborations(String... fields) { 1561 return BoxCollaboration.getAllFileCollaborations(this.getAPI(), this.getID(), 1562 GET_COLLABORATORS_PAGE_SIZE, fields); 1563 1564 } 1565 1566 /** 1567 * Contains information about a BoxFile. 1568 */ 1569 public class Info extends BoxItem.Info { 1570 private String sha1; 1571 private String versionNumber; 1572 private long commentCount; 1573 private EnumSet<Permission> permissions; 1574 private String extension; 1575 private boolean isPackage; 1576 private BoxFileVersion version; 1577 private URL previewLink; 1578 private BoxLock lock; 1579 private boolean isWatermarked; 1580 private Boolean isExternallyOwned; 1581 private JsonObject metadata; 1582 private Map<String, Map<String, Metadata>> metadataMap; 1583 private List<Representation> representations; 1584 private List<String> allowedInviteeRoles; 1585 private Boolean hasCollaborations; 1586 1587 /** 1588 * Constructs an empty Info object. 1589 */ 1590 public Info() { 1591 super(); 1592 } 1593 1594 /** 1595 * Constructs an Info object by parsing information from a JSON string. 1596 * 1597 * @param json the JSON string to parse. 1598 */ 1599 public Info(String json) { 1600 super(json); 1601 } 1602 1603 /** 1604 * Constructs an Info object using an already parsed JSON object. 1605 * 1606 * @param jsonObject the parsed JSON object. 1607 */ 1608 public Info(JsonObject jsonObject) { 1609 super(jsonObject); 1610 } 1611 1612 @Override 1613 public BoxFile getResource() { 1614 return BoxFile.this; 1615 } 1616 1617 /** 1618 * Gets the SHA1 hash of the file. 1619 * 1620 * @return the SHA1 hash of the file. 1621 */ 1622 public String getSha1() { 1623 return this.sha1; 1624 } 1625 1626 /** 1627 * Gets the lock of the file. 1628 * 1629 * @return the lock of the file. 1630 */ 1631 public BoxLock getLock() { 1632 return this.lock; 1633 } 1634 1635 /** 1636 * Gets the current version number of the file. 1637 * 1638 * @return the current version number of the file. 1639 */ 1640 public String getVersionNumber() { 1641 return this.versionNumber; 1642 } 1643 1644 /** 1645 * Gets the number of comments on the file. 1646 * 1647 * @return the number of comments on the file. 1648 */ 1649 public long getCommentCount() { 1650 return this.commentCount; 1651 } 1652 1653 /** 1654 * Gets the permissions that the current user has on the file. 1655 * 1656 * @return the permissions that the current user has on the file. 1657 */ 1658 public EnumSet<Permission> getPermissions() { 1659 return this.permissions; 1660 } 1661 1662 /** 1663 * Gets the extension suffix of the file, excluding the dot. 1664 * 1665 * @return the extension of the file. 1666 */ 1667 public String getExtension() { 1668 return this.extension; 1669 } 1670 1671 /** 1672 * Gets whether or not the file is an OSX package. 1673 * 1674 * @return true if the file is an OSX package; otherwise false. 1675 */ 1676 public boolean getIsPackage() { 1677 return this.isPackage; 1678 } 1679 1680 /** 1681 * Gets the current version details of the file. 1682 * 1683 * @return the current version details of the file. 1684 */ 1685 public BoxFileVersion getVersion() { 1686 return this.version; 1687 } 1688 1689 /** 1690 * Gets the current expiring preview link. 1691 * 1692 * @return the expiring preview link 1693 */ 1694 public URL getPreviewLink() { 1695 return this.previewLink; 1696 } 1697 1698 /** 1699 * Gets flag indicating whether this file is Watermarked. 1700 * 1701 * @return whether the file is watermarked or not 1702 */ 1703 public boolean getIsWatermarked() { 1704 return this.isWatermarked; 1705 } 1706 1707 /** 1708 * Returns the allowed invitee roles for this file item. 1709 * 1710 * @return the list of roles allowed for invited collaborators. 1711 */ 1712 public List<String> getAllowedInviteeRoles() { 1713 return this.allowedInviteeRoles; 1714 } 1715 1716 /** 1717 * Returns the indicator for whether this file item has collaborations. 1718 * 1719 * @return indicator for whether this file item has collaborations. 1720 */ 1721 public Boolean getHasCollaborations() { 1722 return this.hasCollaborations; 1723 } 1724 1725 /** 1726 * Gets the metadata on this file associated with a specified scope and template. 1727 * Makes an attempt to get metadata that was retrieved using getInfo(String ...) method. If no result is found 1728 * then makes an API call to get metadata 1729 * @param templateName the metadata template type name. 1730 * @param scope the scope of the template (usually "global" or "enterprise"). 1731 * @return the metadata returned from the server. 1732 */ 1733 public Metadata getMetadata(String templateName, String scope) { 1734 try { 1735 return this.metadataMap.get(scope).get(templateName); 1736 } catch (NullPointerException e) { 1737 return null; 1738 } 1739 } 1740 1741 /** 1742 * Returns the field for indicating whether a file is owned by a user outside the enterprise. 1743 * @return indicator for whether or not the file is owned by a user outside the enterprise. 1744 */ 1745 public boolean getIsExternallyOwned() { 1746 return this.isExternallyOwned; 1747 } 1748 1749 /** 1750 * Get file's representations. 1751 * @return list of representations 1752 */ 1753 public List<Representation> getRepresentations() { 1754 return this.representations; 1755 } 1756 1757 @Override 1758 protected void parseJSONMember(JsonObject.Member member) { 1759 super.parseJSONMember(member); 1760 1761 String memberName = member.getName(); 1762 JsonValue value = member.getValue(); 1763 try { 1764 if (memberName.equals("sha1")) { 1765 this.sha1 = value.asString(); 1766 } else if (memberName.equals("version_number")) { 1767 this.versionNumber = value.asString(); 1768 } else if (memberName.equals("comment_count")) { 1769 this.commentCount = value.asLong(); 1770 } else if (memberName.equals("permissions")) { 1771 this.permissions = this.parsePermissions(value.asObject()); 1772 } else if (memberName.equals("extension")) { 1773 this.extension = value.asString(); 1774 } else if (memberName.equals("is_package")) { 1775 this.isPackage = value.asBoolean(); 1776 } else if (memberName.equals("has_collaborations")) { 1777 this.hasCollaborations = value.asBoolean(); 1778 } else if (memberName.equals("is_externally_owned")) { 1779 this.isExternallyOwned = value.asBoolean(); 1780 } else if (memberName.equals("file_version")) { 1781 this.version = this.parseFileVersion(value.asObject()); 1782 } else if (memberName.equals("allowed_invitee_roles")) { 1783 this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray()); 1784 } else if (memberName.equals("expiring_embed_link")) { 1785 try { 1786 String urlString = member.getValue().asObject().get("url").asString(); 1787 this.previewLink = new URL(urlString); 1788 } catch (MalformedURLException e) { 1789 throw new BoxAPIException("Couldn't parse expiring_embed_link/url for file", e); 1790 } 1791 } else if (memberName.equals("lock")) { 1792 if (value.isNull()) { 1793 this.lock = null; 1794 } else { 1795 this.lock = new BoxLock(value.asObject(), BoxFile.this.getAPI()); 1796 } 1797 } else if (memberName.equals("watermark_info")) { 1798 JsonObject jsonObject = value.asObject(); 1799 this.isWatermarked = jsonObject.get("is_watermarked").asBoolean(); 1800 } else if (memberName.equals("metadata")) { 1801 JsonObject jsonObject = value.asObject(); 1802 this.metadataMap = Parsers.parseAndPopulateMetadataMap(jsonObject); 1803 } else if (memberName.equals("representations")) { 1804 JsonObject jsonObject = value.asObject(); 1805 this.representations = Parsers.parseRepresentations(jsonObject); 1806 } 1807 } catch (Exception e) { 1808 throw new BoxDeserializationException(memberName, value.toString(), e); 1809 } 1810 } 1811 1812 private EnumSet<Permission> parsePermissions(JsonObject jsonObject) { 1813 EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class); 1814 for (JsonObject.Member member : jsonObject) { 1815 JsonValue value = member.getValue(); 1816 if (value.isNull() || !value.asBoolean()) { 1817 continue; 1818 } 1819 1820 String memberName = member.getName(); 1821 if (memberName.equals("can_download")) { 1822 permissions.add(Permission.CAN_DOWNLOAD); 1823 } else if (memberName.equals("can_upload")) { 1824 permissions.add(Permission.CAN_UPLOAD); 1825 } else if (memberName.equals("can_rename")) { 1826 permissions.add(Permission.CAN_RENAME); 1827 } else if (memberName.equals("can_delete")) { 1828 permissions.add(Permission.CAN_DELETE); 1829 } else if (memberName.equals("can_share")) { 1830 permissions.add(Permission.CAN_SHARE); 1831 } else if (memberName.equals("can_set_share_access")) { 1832 permissions.add(Permission.CAN_SET_SHARE_ACCESS); 1833 } else if (memberName.equals("can_preview")) { 1834 permissions.add(Permission.CAN_PREVIEW); 1835 } else if (memberName.equals("can_comment")) { 1836 permissions.add(Permission.CAN_COMMENT); 1837 } 1838 } 1839 1840 return permissions; 1841 } 1842 1843 private BoxFileVersion parseFileVersion(JsonObject jsonObject) { 1844 return new BoxFileVersion(BoxFile.this.getAPI(), jsonObject, BoxFile.this.getID()); 1845 } 1846 1847 private List<String> parseAllowedInviteeRoles(JsonArray jsonArray) { 1848 List<String> roles = new ArrayList<String>(jsonArray.size()); 1849 for (JsonValue value : jsonArray) { 1850 roles.add(value.asString()); 1851 } 1852 1853 return roles; 1854 } 1855 } 1856 1857 /** 1858 * Enumerates the possible permissions that a user can have on a file. 1859 */ 1860 public enum Permission { 1861 /** 1862 * The user can download the file. 1863 */ 1864 CAN_DOWNLOAD("can_download"), 1865 1866 /** 1867 * The user can upload new versions of the file. 1868 */ 1869 CAN_UPLOAD("can_upload"), 1870 1871 /** 1872 * The user can rename the file. 1873 */ 1874 CAN_RENAME("can_rename"), 1875 1876 /** 1877 * The user can delete the file. 1878 */ 1879 CAN_DELETE("can_delete"), 1880 1881 /** 1882 * The user can share the file. 1883 */ 1884 CAN_SHARE("can_share"), 1885 1886 /** 1887 * The user can set the access level for shared links to the file. 1888 */ 1889 CAN_SET_SHARE_ACCESS("can_set_share_access"), 1890 1891 /** 1892 * The user can preview the file. 1893 */ 1894 CAN_PREVIEW("can_preview"), 1895 1896 /** 1897 * The user can comment on the file. 1898 */ 1899 CAN_COMMENT("can_comment"); 1900 1901 private final String jsonValue; 1902 1903 private Permission(String jsonValue) { 1904 this.jsonValue = jsonValue; 1905 } 1906 1907 static Permission fromJSONValue(String jsonValue) { 1908 return Permission.valueOf(jsonValue.toUpperCase()); 1909 } 1910 1911 String toJSONValue() { 1912 return this.jsonValue; 1913 } 1914 } 1915 1916}