List of usage examples for com.google.api.client.googleapis.json GoogleJsonResponseException getDetails
public final GoogleJsonError getDetails()
From source file:MyUploads.java
License:Apache License
/** * Authorize the user, call the youtube.channels.list method to retrieve * the playlist ID for the list of videos uploaded to the user's channel, * and then call the youtube.playlistItems.list method to retrieve the * list of videos in that playlist./* w w w .j a v a 2 s . c o m*/ */ public static List<Video> run() { try { // Call the API's channels.list method to retrieve the // resource that represents the authenticated user's channel. // In the API response, only include channel information needed for // this use case. The channel's contentDetails part contains // playlist IDs relevant to the channel, including the ID for the // list that contains videos uploaded to the channel. YouTube.Channels.List channelRequest = Main.youtube.channels().list("contentDetails"); channelRequest.setMine(true); channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo"); ChannelListResponse channelResult = channelRequest.execute(); List<Channel> channelsList = channelResult.getItems(); if (channelsList != null) { // The user's default channel is the first item in the list. // Extract the playlist ID for the channel's videos from the // API response. String uploadPlaylistId = channelsList.get(0).getContentDetails().getRelatedPlaylists() .getUploads(); // Define a list to store items in the list of uploaded videos. List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>(); // Retrieve the playlist of the channel's uploaded videos. YouTube.PlaylistItems.List playlistItemRequest = Main.youtube.playlistItems() .list("id,contentDetails,snippet"); playlistItemRequest.setPlaylistId(uploadPlaylistId); // Only retrieve data used in this application, thereby making // the application more efficient. See: // https://developers.google.com/youtube/v3/getting-started#partial playlistItemRequest.setFields( "items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo"); String nextToken = ""; // Call the API one or more times to retrieve all items in the // list. As long as the API response returns a nextPageToken, // there are still more items to retrieve. do { playlistItemRequest.setPageToken(nextToken); PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute(); playlistItemList.addAll(playlistItemResult.getItems()); nextToken = playlistItemResult.getNextPageToken(); } while (nextToken != null); // Prints information about the results. return prettyPrint(playlistItemList.size(), playlistItemList.iterator()); } } catch (GoogleJsonResponseException e) { e.printStackTrace(); System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (Throwable t) { t.printStackTrace(); } return null; }
From source file:business.YoutubeService.java
License:Apache License
public static List<ItemView> searchVideos(String queryTerm) { try {//w w w . j a v a2s.c om // Define the API request for retrieving search results. YouTube.Search.List search = youtube.search().list("id,snippet"); // Set your developer key from the {{ Google Cloud Console }} for // non-authenticated requests. See: // {{ https://cloud.google.com/console }} //String apiKey = properties.getProperty("youtube.apikey"); //search.setKey(apiKey); search.setQ(queryTerm); // Restrict the search results to only include videos. See: // https://developers.google.com/youtube/v3/docs/search/list#type search.setType("video"); // To increase efficiency, only retrieve the fields that the // application uses. search.setFields("items(id/videoId)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); // Call the API with Ids return findVideosById(search.execute()); } catch (GoogleJsonResponseException e) { System.err.println("There was a service error: 12" + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (IOException e) { System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); } catch (Throwable t) { t.printStackTrace(); } return null; }
From source file:ch.cyberduck.core.googledrive.DriveExceptionMappingService.java
License:Open Source License
@Override public BackgroundException map(final IOException failure) { final StringBuilder buffer = new StringBuilder(); if (failure instanceof GoogleJsonResponseException) { final GoogleJsonResponseException error = (GoogleJsonResponseException) failure; this.append(buffer, error.getDetails().getMessage()); }/*www . j a v a 2s . c o m*/ if (failure instanceof HttpResponseException) { final HttpResponseException response = (HttpResponseException) failure; this.append(buffer, response.getStatusMessage()); switch (response.getStatusCode()) { case HttpStatus.SC_UNAUTHORIZED: // Invalid Credentials. Refresh the access token using the long-lived refresh token return new LoginFailureException(buffer.toString(), failure); case HttpStatus.SC_FORBIDDEN: return new AccessDeniedException(buffer.toString(), failure); case HttpStatus.SC_NOT_FOUND: return new NotfoundException(buffer.toString(), failure); case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE: return new QuotaException(buffer.toString(), failure); case HttpStatus.SC_INSUFFICIENT_STORAGE: return new QuotaException(buffer.toString(), failure); case HttpStatus.SC_PAYMENT_REQUIRED: return new QuotaException(buffer.toString(), failure); case HttpStatus.SC_BAD_REQUEST: return new InteroperabilityException(buffer.toString(), failure); case HttpStatus.SC_METHOD_NOT_ALLOWED: return new InteroperabilityException(buffer.toString(), failure); case HttpStatus.SC_NOT_IMPLEMENTED: return new InteroperabilityException(buffer.toString(), failure); case HttpStatus.SC_INTERNAL_SERVER_ERROR: return new InteroperabilityException(buffer.toString(), failure); case HttpStatus.SC_SERVICE_UNAVAILABLE: return new ConnectionRefusedException(buffer.toString(), failure); } } return super.map(failure); }
From source file:com.acceleratedio.pac_n_zoom.UploadVideo.java
License:Apache License
/** * Upload the user-selected video to the user's YouTube channel. The code * looks for the video in the application's project folder and uses OAuth * 2.0 to authorize the API request.//from w w w. jav a 2 s .c o m * * @param args command line args (not used). */ public static void main(String[] args) { MakePostRequest get_video = new MakePostRequest(); get_video.execute(); // This OAuth 2.0 access scope allows an application to upload files // to the authenticated user's YouTube channel, but doesn't allow // other types of access. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload"); String vidFileName = PickAnmActivity.fil_nams[position].replace('/', '?') + ".mp4"; String httpAddrs = "http://www.pnzanimate.me/Droid/db_rd.php?"; httpAddrs += vidFileName; try { // Authorize the request. Credential credential = Auth.authorize(scopes, "uploadvideo"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-uploadvideo-sample").build(); System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME); // Add extra information to the video before uploading. Video videoObjectDefiningMetadata = new Video(); // Set the video to be publicly visible. This is the default // setting. Other supporting settings are "unlisted" and "private." VideoStatus status = new VideoStatus(); status.setPrivacyStatus("public"); videoObjectDefiningMetadata.setStatus(status); // Most of the video's metadata is set on the VideoSnippet object. VideoSnippet snippet = new VideoSnippet(); // This code uses a Calendar instance to create a unique name and // description for test purposes so that you can easily upload // multiple files. You should remove this code from your project // and use your own standard names instead. Calendar cal = Calendar.getInstance(); snippet.setTitle("Test Upload via Java on " + cal.getTime()); snippet.setDescription( "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime()); // Set the keyword tags that you want to associate with the video. List<String> tags = new ArrayList<String>(); tags.add("test"); tags.add("example"); tags.add("java"); tags.add("YouTube Data API V3"); tags.add("erase me"); snippet.setTags(tags); // Add the completed snippet object to the video resource. videoObjectDefiningMetadata.setSnippet(snippet); InputStreamContent mediaContent = new InputStreamContent("mp4", UploadVideo.class.getResourceAsStream("/sample-video.mp4")); // Insert the video. The command sends three arguments. The first // specifies which information the API request is setting and which // information the API response should return. The second argument // is the video resource that contains metadata about the new video. // The third argument is the actual video content. YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent); // Set the upload type and add an event listener. MediaHttpUploader uploader = videoInsert.getMediaHttpUploader(); // Indicate whether direct media upload is enabled. A value of // "True" indicates that direct media upload is enabled and that // the entire media content will be uploaded in a single request. // A value of "False," which is the default, indicates that the // request will use the resumable media upload protocol, which // supports the ability to resume an upload operation after a // network interruption or other transmission failure, saving // time and bandwidth in the event of network failures. uploader.setDirectUploadEnabled(false); MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() { public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { case INITIATION_STARTED: System.out.println("Initiation Started"); break; case INITIATION_COMPLETE: System.out.println("Initiation Completed"); break; case MEDIA_IN_PROGRESS: System.out.println("Upload in progress"); System.out.println("Upload percentage: " + uploader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Upload Completed!"); break; case NOT_STARTED: System.out.println("Upload Not Started!"); break; } } }; uploader.setProgressListener(progressListener); // Call the API and upload the video. Video returnedVideo = videoInsert.execute(); // Print data about the newly inserted video from the API response. System.out.println("\n================== Returned Video ==================\n"); System.out.println(" - Id: " + returnedVideo.getId()); System.out.println(" - Title: " + returnedVideo.getSnippet().getTitle()); System.out.println(" - Tags: " + returnedVideo.getSnippet().getTags()); System.out.println(" - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus()); System.out.println(" - Video Count: " + returnedVideo.getStatistics().getViewCount()); } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }
From source file:com.agroknow.cimmyt.utils.UploadVideo.java
License:Apache License
/** * Upload the user-selected video to the user's YouTube channel. The code * looks for the video in the application's project folder and uses OAuth * 2.0 to authorize the API request./*from ww w . java2s . c o m*/ * * @param args command line args (not used). */ public static void main(String[] args) { // This OAuth 2.0 access scope allows an application to upload files // to the authenticated user's YouTube channel, but doesn't allow // other types of access. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "uploadvideo"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-uploadvideo-sample").build(); System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME); // Add extra information to the video before uploading. Video videoObjectDefiningMetadata = new Video(); // Set the video to be publicly visible. This is the default // setting. Other supporting settings are "unlisted" and "private." VideoStatus status = new VideoStatus(); status.setPrivacyStatus("public"); videoObjectDefiningMetadata.setStatus(status); // Most of the video's metadata is set on the VideoSnippet object. VideoSnippet snippet = new VideoSnippet(); // This code uses a Calendar instance to create a unique name and // description for test purposes so that you can easily upload // multiple files. You should remove this code from your project // and use your own standard names instead. Calendar cal = Calendar.getInstance(); snippet.setTitle("Test Upload via Java on " + cal.getTime()); snippet.setDescription( "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime()); // Set the keyword tags that you want to associate with the video. List<String> tags = new ArrayList<String>(); tags.add("test"); tags.add("example"); tags.add("java"); tags.add("YouTube Data API V3"); tags.add("erase me"); snippet.setTags(tags); // Add the completed snippet object to the video resource. videoObjectDefiningMetadata.setSnippet(snippet); InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4")); // Insert the video. The command sends three arguments. The first // specifies which information the API request is setting and which // information the API response should return. The second argument // is the video resource that contains metadata about the new video. // The third argument is the actual video content. YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent); // Set the upload type and add an event listener. MediaHttpUploader uploader = videoInsert.getMediaHttpUploader(); // Indicate whether direct media upload is enabled. A value of // "True" indicates that direct media upload is enabled and that // the entire media content will be uploaded in a single request. // A value of "False," which is the default, indicates that the // request will use the resumable media upload protocol, which // supports the ability to resume an upload operation after a // network interruption or other transmission failure, saving // time and bandwidth in the event of network failures. uploader.setDirectUploadEnabled(false); MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() { public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { case INITIATION_STARTED: System.out.println("Initiation Started"); break; case INITIATION_COMPLETE: System.out.println("Initiation Completed"); break; case MEDIA_IN_PROGRESS: System.out.println("Upload in progress"); System.out.println("Upload percentage: " + uploader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Upload Completed!"); break; case NOT_STARTED: System.out.println("Upload Not Started!"); break; } } }; uploader.setProgressListener(progressListener); // Call the API and upload the video. Video returnedVideo = videoInsert.execute(); // Print data about the newly inserted video from the API response. System.out.println("\n================== Returned Video ==================\n"); System.out.println(" - Id: " + returnedVideo.getId()); System.out.println(" - Title: " + returnedVideo.getSnippet().getTitle()); System.out.println(" - Tags: " + returnedVideo.getSnippet().getTags()); System.out.println(" - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus()); System.out.println(" - Video Count: " + returnedVideo.getStatistics().getViewCount()); } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }
From source file:com.ale46.YoutubePlaylist.java
License:Open Source License
YoutubePlaylist() {
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
try {//from w w w . j a v a 2s. c om
// Authorize the request.
Credential credential = YoutubeAuth.authorize(scopes, "playlistupdates");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(YoutubeAuth.HTTP_TRANSPORT, YoutubeAuth.JSON_FACTORY, credential)
.setApplicationName("youtube-cmdline-playlistupdates-sample").build();
} catch (GoogleJsonResponseException e) {
System.err.println(
"There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
From source file:com.ale46.YoutubeSearch.java
License:Open Source License
public List<SearchResult> search(String keyword) throws HttpResponseException { try {// w ww .jav a 2 s . c o m // This object is used to make YouTube Data API requests. The last // argument is required, but since we don't need anything // initialized when the HttpRequest is initialized, we override // the interface and provide a no-op function. youtube = new YouTube.Builder(YoutubeAuth.HTTP_TRANSPORT, YoutubeAuth.JSON_FACTORY, request -> { }).setApplicationName("youtube-cmdline-search-sample").build(); // Prompt the user to enter a query term. //String queryTerm = getInputQuery(); // Define the API request for retrieving search results. YouTube.Search.List search = youtube.search().list("id,snippet"); // Set your developer key from the Google Developers Console for // non-authenticated requests. See: // https://console.developers.google.com/ search.setKey(apiKey); search.setQ(keyword); // Restrict the search results to only include videos. See: // https://developers.google.com/youtube/v3/docs/search/list#type search.setType("video"); // To increase efficiency, only retrieve the fields that the // application uses. search.setFields("items(id/kind,id/videoId,snippet/title,snippet)"); long NUMBER_OF_VIDEOS_RETURNED = 25; search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); // Call the API and print results. SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); if (searchResultList != null) { //prettyPrint(searchResultList.iterator(), queryTerm); //prettyPrint(searchResultList.iterator()); return searchResultList; } } catch (GoogleJsonResponseException e) { System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (IOException e) { System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); } catch (Throwable t) { t.printStackTrace(); } return null; }
From source file:com.appian.google.glassware.mirror.auth.NewUserBootstrapper.java
License:Apache License
/** * Bootstrap a new user. Do all of the typical actions for a new user: * <ul>// w w w .ja va 2s. co m * <li>Creating a timeline subscription</li> * <li>Inserting a contact</li> * <li>Sending the user a welcome message</li> * </ul> */ public static void bootstrapNewUser(String userId) throws IOException { Credential credential = AuthUtil.newAuthorizationCodeFlow().loadCredential(userId); // Create contact Contact appianGlasswareContact = new Contact(); appianGlasswareContact.setId("com.appian.glassware.contact"); appianGlasswareContact.setDisplayName("Appian Glassware Contact"); appianGlasswareContact.setImageUrls( Lists.newArrayList("https://dl.dropboxusercontent.com/s/3r7wvml2tlor3q4/appianFigure.png")); appianGlasswareContact.setAcceptCommands( Lists.newArrayList(new Command().setType("TAKE_A_NOTE"), new Command().setType("POST_AN_UPDATE"))); Contact insertedContact = MirrorClient.insertContact(credential, appianGlasswareContact); LOG.info("Bootstrapper inserted contact " + insertedContact.getId() + " for user " + userId); try { // Subscribe to timeline updates Subscription subscription = MirrorClient.insertSubscription(credential, AppianGlasswareUtils.getNotificationCallbackUri(), userId, "timeline"); LOG.info("Bootstrapper inserted subscription " + subscription.getId() + " for user " + userId); } catch (GoogleJsonResponseException e) { LOG.warning("Failed to create timeline subscription. Might be running on " + "localhost. Details:" + e.getDetails().toPrettyString()); } // Send welcome timeline item TimelineItem timelineItem = new TimelineItem(); timelineItem.setText("Welcome to Appian Glassware. You have been subscribed for notifications."); ArrayList<MenuItem> menus = new ArrayList<MenuItem>(); AppianGlasswareUtils.createMenus(menus, true, true, true); timelineItem.setMenuItems(menus); timelineItem.setNotification(new NotificationConfig().setLevel("DEFAULT")); TimelineItem insertedItem = MirrorClient.insertTimelineItem(credential, timelineItem); LOG.info("Bootstrapper inserted welcome message " + insertedItem.getId() + " for user " + userId); }
From source file:com.cloudera.director.google.compute.GoogleComputeProvider.java
License:Apache License
private boolean hasError(GoogleJsonResponseException ex, int code, String reason) { if (ex.getStatusCode() != code) { return false; }/*from w w w .ja v a 2 s . c om*/ List<GoogleJsonError.ErrorInfo> errors = ex.getDetails().getErrors(); for (GoogleJsonError.ErrorInfo error : errors) { if (error.getReason().equals(reason)) { return true; } } return false; }
From source file:com.cmdev.tma4g.MainServlet.java
License:Apache License
/** * Do stuff when buttons on index.jsp are clicked */// w w w . j a v a 2s . c o m @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { String userId = AuthUtil.getUserId(req); Credential credential = AuthUtil.newAuthorizationCodeFlow().loadCredential(userId); String message = ""; if (req.getParameter("operation").equals("insertSubscription")) { // subscribe (only works deployed to production) try { MirrorClient.insertSubscription(credential, WebUtil.buildUrl(req, "/notify"), userId, req.getParameter("collection")); message = "Application is now subscribed to updates."; } catch (GoogleJsonResponseException e) { LOG.warning("Could not subscribe " + WebUtil.buildUrl(req, "/notify") + " because " + e.getDetails().toPrettyString()); message = "Failed to subscribe. Check your log for details"; } } else if (req.getParameter("operation").equals("deleteSubscription")) { // subscribe (only works deployed to production) MirrorClient.deleteSubscription(credential, req.getParameter("subscriptionId")); message = "Application has been unsubscribed."; } else if (req.getParameter("operation").equals("deleteTimelineItem")) { // Delete a timeline item LOG.fine("Deleting Timeline Item"); MirrorClient.deleteTimelineItem(credential, req.getParameter("itemId")); message = "Timeline Item has been deleted."; } else if (req.getParameter("operation").equals("setAlert")) { LOG.fine("Inserting Alert Item"); if (req.getParameter("stopId") != null) { AlertSubscription newSub = new AlertSubscription(AuthUtil.getUserId(req), req.getParameter("stopId")); TimelineItem timelineItem = makeDeletableTimelineItem(); timelineItem.setText("Created alert for stop ID " + req.getParameter("stopId")); // Triggers an audible tone when the timeline item is received MirrorClient.insertTimelineItem(credential, timelineItem); storeAlertSubscription(newSub); nextArrival(credential, newSub.getStopId()); message = "New alert created for " + newSub.getStopId(); } } else if (req.getParameter("operation").equals("listAlerts")) { listAlertSubscriptions(AuthUtil.getUserId(req)); } else { String operation = req.getParameter("operation"); LOG.warning("Unknown operation specified " + operation); message = "I don't know how to do that"; } WebUtil.setFlash(req, message); res.sendRedirect(WebUtil.buildUrl(req, "/")); }