Get post form twitter public profile in java - java

I am trying to review twitter public profile using twitter4J.
I tried the examples on twitter4j git location but it did not worked.
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterTimeLine {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
int pageno = 1;
String user = "google";
List<Status> statuses = new ArrayList<Status>();
while (true) {
try {
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(user, page));
if (statuses.size() == size)
break;
}
catch(TwitterException e) {
e.printStackTrace();
}
}
System.out.println("Total: "+statuses.size());
}
}
But it always gives me error
400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
message - Bad Authentication data.
code - 215
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=4be80492 or
http://www.google.co.jp/search?q=0a6306df
TwitterException{exceptionCode=[4be80492-0a6306df], statusCode=400, message=Bad Authentication data., code=215, retryAfter=-1, rateLimitStatus=null, version=4.0.4}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1786)
at twitter4j.TwitterImpl.getUserTimeline(TwitterImpl.java:131)
at com.twitter.ibeat.iBeatTwitter.TwitterTimeLine.main(TwitterTimeLine.java:33)
400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
message - Bad Authentication data.
code - 215
Could you please help me to get this working.
Regards
Virendra Agarwal

Problem was solved using oAuth token and Query API from twitter4J.

Related

How to send messages from an app to a user using restfb?

I am trying to use restfb to send a message to who likes the page.Using the graph API I got the page access_token and recipient_id.When I try to send it ends in an exception showing
Exception in thread "main" com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: Error validating access token: Session has expired on Friday, 03-Feb-17 03:00:00 PST. The current time is Friday, 03-Feb-17 21:20:41 PST. (code 190, subcode 463)
But when I try to access the details of user in graph it is working fine.Am i doing something wrong?..Please help
Thanks in advance....
The java code
import java.util.List;
import com.restfb.*;
import com.restfb.FacebookClient.AccessToken;
import com.restfb.exception.FacebookException;
import com.restfb.json.JsonObject;
import com.restfb.types.Conversation;
import com.restfb.types.Message;
import com.restfb.types.User;
import com.restfb.types.send.IdMessageRecipient;
import com.restfb.types.send.PhoneMessageRecipient;
import com.restfb.types.send.SendResponse;
import facebook4j.Facebook;
public class Fbsample {
public static void main(String[] argv) throws FacebookException
{
FacebookClient facebookClient = new DefaultFacebookClient("***");
User user = facebookClient.fetchObject("me", User.class);
String name=user.getFirstName();
String email=user.getEmail();
String id=user.getId();
System.out.println(name);
System.out.println(id);
JsonObject picture = facebookClient.fetchObject("me/picture",JsonObject.class,Parameter.with("redirect","false"), Parameter.with("type","large"));
System.out.println(picture);
IdMessageRecipient recipient = new IdMessageRecipient("****");
Message msg = new Message();
msg.setMessage("Hello");
String pageAccessToken ="***";
// create a version 2.6 client
FacebookClient pageClient = new DefaultFacebookClient(pageAccessToken, Version.VERSION_2_6);
SendResponse resp = pageClient.publish("me/messages", SendResponse.class,
Parameter.with("recipient", recipient), // the id or phone recipient
Parameter.with("message", msg)); // one of the messages from above
}
}
Here instead of real access token and recipient_id I have given * for now.And one more thing which id should I give the user_id or conversation_id and access token for page or user?...

Working with twitter API

I'm trying to create a small website which takes user's twitter username and retrieve the basic information from it like: screen name, created date, number of followers, etc... and display it. But I couldn't find a new helpful working tutorial or example of how to work with twitter API. Can someone please recommend something for me or just give some instructions of how should I start and work please? I prefer it to be done with Java or PHP.
Also I have a problem, when creating my application access key in twitter, I can't create the access token! the button is not shown! how can I solve this?
You Can use below code-
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterSearch {
private static final String CATEGORY = "Mobile";
private static final String SOURCE = "Twitter";
public static void main(String ...args) throws TwitterException, IOException
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(TwitterConfig.OATH_CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterConfig.OATH_CONSUMER_SECRET)
.setOAuthAccessToken(TwitterConfig.OATH_ACCESS_TOKEN)
.setOAuthAccessTokenSecret(TwitterConfig.OATH_ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
System.out.println("Product to be searched " + args[0]);
Query query = new Query(args[0]);
query.setLang("en");
query.setLocale("en_IN");
query.setCount(100);
QueryResult result = twitter.search(query);
System.out.println("Output File "+ args[1]);
System.out.println(result.getTweets());
for(Status tweet : result.getTweets())
{
System.out.println(tweet.getText());
}
}
}
result.getTweets() return a List, and you can iterate over that list and can print tweet.getText() to print tweet.
Use this maven dependency-
<dependency><groupId>org.twitter4j</groupId><artifactId>twitter4j-core</artifactId><version>[4.0,)</version></dependency>
Refer below link for keys-
https://dev.twitter.com/oauth/overview

