|
| 1 | +/* |
| 2 | + * Copyright (c) 2012 Google Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | + * in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | + * or implied. See the License for the specific language governing permissions and limitations under |
| 12 | + * the License. |
| 13 | + */ |
| 14 | + |
| 15 | +package com.google.api.services.samples.youtube.cmdline.data; |
| 16 | + |
| 17 | +import com.google.api.client.googleapis.json.GoogleJsonResponseException; |
| 18 | +import com.google.api.client.http.HttpRequest; |
| 19 | +import com.google.api.client.http.HttpRequestInitializer; |
| 20 | +import com.google.api.client.http.HttpTransport; |
| 21 | +import com.google.api.client.http.javanet.NetHttpTransport; |
| 22 | +import com.google.api.client.json.JsonFactory; |
| 23 | +import com.google.api.client.json.jackson2.JacksonFactory; |
| 24 | +import com.google.api.services.samples.youtube.cmdline.Auth; |
| 25 | +import com.google.api.services.youtube.YouTube; |
| 26 | +import com.google.api.services.youtube.model.ResourceId; |
| 27 | +import com.google.api.services.youtube.model.SearchListResponse; |
| 28 | +import com.google.api.services.youtube.model.SearchResult; |
| 29 | +import com.google.api.services.youtube.model.Thumbnail; |
| 30 | + |
| 31 | +import java.io.BufferedReader; |
| 32 | +import java.io.IOException; |
| 33 | +import java.io.InputStream; |
| 34 | +import java.io.InputStreamReader; |
| 35 | +import java.util.Iterator; |
| 36 | +import java.util.List; |
| 37 | +import java.util.Properties; |
| 38 | + |
| 39 | +/** |
| 40 | + * Print a list of videos matching a search term. |
| 41 | + * |
| 42 | + * @author Jeremy Walker |
| 43 | + */ |
| 44 | +public class Search { |
| 45 | + |
| 46 | + /** |
| 47 | + * Define a global variable that identifies the name of a file that |
| 48 | + * contains the developer's API key. |
| 49 | + */ |
| 50 | + private static final String PROPERTIES_FILENAME = "youtube.properties"; |
| 51 | + |
| 52 | + private static final long NUMBER_OF_VIDEOS_RETURNED = 25; |
| 53 | + |
| 54 | + /** |
| 55 | + * Define a global instance of a Youtube object, which will be used |
| 56 | + * to make YouTube Data API requests. |
| 57 | + */ |
| 58 | + private static YouTube youtube; |
| 59 | + |
| 60 | + /** |
| 61 | + * Initialize a YouTube object to search for videos on YouTube. Then |
| 62 | + * display the name and thumbnail image of each video in the result set. |
| 63 | + * |
| 64 | + * @param args command line args. |
| 65 | + */ |
| 66 | + public static void main(String[] args) { |
| 67 | + // Read the developer key from the properties file. |
| 68 | + Properties properties = new Properties(); |
| 69 | + try { |
| 70 | + InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME); |
| 71 | + properties.load(in); |
| 72 | + |
| 73 | + } catch (IOException e) { |
| 74 | + System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() |
| 75 | + + " : " + e.getMessage()); |
| 76 | + System.exit(1); |
| 77 | + } |
| 78 | + |
| 79 | + try { |
| 80 | + // This object is used to make YouTube Data API requests. The last |
| 81 | + // argument is required, but since we don't need anything |
| 82 | + // initialized when the HttpRequest is initialized, we override |
| 83 | + // the interface and provide a no-op function. |
| 84 | + youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() { |
| 85 | + public void initialize(HttpRequest request) throws IOException { |
| 86 | + } |
| 87 | + }).setApplicationName("youtube-cmdline-search-sample").build(); |
| 88 | + |
| 89 | + // Prompt the user to enter a query term. |
| 90 | + String queryTerm = getInputQuery(); |
| 91 | + |
| 92 | + // Define the API request for retrieving search results. |
| 93 | + YouTube.Search.List search = youtube.search().list("id,snippet"); |
| 94 | + |
| 95 | + // Set your developer key from the {{ Google Cloud Console }} for |
| 96 | + // non-authenticated requests. See: |
| 97 | + // {{ https://cloud.google.com/console }} |
| 98 | + String apiKey = properties.getProperty("youtube.apikey"); |
| 99 | + search.setKey(apiKey); |
| 100 | + search.setQ(queryTerm); |
| 101 | + |
| 102 | + // Restrict the search results to only include videos. See: |
| 103 | + // https://developers.google.com/youtube/v3/docs/search/list#type |
| 104 | + search.setType("video"); |
| 105 | + |
| 106 | + // To increase efficiency, only retrieve the fields that the |
| 107 | + // application uses. |
| 108 | + search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); |
| 109 | + search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); |
| 110 | + |
| 111 | + // Call the API and print results. |
| 112 | + SearchListResponse searchResponse = search.execute(); |
| 113 | + List<SearchResult> searchResultList = searchResponse.getItems(); |
| 114 | + if (searchResultList != null) { |
| 115 | + prettyPrint(searchResultList.iterator(), queryTerm); |
| 116 | + } |
| 117 | + } catch (GoogleJsonResponseException e) { |
| 118 | + System.err.println("There was a service error: " + e.getDetails().getCode() + " : " |
| 119 | + + e.getDetails().getMessage()); |
| 120 | + } catch (IOException e) { |
| 121 | + System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); |
| 122 | + } catch (Throwable t) { |
| 123 | + t.printStackTrace(); |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + /* |
| 128 | + * Prompt the user to enter a query term and return the user-specified term. |
| 129 | + */ |
| 130 | + private static String getInputQuery() throws IOException { |
| 131 | + |
| 132 | + String inputQuery = ""; |
| 133 | + |
| 134 | + System.out.print("Please enter a search term: "); |
| 135 | + BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); |
| 136 | + inputQuery = bReader.readLine(); |
| 137 | + |
| 138 | + if (inputQuery.length() < 1) { |
| 139 | + // Use the string "YouTube Developers Live" as a default. |
| 140 | + inputQuery = "YouTube Developers Live"; |
| 141 | + } |
| 142 | + return inputQuery; |
| 143 | + } |
| 144 | + |
| 145 | + /* |
| 146 | + * Prints out all results in the Iterator. For each result, print the |
| 147 | + * title, video ID, and thumbnail. |
| 148 | + * |
| 149 | + * @param iteratorSearchResults Iterator of SearchResults to print |
| 150 | + * |
| 151 | + * @param query Search query (String) |
| 152 | + */ |
| 153 | + private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) { |
| 154 | + |
| 155 | + System.out.println("\n============================================================="); |
| 156 | + System.out.println( |
| 157 | + " First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\"."); |
| 158 | + System.out.println("=============================================================\n"); |
| 159 | + |
| 160 | + if (!iteratorSearchResults.hasNext()) { |
| 161 | + System.out.println(" There aren't any results for your query."); |
| 162 | + } |
| 163 | + |
| 164 | + while (iteratorSearchResults.hasNext()) { |
| 165 | + |
| 166 | + SearchResult singleVideo = iteratorSearchResults.next(); |
| 167 | + ResourceId rId = singleVideo.getId(); |
| 168 | + |
| 169 | + // Confirm that the result represents a video. Otherwise, the |
| 170 | + // item will not contain a video ID. |
| 171 | + if (rId.getKind().equals("youtube#video")) { |
| 172 | + Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault(); |
| 173 | + |
| 174 | + System.out.println(" Video Id" + rId.getVideoId()); |
| 175 | + System.out.println(" Title: " + singleVideo.getSnippet().getTitle()); |
| 176 | + System.out.println(" Thumbnail: " + thumbnail.getUrl()); |
| 177 | + System.out.println("\n-------------------------------------------------------------\n"); |
| 178 | + } |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments