001package com.box.sdk; 002import java.net.URL; 003 004import com.eclipsesource.json.JsonArray; 005import com.eclipsesource.json.JsonObject; 006import com.eclipsesource.json.JsonValue; 007/** 008 * Represents search on Box. This class can be used to search through your box instance. 009 * In addition this lets you take advantage of all the advanced search features. 010 * 011 * <p>Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked 012 * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error 013 * handling for errors related to the Box REST API, you should capture this exception explicitly.</p> 014 */ 015public class BoxSearch { 016 017 /** 018 * Search URL Template. 019 */ 020 public static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search"); 021 private final BoxAPIConnection api; 022 023 /** 024 * Constructs a Search to be used by everything. 025 * @param api the API connection to be used by the search. 026 */ 027 public BoxSearch(BoxAPIConnection api) { 028 this.api = api; 029 } 030 031 /** 032 * Searches all descendant folders using a given query and query parameters. 033 * @param offset is the starting position. 034 * @param limit the maximum number of items to return. The default is 30 and the maximum is 200. 035 * @param bsp containing query and advanced search capabilities. 036 * @return a PartialCollection containing the search results. 037 */ 038 public PartialCollection<BoxItem.Info> searchRange(long offset, long limit, final BoxSearchParameters bsp) { 039 QueryStringBuilder builder = bsp.getQueryParameters() 040 .appendParam("limit", limit) 041 .appendParam("offset", offset); 042 URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString()); 043 BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); 044 BoxJSONResponse response = (BoxJSONResponse) request.send(); 045 JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); 046 String totalCountString = responseJSON.get("total_count").toString(); 047 long fullSize = Double.valueOf(totalCountString).longValue(); 048 PartialCollection<BoxItem.Info> results = new PartialCollection<BoxItem.Info>(offset, limit, fullSize); 049 JsonArray jsonArray = responseJSON.get("entries").asArray(); 050 for (JsonValue value : jsonArray) { 051 JsonObject jsonObject = value.asObject(); 052 BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject); 053 if (parsedItemInfo != null) { 054 results.add(parsedItemInfo); 055 } 056 } 057 return results; 058 } 059 /** 060 * Gets the API connection used by this resource. 061 * @return the API connection used by this resource. 062 */ 063 public BoxAPIConnection getAPI() { 064 return this.api; 065 } 066}