Skip to content

Commit 452ada3

Browse files
committed
"Added sample: java/src/main/java/com/google/api/services/samples/youtube/cmdline/data/GeolocationSearch.java"
1 parent 3d4bbb5 commit 452ada3

1 file changed

Lines changed: 248 additions & 0 deletions

File tree

Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
/*
2+
* Copyright (c) 2014 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.util.Joiner;
21+
import com.google.api.services.samples.youtube.cmdline.Auth;
22+
import com.google.api.services.youtube.YouTube;
23+
import com.google.api.services.youtube.model.GeoPoint;
24+
import com.google.api.services.youtube.model.SearchListResponse;
25+
import com.google.api.services.youtube.model.SearchResult;
26+
import com.google.api.services.youtube.model.Thumbnail;
27+
import com.google.api.services.youtube.model.Video;
28+
import com.google.api.services.youtube.model.VideoListResponse;
29+
30+
import java.io.BufferedReader;
31+
import java.io.IOException;
32+
import java.io.InputStream;
33+
import java.io.InputStreamReader;
34+
import java.util.ArrayList;
35+
import java.util.Iterator;
36+
import java.util.List;
37+
import java.util.Properties;
38+
39+
/**
40+
* This sample lists videos that are associated with a particular keyword and are in the radius of
41+
* particular geographic coordinates by:
42+
*
43+
* 1. Searching videos with "youtube.search.list" method and setting "type", "q", "location" and
44+
* "locationRadius" parameters.
45+
* 2. Retrieving location details for each video with "youtube.videos.list" method and setting
46+
* "id" parameter to comma separated list of video IDs in search result.
47+
*
48+
* @author Ibrahim Ulukaya
49+
*/
50+
public class GeolocationSearch {
51+
52+
/**
53+
* Define a global variable that identifies the name of a file that
54+
* contains the developer's API key.
55+
*/
56+
private static final String PROPERTIES_FILENAME = "youtube.properties";
57+
58+
private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
59+
60+
/**
61+
* Define a global instance of a Youtube object, which will be used
62+
* to make YouTube Data API requests.
63+
*/
64+
private static YouTube youtube;
65+
66+
/**
67+
* Initialize a YouTube object to search for videos on YouTube. Then
68+
* display the name and thumbnail image of each video in the result set.
69+
*
70+
* @param args command line args.
71+
*/
72+
public static void main(String[] args) {
73+
// Read the developer key from the properties file.
74+
Properties properties = new Properties();
75+
try {
76+
InputStream in = GeolocationSearch.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
77+
properties.load(in);
78+
79+
} catch (IOException e) {
80+
System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
81+
+ " : " + e.getMessage());
82+
System.exit(1);
83+
}
84+
85+
try {
86+
// This object is used to make YouTube Data API requests. The last
87+
// argument is required, but since we don't need anything
88+
// initialized when the HttpRequest is initialized, we override
89+
// the interface and provide a no-op function.
90+
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
91+
@Override
92+
public void initialize(HttpRequest request) throws IOException {
93+
}
94+
}).setApplicationName("youtube-cmdline-geolocationsearch-sample").build();
95+
96+
// Prompt the user to enter a query term.
97+
String queryTerm = getInputQuery();
98+
99+
// Prompt the user to enter location coordinates.
100+
String location = getInputLocation();
101+
102+
// Prompt the user to enter a location radius.
103+
String locationRadius = getInputLocationRadius();
104+
105+
// Define the API request for retrieving search results.
106+
YouTube.Search.List search = youtube.search().list("id,snippet");
107+
108+
// Set your developer key from the {{ Google Cloud Console }} for
109+
// non-authenticated requests. See:
110+
// {{ https://cloud.google.com/console }}
111+
String apiKey = properties.getProperty("youtube.apikey");
112+
search.setKey(apiKey);
113+
search.setQ(queryTerm);
114+
search.setLocation(location);
115+
search.setLocationRadius(locationRadius);
116+
117+
// Restrict the search results to only include videos. See:
118+
// https://developers.google.com/youtube/v3/docs/search/list#type
119+
search.setType("video");
120+
121+
// As a best practice, only retrieve the fields that the
122+
// application uses.
123+
search.setFields("items(id/videoId)");
124+
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
125+
126+
// Call the API and print results.
127+
SearchListResponse searchResponse = search.execute();
128+
List<SearchResult> searchResultList = searchResponse.getItems();
129+
List<String> videoIds = new ArrayList<String>();
130+
131+
if (searchResultList != null) {
132+
133+
// Merge video IDs
134+
for (SearchResult searchResult : searchResultList) {
135+
videoIds.add(searchResult.getId().getVideoId());
136+
}
137+
Joiner stringJoiner = Joiner.on(',');
138+
String videoId = stringJoiner.join(videoIds);
139+
140+
// Call the YouTube Data API's youtube.videos.list method to
141+
// retrieve the resources that represent the specified videos.
142+
YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet, recordingDetails").setId(videoId);
143+
VideoListResponse listResponse = listVideosRequest.execute();
144+
145+
List<Video> videoList = listResponse.getItems();
146+
147+
if (videoList != null) {
148+
prettyPrint(videoList.iterator(), queryTerm);
149+
}
150+
}
151+
} catch (GoogleJsonResponseException e) {
152+
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
153+
+ e.getDetails().getMessage());
154+
} catch (IOException e) {
155+
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
156+
} catch (Throwable t) {
157+
t.printStackTrace();
158+
}
159+
}
160+
161+
/*
162+
* Prompt the user to enter a query term and return the user-specified term.
163+
*/
164+
private static String getInputQuery() throws IOException {
165+
166+
String inputQuery = "";
167+
168+
System.out.print("Please enter a search term: ");
169+
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
170+
inputQuery = bReader.readLine();
171+
172+
if (inputQuery.length() < 1) {
173+
// Use the string "YouTube Developers Live" as a default.
174+
inputQuery = "YouTube Developers Live";
175+
}
176+
return inputQuery;
177+
}
178+
179+
/*
180+
* Prompt the user to enter location coordinates and return the user-specified coordinates.
181+
*/
182+
private static String getInputLocation() throws IOException {
183+
184+
String inputQuery = "";
185+
186+
System.out.print("Please enter location coordinates (example: 37.42307,-122.08427): ");
187+
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
188+
inputQuery = bReader.readLine();
189+
190+
if (inputQuery.length() < 1) {
191+
// Use the string "37.42307,-122.08427" as a default.
192+
inputQuery = "37.42307,-122.08427";
193+
}
194+
return inputQuery;
195+
}
196+
197+
/*
198+
* Prompt the user to enter a location radius and return the user-specified radius.
199+
*/
200+
private static String getInputLocationRadius() throws IOException {
201+
202+
String inputQuery = "";
203+
204+
System.out.print("Please enter a location radius (examples: 5km, 8mi):");
205+
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
206+
inputQuery = bReader.readLine();
207+
208+
if (inputQuery.length() < 1) {
209+
// Use the string "5km" as a default.
210+
inputQuery = "5km";
211+
}
212+
return inputQuery;
213+
}
214+
215+
/*
216+
* Prints out all results in the Iterator. For each result, print the
217+
* title, video ID, location, and thumbnail.
218+
*
219+
* @param iteratorVideoResults Iterator of Videos to print
220+
*
221+
* @param query Search query (String)
222+
*/
223+
private static void prettyPrint(Iterator<Video> iteratorVideoResults, String query) {
224+
225+
System.out.println("\n=============================================================");
226+
System.out.println(
227+
" First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
228+
System.out.println("=============================================================\n");
229+
230+
if (!iteratorVideoResults.hasNext()) {
231+
System.out.println(" There aren't any results for your query.");
232+
}
233+
234+
while (iteratorVideoResults.hasNext()) {
235+
236+
Video singleVideo = iteratorVideoResults.next();
237+
238+
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
239+
GeoPoint location = singleVideo.getRecordingDetails().getLocation();
240+
241+
System.out.println(" Video Id" + singleVideo.getId());
242+
System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
243+
System.out.println(" Location: " + location.getLatitude() + ", " + location.getLongitude());
244+
System.out.println(" Thumbnail: " + thumbnail.getUrl());
245+
System.out.println("\n-------------------------------------------------------------\n");
246+
}
247+
}
248+
}

0 commit comments

Comments
 (0)