how to call client_secrets.json from an external directory java? - java

I basically have a dynamic WEB-APP which through a servlet I am trying to retrieve a youtube video comments.
Although there is alot of article about it in the web but I don't know why none worked for me.
First Attempt:
private static int counter = 0;
private static YouTube youtube;
public static void getYoutubeOauth() throws Exception {
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
Credential credential = Auth.authorize(scopes, "commentthreads");
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build();
String videoId = "KIgxmV9xXBQ";
// Get video comments threads
CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute();
while (true) {
handleCommentsThreads(commentsPage.getItems());
String nextPageToken = commentsPage.getNextPageToken();
if (nextPageToken == null)
break;
// Get next page of video comments threads
commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute();
}
System.out.println("Total: " + counter);
}
With this I am getting nullpointerexception at line: Credential credential = Auth.authorize(scopes, "commentthreads");
If you can please explain what is scope and where do you get it from.
Second Attempt I tried creating a different function for getting credentials.
Second Attempt:
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
// Load client secrets.
Reader clientSecretReader = new InputStreamReader(
Auth.class.getResourceAsStream("/home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json"));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
// Checks that the defaults have been replaced (Default = "Enter X here").
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
+ "into src/main/resources/client_secrets.json");
return null;
}
// This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
.build();
// Build the local server and bind it to port 8080
LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
// Authorize.
return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
Here also Im getting an nullpointerexception at line Reader clientSecretReader = new InputStreamReader(... although If I would try nano /home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json in my terminal I can access the file.
Question: How to authorize my web-app and read client_secrets.json from an external directory.

Was a bit painful but made the second solution working.
So what I was doing wrong was that I was calling Auth.class.getResourceAsStream which it requires the data to be available to classLoader but to my classLoader it was not.
so what I had to do is to request my client_secrets.json from an external directory which then you have to use FileInputStream other than getResourceAsStream.
Both FileInputStream and getResourceAsStream works fine but they differ on your situation and different code.
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
Reader clientSecretReader = new InputStreamReader(
new FileInputStream("/client_secrets.json"));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
System.out.println(clientSecretReader.toString());
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
+ "into src/main/resources/client_secrets.json");
return null;
}
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
.build();
LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8081).build();
return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
private static int counter = 0;
private static YouTube youtube;
public static void getYoutubeOauth() throws Exception {
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
Credential credential = authorize(scopes, "commentthreads");
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build();
String videoId = "KIgxmV9xXBQ";
// Get video comments threads
CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute();
while (true) {
handleCommentsThreads(commentsPage.getItems());
String nextPageToken = commentsPage.getNextPageToken();
if (nextPageToken == null)
break;
commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute();
}
System.out.println("Total: " + counter);
}
private static YouTube.CommentThreads.List prepareListRequest(String videoId) throws Exception {
return youtube.commentThreads()
.list("snippet,replies")
.setVideoId(videoId)
.setMaxResults(100L)
.setModerationStatus("published")
.setTextFormat("plainText");
}
private static void handleCommentsThreads(List<CommentThread> commentThreads) {
for (CommentThread commentThread : commentThreads) {
List<Comment> comments = Lists.newArrayList();
comments.add(commentThread.getSnippet().getTopLevelComment());
CommentThreadReplies replies = commentThread.getReplies();
if (replies != null)
comments.addAll(replies.getComments());
System.out.println("Found " + comments.size() + " comments.");
// Do your comments logic here
counter += comments.size();
}
}
Note: change FileInputStream location to your own location.
Then you can call getYoutubeOauth and hope for getting a working response :)

Related

Application Stop When Google Calendar Oauth