Java Rest API client - GET method - Error 415

I am new to writing Java client for Restful API using Apache CXF.
On running below code I am getting error 415 returned which when I looked online shows as "unsupported media type". In order to fix it I changed the code to "target.request(MediaType.APPLICATION_XML)" from original target.request(). However this didn't fix the code.
What is the best way to debug this issue?
Thanks a lot in advance for your time.
Update: After discussion with the Rest API developer I came to know that I need to add a header "("Content-Type", "application/x-www-form-urlencoded");". but I am not sure how to add a header. Does anyone know how to add this header here?
package com.blackhawk.ivr.restAPI.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class BlissRestAPI {
public static final String BLISS_SERVICRE_URL = "http://x.x.x.x:9090/services";
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(BLISS_SERVICRE_URL);
target = target.path("/cardmanagementservices/v3/card/status").queryParam("ani", "xxxxxxxxxx").queryParam("card.expiration", "xxxxxx").queryParam("card.number", "xxxxxxxxxxxxxxxx").queryParam("channel.id", "xyz");
Invocation.Builder builder = target.request(MediaType.APPLICATION_XML);
Response response = builder.get();
System.out.println(response.getStatus());
response.close();
client.close();
}
}
First you can change the media type as given below.
Client: MediaType.APPLICATION_XML
Rest: MediaType.APPLICATION_JSON
JAX-WS are Java standard to build web service. So you have used it here, As my knowledge it is easy to use axis 2 to this kind of web services and clients since there are more implementations of JAX-WS. So i will give you a solution using apache axis technology.
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
public class axisClient {
public static void main(String [] args) throws Exception {
String endpoint = "http://localhost:8090/archive_name/service_name.jws";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( "service_method_name" );
call.addParameter("parameter_name", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_STRING );
call.setProperty(Call.CHARACTER_SET_ENCODING, "UTF-8");
String jsonString = (String) call.invoke( new Object [] { "parameter_value"});
System.out.println("Got result : " + jsonString);
}
}
I got it working by using below code (got 200 status returned)
WebClient client = WebClient.create(BLISS_SERVICRE_URL);
client.path("/cardmanagementservices/v3/card/status").query("ani", "xxxxxxxxxx").query("card.expiration", "xxxxxx").query("card.number", "xxxxxxxxxxxxxx").query("channel.id", "xxxxx");
client.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML);
client.header("Content-Type","application/x-www-form-urlencoded");
Response response = client.get();
System.out.println(response.getStatus());

Insufficient Permission when run youtube retriving comments

This is my whole code. I want to give a video ID which from youtube to get the comments related to this vedio ID. But always show that I have Insufficient Permission.
I have tried to address this, and found youtube .commentThreads().list("snippet").setVideoId("tLTm_POao1c") .setTextFormat("plainText").execute(); is the problem. Specifically, execute() in this line calls "Insufficient Permission".
Why is this?
package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addsubscription_sample;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import com.google.api.client.util.Preconditions;//aiyamaya
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
//import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.Subscription;
import com.google.api.services.youtube.model.SubscriptionSnippet;
import com.google.common.collect.Lists;
import com.google.api.services.youtube.model.CommentThreadListResponse;
import com.google.api.services.youtube.model.CommentThread;
import com.google.api.services.youtube.model.CommentSnippet;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addsubscription_sample.Auth;
//import com.google.api.services.samples.youtube.cmdline.Auth;
/**
* Demo of subscribing user to a channel using the YouTube Data API (V3) with
* OAuth2 for authorization.
*
* #author Ibrahim Ulukaya
*/
public class AddSubscription {
/** Global instance of the HTTP transport. */
// private static final HttpTransport HTTP_TRANSPORT = new
// NetHttpTransport();
/** Global instance of the JSON factory. */
// private static final JsonFactory JSON_FACTORY = new JacksonFactory();
/** Global instance of Youtube object to make all API requests. */
private static YouTube youtube;
public static void main(String[] args) {
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", "bproxy.rmit.edu.au");
System.setProperty("proxyPort", "8080");
List<String> scopes = Lists
.newArrayList("https://www.googleapis.com/auth/youtube");
try {
// Authorization.
Credential credential = Auth.authorize(scopes, "commentthreads");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT,
Auth.JSON_FACTORY, credential).setApplicationName(
"youtube-cmdline-commentthreads-sample").build();
// YouTube object used to make all API requests.
CommentThreadListResponse videoCommentsListResponse = youtube
.commentThreads().list("snippet").setVideoId("tLTm_POao1c")
.setTextFormat("plainText").execute();
List<CommentThread> videoComments = videoCommentsListResponse
.getItems();
} 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();
}
}
/*
* Returns a channel id (String) from user via the terminal.
*/
}
This is the error information:
May 22, 2015 8:19:15 AM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\E18300\.oauth-credentials
May 22, 2015 8:19:15 AM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\E18300\.oauth-credentials
2015-05-22 08:19:15.192:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2015-05-22 08:19:15.193:INFO::jetty-6.1.26
2015-05-22 08:19:15.212:INFO::Started SocketConnector#localhost:8080
2015-05-22 08:19:20.433:INFO::Stopped SocketConnector#localhost:8080
GoogleJsonResponseException code: 403 : Insufficient Permission
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1045)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addsubscription_sample.AddSubscription.main(AddSubscription.java:86)
The documentation lacks in this part, but you need to use the scope https://www.googleapis.com/auth/youtube.force-ssl to retrieve comments from the YouTube API. Took me way too much time to solve this issue.
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl'
];
to retrieve comments from the YouTube API add
https://www.googleapis.com/auth/youtube.force-ssl
this into OAUTH2_SCOPES array
As the error message indicates, your request does not have sufficient permissions. If you look at the API Reference Overview you will see:
Every request must either specify an API key (with the key parameter) or provide an OAuth 2.0 token. Your API key is available in the API console's API Access pane for your project.
For example I am able to view the comment thread list for a video by making a GET request to this link in the browser directly:
https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&key=YOUR_KEY&videoId=tLTm_POao1c. You will need to replace YOUR_KEY with your application key that you can find in your Google developer console.
I don't know why the code sample for comment threads does not mention anything about the need to include the API key (probably because it is assumed that you read the API Overview first). But
if you look at this other code sample, you will see that you can include a developer key in a local file that you can load into a Properties object:
// Read the developer key from the properties file.
Properties properties = new Properties();
try {
InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
properties.load(in);
} catch (IOException e) {
System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
+ " : " + e.getMessage());
System.exit(1);
}
Further down the line, the api key is extracted from the Properties object and is used in the search API call:
// Set your developer key from the Google Developers Console for
// non-authenticated requests. See:
// https://console.developers.google.com/
String apiKey = properties.getProperty("youtube.apikey");
search.setKey(apiKey);
search.setQ(queryTerm);
In a similar manner, you can call setKey() on your code, as described by the JavaDocs: https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/YouTube.CommentThreads.List.html#setKey(java.lang.String)
So, you may need to add something like this:
CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
.list("snippet")
.setKey(YOUR_KEY)
.setVideoId("tLTm_POao1c")
.setTextFormat("plainText")
.execute();
You don't even need the Properties file, unless you plan to change the API key after you write the code and deploy it.
You only need a key to retrieve comments. Something like this:
String apiUrl = "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&videoId=" + ytId + "&moderationStatus=published&order=relevance&maxResults=5&key=" + apiKey;
Then handle the Json response.

BigQuery and OAuth2