The application freezes while Google Calendar API authentication is in progress.
Below is my source code.
private final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
private java.io.File DATA_STORE_DIR;
private FileDataStoreFactory DATA_STORE_FACTORY;
private final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private HttpTransport HTTP_TRANSPORT;
private final List<String> SCOPES = Arrays.asList(CalendarScopes.CALENDAR);
#Value("#{config['path.googleAuth']}")
private String googleAuthPath;
public void setGoogleData(String member_id_num) throws Exception{
String userHome = "";
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
userHome = System.getProperty("user.home");
}else if(System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0) {
userHome = googleAuthPath;
}else {
userHome = System.getProperty("user.home");
}
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_DIR = new java.io.File(userHome,".credentials_sellers/calendar-java-quickstart_sellers"+File.separator+member_id_num);
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
log.info("DATA_STORE_DIR=" + DATA_STORE_DIR);
}
public Credential authorize(String member_id_num) throws Exception {
setGoogleData(member_id_num);
InputStream in = GoogleCalendarService.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
log.info("clientSecrets = " + clientSecrets);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
log.info("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
my client_secret.json
{
"installed": {
"client_id": "459740830795-lm5pnqsule6jg4ufu3uvnufgr7tdajn6.apps.googleusercontent.com",
"project_id": "the-sellers-255504",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "L3kDYxfDoSDUG5wM3XEMDi9H",
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost", "http://xxx.xxx.x.xxx", "http://xxx.xxx.x.xxx:8090", "http://xxx.xxx.x.xxx", "http://xxx.xxx.x.xxx:8090"]
}
}
In my local environment, the test was successful.
However, the website hangs because I try to link it to a Linux server.
help me please ....

List all events from Google calendar

I want to list all events all events from Google calendar using this code:
public class GoogleCalendarImpl
{
private static final String APPLICATION_NAME = "";
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/calendar_sample");
private static FileDataStoreFactory dataStoreFactory;
private static HttpTransport httpTransport;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static com.google.api.services.calendar.Calendar client;
static final java.util.List<Calendar> addedCalendarsUsingBatch = Lists.newArrayList();
private static final String calId = "edrhrtherherh#development-1384.iam.gserviceaccount.com";
private static Credential authorize() throws Exception
{
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(GoogleCalendarImpl.class.getResourceAsStream("/development-241a19899242.json")));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory).build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args)
{
try
{
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
Credential credential = authorize();
client = new com.google.api.services.calendar.Calendar.Builder(
httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
getAllEvents();
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
catch (Throwable t)
{
t.printStackTrace();
}
System.exit(1);
}
private static List<Event> getAllEvents() throws IOException
{
List<Event> events = new ArrayList<>();
String nextPageToken = null;
do
{
System.out.println("Loading page " + nextPageToken);
Events feed = client.events().list(calId).setPageToken(nextPageToken).execute();
events.addAll(feed.getItems());
nextPageToken = feed.getNextPageToken();
}
while (nextPageToken != null);
return events;
}
}
But when I run the code Firefox(default web browser) is started and I'm redirected to page:
Error: redirect_uri_mismatch
The redirect URI in the request, http://localhost:56345/Callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/1024206104045435454813?project=762076316631 to update the authorized redirect URIs.
I would like to get all entried from Google calendar configured into my account.
How I can fix this issue?
How to fix Error: redirect_uri_mismatch
Go to your GDC and check what you specified as URI redirect. It should be
http://localhost:portnumber/oauth2callback.
Don't forget the 'oauth2' part.

Null Pointer Exception when accessing Google Analytics report data using different credentials

I am following the tutorial to get access to the GA account report data by executing a simple GA query, by using the Google Developers console.
I followed all steps mentioned in the tutorial and the code works fine.
I have included the code below.
public class GoogleAnalyticsAccess {
private static final String APPLICATION_NAME = "GAAccess/1.0";
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/analytics_sample");
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static FileDataStoreFactory dataStoreFactory;
private static HttpTransport httpTransport;
public static Credential authorizeUser() throws IOException {
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(
GoogleAnalyticsAccess.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter") ||
clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/?api=analytics " +
"into Dashboard/src/main/resources/client_secrets.json");
System.exit(1);
}
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
clientSecrets, Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
.setDataStoreFactory(dataStoreFactory).build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static Analytics getAnalyticsServiceObject(Credential credential){
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
.build();
}
public static String getGAAccountId(Analytics analytics) throws IOException {
String accountId =null;
Accounts accounts = analytics.management().accounts().list().execute();
List<Account> accountsList = accounts.getItems();
if(accountsList.isEmpty()){
System.err.println("No accounts found");
}
else{
for(int i=0; i<accountsList.size();i++){
if(accountsList.get(i).getName().equals("XXXX")){
accountId = accountsList.get(i).getId();
break;
}
}
}
return accountId;
}
public static String getGAWebPropertyId(Analytics analytics,String accountId) throws IOException {
String webPropertyId = null;
Webproperties webProperties = null;
webProperties = analytics.management().webproperties().list(accountId).execute();
List<Webproperty> webPropertiesList = webProperties.getItems();
if (webPropertiesList.isEmpty()) {
System.err.println("No Web Properties found");
} else {
for (int i=0; i<webPropertiesList.size();i++){
if(webPropertiesList.get(i).getName().equals("XXXX")){
webPropertyId = webPropertiesList.get(i).getId();
}
}
}
return webPropertyId;
}
public static String getGAViewId(Analytics analytics, String accountId, String webPropertyId) throws IOException {
String viewId = null;
Profiles views = analytics.management().profiles().list(accountId, webPropertyId).execute();
List<Profile> viewsList = views.getItems();
if (viewsList.isEmpty()) {
System.err.println("No profiles found");
} else {
for(int i=0; i<viewsList.size();i++){
if(viewsList.get(i).getName().equals("XXXX")){
viewId = viewsList.get(i).getId();
}
}
}
return viewId;
}
public static List<GoogleAnalyticsData> executeGAQuery(Analytics analytics, String viewId, String dimension) throws IOException {
List<GoogleAnalyticsData> dataList = new ArrayList<GoogleAnalyticsData>();
if (viewId == null) {
System.err.println("No profiles found.");
} else {
GaData gaData = analytics.data().ga().get("ga:" + viewId, "2015-02-13", "2015-02-27", "ga:users")
.setDimensions("ga:" + dimension)
.setMaxResults(200).execute();
if (gaData.getRows() == null || gaData.getRows().isEmpty()) {
System.out.println("No results Found.");
} else {
GoogleAnalyticsData data;
for (List<String> row : gaData.getRows()) {
data = new GoogleAnalyticsData();
data.setName(row.get(0));
data.setValue(Integer.parseInt(row.get(1)));
dataList.add(data);
}
}
}
return dataList;
}
public static void main(String[] args) throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
Credential credential = authorizeUser();
Analytics analytics = getAnalyticsServiceObject(credential);
String accountId = getGAAccountId(analytics);
String webPropertyId = getGAWebPropertyId(analytics,accountId);
String viewId = getGAViewId(analytics,accountId,webPropertyId);
List<GoogleAnalyticsData> continentDataList = executeGAQuery(analytics, viewId, "continent");
List<GoogleAnalyticsData> countryDataList = executeGAQuery(analytics, viewId, "country");
for(int i =0; i <continentDataList.size();i++){
System.out.println(continentDataList.get(i).getName() + " " + continentDataList.get(i).getValue());
}
for(int i=0; i< countryDataList.size();i++){
System.out.println(countryDataList.get(i).getName() + " " + countryDataList.get(i).getValue());
}
}
}
I get an error when I access the same GA account report data by giving the credential (Client secret and Id) of another user who also has shared access to that report data.
I am successfully able to access the report data using the other users credentials If I have already run the java application using my credentials first. But If I run the app with the other users credentials first, then I get the following error.
The Stack trace is shown below.
Exception in thread "main" java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:92)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at org.dashboard.access.data.GoogleAnalyticsAccess.getGAAccountId(GoogleAnalyticsAccess.java:266)
at org.dashboard.access.data.GoogleAnalyticsAccess.main(GoogleAnalyticsAccess.java:364)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
The specific exception occurs at the following line in method getGAAccountId.
Accounts accounts = analytics.management().accounts().list().execute();
Is there any workaround for this issue?
If your client_secrets.json is well configured, you just have to delete the file .store/analytics_sample and run it again.