I'm trying to access Google BigQuery using Service Account approach. My code is as follows:
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
GoogleCredential credentials = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("XXXXX#developer.gserviceaccount.com")
.setServiceAccountScopes(BigqueryScopes.BIGQUERY)
.setServiceAccountPrivateKeyFromP12File(
new File("PATH-TO-privatekey.p12"))
.build();
Bigquery bigquery = Bigquery.builder(HTTP_TRANSPORT, JSON_FACTORY).setHttpRequestInitializer(credentials)
.build();
com.google.api.services.bigquery.Bigquery.Datasets.List datasetRequest = bigquery.datasets().list(
"PROJECT_ID");
DatasetList datasetList = datasetRequest.execute();
if (datasetList.getDatasets() != null) {
java.util.List<Datasets> datasets = datasetList.getDatasets();
System.out.println("Available datasets\n----------------");
for (Datasets dataset : datasets) {
System.out.format("%s\n", dataset.getDatasetReference().getDatasetId());
}
}
But it throws the following exception:
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Authorization required",
"reason" : "required"
} ],
"message" : "Authorization required"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:159)
at com.google.api.client.googleapis.json.GoogleJsonResponseException.execute(GoogleJsonResponseException.java:187)
at com.google.api.client.googleapis.services.GoogleClient.executeUnparsed(GoogleClient.java:115)
at com.google.api.client.http.json.JsonHttpRequest.executeUnparsed(JsonHttpRequest.java:112)
at com.google.api.services.bigquery.Bigquery$Datasets$List.execute(Bigquery.java:979)
The exception is fired on this line:
DatasetList datasetList = datasetRequest.execute();
I'm getting the account ID from Google's API console from the second line on the section that looks like this:
Client ID: XXXXX.apps.googleusercontent.com
Email address: XXXXX#developer.gserviceaccount.com
What am I missing?
Eureka! Both Eric's and Michael's code works well.
The error posted in the question can be reproduced by setting the time on the client machine incorrectly. Fortunately, it can be solved by setting the time on the client machine correctly.
Note: For what it's worth, I synchronized the time on a Windows 7 box using the "Update now" button in the "Internet Time Settings" dialog. I figured that should be pretty idiot-proof... but I guess I beat the system. It corrected the seconds but left the machine off by exactly one minute. The BigQuery call failed after that. It succeeded after I manually changed the time.
Our error handling code in the Java library needs to be improved a bit!
It looks like the signed JWT for requesting an OAuth access token is failing. You can see this by enabling the logs that #MichaelManoochehri mentioned above.
There's only a few things that I think could be causing this failure:
Invalid signature (using the wrong key)
Invalid e-mail address for the service account (I think that's been ruled out)
Invalid date/time stamp used for generating the signed blob (an issue date, and an expiration date)
Invalid scope (I think that's been ruled out)
You should check that your date/time is properly set on your server with the proper timezone -- sync'd to NTP. You can use time.gov to see the official US atomic clock time.
EDIT: The answer I gave below is relevant to using Google App Engine Service Accounts - leaving here for reference.
Double check that you have added your service account address to your project's team page as an owner.
I'd recommend using the AppIdentityCredential class to handle service account auth. Here's a small snippet that demonstrates this, and I'll add additional documentation about this on the BigQuery API developer page.
Also, make sure that you are using the latest version of the Google Java API client (as of today, it's version "v2-rev5-1.5.0-beta" here).
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryRequest;
#SuppressWarnings("serial")
public class Bigquery_service_accounts_demoServlet<TRANSPORT> extends HttpServlet {
// ENTER YOUR PROJECT ID HERE
private static final String PROJECT_ID = "";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String BIGQUERY_SCOPE = "https://www.googleapis.com/auth/bigquery";
AppIdentityCredential credential = new AppIdentityCredential(BIGQUERY_SCOPE);
Bigquery bigquery = Bigquery.builder(TRANSPORT,JSON_FACTORY)
.setHttpRequestInitializer(credential)
.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
public void initialize(JsonHttpRequest request) {
BigqueryRequest bigqueryRequest = (BigqueryRequest) request;
bigqueryRequest.setPrettyPrint(true);
}
}).build();
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println(bigquery.datasets()
.list(PROJECT_ID)
.execute().toString());
}
}
Here is a complete snippet for reference:
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.Bigquery.Datasets;
import com.google.api.services.bigquery.model.DatasetList;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
public class BigQueryJavaServiceAccount {
private static final String SCOPE = "https://www.googleapis.com/auth/bigquery";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
public static void main(String[] args) throws IOException, GeneralSecurityException {
GoogleCredential credential = new GoogleCredential.Builder().setTransport(TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("XXXXXXX#developer.gserviceaccount.com")
.setServiceAccountScopes(SCOPE)
.setServiceAccountPrivateKeyFromP12File(new File("my_file.p12"))
.build();
Bigquery bigquery = Bigquery.builder(TRANSPORT, JSON_FACTORY)
.setApplicationName("Google-BigQuery-App/1.0")
.setHttpRequestInitializer(credential).build();
Datasets.List datasetRequest = bigquery.datasets().list("publicdata");
DatasetList datasetList = datasetRequest.execute();
System.out.format("%s\n", datasetList.toPrettyString());
}

Categories