while refresh page getting code already redeemed - using google calendar API

This is my code, its working fine. but if refresh a page, getting 400 error.
and log shows code already redeemed. please suggest where is error. I used refresh token also even though getting error.
refresh token correctly used?
Thanks
HttpSession session = req.getSession(true); //create user session
try {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
//String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
String scope = "https://www.googleapis.com/auth/calendar";
String code = req.getParameter("code");
String eventid = req.getParameter("eventid");
if(eventid != null)
session.setAttribute("eventid", req.getParameter("eventid"));
GoogleTokenResponse response=null;
Credential credential=null;
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Collections.singleton(scope)).setAccessType("offline").setApprovalPrompt("force").build();
if(code == null){
String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(CLIENT_ID,REDIRECT_URI,Collections.singleton(scope)).setState("").build();
resp.sendRedirect(authorizationUrl);
}else{
response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI)
.execute();
// End of Step 2
flow.createAndStoreCredential(response, null);
}
// Step 2: Exchange
if(session.getAttribute("refresh") != null){
credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build().setFromTokenResponse((new TokenResponse().setRefreshToken(session.getAttribute("refresh").toString())));
credential.refreshToken();
}else{
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build().setFromTokenResponse(response);
session.setAttribute("refresh", credential.getRefreshToken());
}
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Minutes Of Meeting").build();
List<CalEvent> lstEvent = new ArrayList<CalEvent>();
Date d1= getRelativeDate(java.util.Calendar.MONTH, -1);
String pageToken = null;
do {
Events events = service.events().list("primary").setTimeMin(new DateTime(d1,TimeZone.getTimeZone("IST"))).setPageToken(pageToken).execute();
List<Event> items = events.getItems();
for (Event event : items) {
//System.out.println("Event Name: " + event.getSummary() + " Event Organiser :"+event.getOrganizer()+" Event Guest"+event.getAttendees());
//lstEvent.put(event.getSummary(),event.getSummary());
//lstEvent.put(event.getOrganizer().getDisplayName(),event.getOrganizer().getDisplayName());
if(event.getStart().isEmpty()){
List attees = event.getAttendees();
lstEvent.add(new CalEvent(event.getId(),event.getSummary(),event.getOrganizer().getDisplayName(),event.getLocation(),"","",attees));
}else{
Long dt = event.getStart().getDateTime()==null?0:event.getStart().getDateTime().getValue();
Date dt11 = new Date(dt);
Long dt1 = event.getEnd().getDateTime()==null?0:event.getEnd().getDateTime().getValue();
Date dt111 = new Date(dt1);
List attees = event.getAttendees();
lstEvent.add(new CalEvent(event.getId(),event.getSummary(),event.getOrganizer().getDisplayName(),event.getLocation(),dt11.toString(),dt111.toString(),attees));
}
//Date returnd = new Date(dt11.getTime()+(330*60000));
//Date returned = new Date(dt111.getTime()+(330*60000));
}
pageToken = events.getNextPageToken();
} while (pageToken != null);
req.setAttribute("events", lstEvent);
RequestDispatcher rd = req.getRequestDispatcher("/Home.jsp");
try {
rd.forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please help me solve this issue

You Tube video upload "401 Unauthorized" using youtube-data-api

I am trying to upload video to Youtube using the java youtube api and getting "401 Unauthorized".
I have created a service account using the developers console and using that .p12 file
Here is the code I am using.
public class YouTubeUtils {
private static YouTube youtube;
private static final String VIDEO_FORMAT = "video/*";
private static final String APPLICATION_NAME = "TestApp";
private static final String SERVICE_ACCOUNT_EMAIL = "xxxxx#developer.gserviceaccount.com";
private static HttpTransport httpTransport;
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public static void main(String[] args) {
try {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
if (SERVICE_ACCOUNT_EMAIL.startsWith("Enter ")) {
System.err.println(SERVICE_ACCOUNT_EMAIL);
System.exit(1);
}
String p12Content = Files.readFirstLine(new File("C:/Workspace/TestApp.p12"),
Charset.defaultCharset());
if (p12Content.startsWith("Please")) {
System.err.println(p12Content);
System.exit(1);
}
List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_UPLOAD);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(new File("C:/Workspace/TestApp.p12"))
.build();
youtube = new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
Video videoObjectDefiningMetadata = new Video();
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("public");
videoObjectDefiningMetadata.setStatus(status);
VideoSnippet snippet = new VideoSnippet();
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());
List<String> tags = new ArrayList<String>();
tags.add("test");
tags.add("video");
snippet.setTags(tags);
videoObjectDefiningMetadata.setSnippet(snippet);
FileInputStream fin = new FileInputStream(new File("C:/Workspace/small.mp4"));
InputStreamContent mediaContent = new InputStreamContent(VIDEO_FORMAT,fin);
YouTube.Videos.Insert videoInsert = youtube.videos().insert(
"snippet,statistics,status",
videoObjectDefiningMetadata, mediaContent);
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
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 (IOException e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
It prints
Initiation Started
Initiation Completed
and after that I am getting "401 Unauthorized"
Can someone help me on this.
Thanks
Please refer to this link, it says Service Accounts do not work with the YouTube API
Also, please refer to this link to know how to get authorization credentials and what type of credentials the Youtube API supports.
And here is an example of uploading a video to youtube using OAuth 2.0.

Categories