There is an example for getting the keywords in an adgroup but I want to find the count of all keywords in the account.
How can I do this in java?
Here is how I modified an adwords api code to make it able to retrieve the count of keywords in an account (specified as clientCustomerId in ads.properties file).
package adwords.axis.v201609.basicoperations;
import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201609.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201609.cm.AdGroupCriterionPage;
import com.google.api.ads.adwords.axis.v201609.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201609.cm.Paging;
import com.google.api.ads.adwords.axis.v201609.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.selectorfields.v201609.cm.AdGroupCriterionField;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.client.auth.oauth2.Credential;
import java.text.NumberFormat;
/**
* This example gets the count of all ad group criteria in an account.
*
* #modified by Biniam Asnake.
*/
public class GetCountOfKeywordsInAccount {
public static void main(String[] args) throws Exception {
// execution duration counter
long started = System.currentTimeMillis();
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(OfflineCredentials.Api.ADWORDS)
.fromFile()
.build()
.generateCredential();
// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
AdWordsServices adWordsServices = new AdWordsServices();
runExample(adWordsServices, session);
System.out.println("Execution took: " + ((System.currentTimeMillis() - started) / 1000) + " seconds.");
}
public static void runExample(AdWordsServices adWordsServices, AdWordsSession session) throws Exception {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface adGroupCriterionService =
adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
// Create selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields(AdGroupCriterionField.Id)
.in(AdGroupCriterionField.CriteriaType, "KEYWORD")
.in(AdGroupCriterionField.Status, "ENABLED")
.build();
// Set selector paging = the most important change is to set numberResults to 0.
Paging paging = new Paging();
paging.setNumberResults(0);
selector.setPaging(paging);
// Get all ad group criteria.
AdGroupCriterionPage page = adGroupCriterionService.get(selector);
System.out.println("Count of Keywords = " + NumberFormat.getInstance().format(page.getTotalNumEntries()));
}
}
Make sure you have ads.properties file in your class path.
# Credentials for accessing Google AdWords API
api.adwords.refreshToken=SOME-THING
api.adwords.clientId=SOME-THING
api.adwords.clientSecret=SOME-THING
api.adwords.userAgent=SOME-THING
api.adwords.developerToken=SOME-THING
api.adwords.isPartialFailure=true
api.adwords.clientCustomerId=123456789
Related
I created a basic Vaadin application then added my Domino Jar files.
When I run the application, I get
[com.vaadin.server.ServiceException: java.lang.NoClassDefFoundError: lotus/domino/NotesException]
I've read a bunch of articles that talk about using OSGI etc. Isn't there a simple way to access Domino data from Vaadin without all the plug-ins etc? If not can someone explain why?
This is the calling code
package com.lms.helloDomino;
import javax.servlet.annotation.WebServlet;
import com.lms.service.StarService;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import lotus.domino.NotesException;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of an HTML page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {#link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
#Theme("mytheme")
public class MyUI extends UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
StarService myStarService = null;
try
{
myStarService = new StarService();
myStarService.openStarDB();
} catch ( Exception e1 )
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
final VerticalLayout layout = new VerticalLayout();
final TextField name = new TextField();
name.setCaption("Your Domino Name");
name.setValue( myStarService.getNABProfile( "" ).fullName.toString() );
Button button = new Button("Click Me");
button.addClickListener(e -> {
layout.addComponent(new Label("Thanks " + name.getValue()
+ ", it works!"));
});
layout.addComponents(name, button);
setContent(layout);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
Here is the domino code
package com.lms.service;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.NotesFactory;
public class StarService
{
public static Session notesSession = null;
public static Session getNotesSession()
{
if( notesSession == null )
try
{
notesSession = NotesFactory.createSession( "testHostServer", "testUser", "testPassword" );
} catch ( NotesException e )
{
e.printStackTrace();
}
return notesSession;
}
public StarService() throws NotesException
{
System.out.println( "Begin StarService Constructor" );
// Setup the notes connectivity
getNotesSession();
System.out.print( getNotesSession().getUserName() );
System.out.println( "End STARService Constructor" );
}
}
Turns out it was a build path issue. A big thank you to Karsten Lehmann from mindoo.de who helped me figure this out.
I didn't realize when running an Apache web server which serves up the Vaadin application, required my Domino .jar files on it's build path as well. He showed my how to add the .jar files to Apache's as follows:
Double click the Apache server under the servers tab
Click the Open Launch Configuration
Click the Class Path Tab
Highlight User Entries and Add External Jar files.
I've been looking for this off / on for a year now. Can't believe it's finally working!!!
I am using Lucene 6.6 and I am facing difficulty in importing lucene.queryparser and I did check the lucene documentations and it doesn't exist now.
I am using below code. Is there any alternative for queryparser in lucene6.
import java.io.IOException;
import java.text.ParseException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
public class HelloLucene {
public static void main(String[] args) throws IOException, ParseException {
// 0. Specify the analyzer for tokenizing text.
// The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer();
// 1. create the index
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter w = new IndexWriter(index, config);
addDoc(w, "Lucene in Action", "193398817");
addDoc(w, "Lucene for Dummies", "55320055Z");
addDoc(w, "Managing Gigabytes", "55063554A");
addDoc(w, "The Art of Computer Science", "9900333X");
w.close();
// 2. query
String querystr = args.length > 0 ? args[0] : "lucene";
// the "title" arg specifies the default field to use
// when no field is explicitly specified in the query.
Query q = null;
try {
q = new QueryParser(Version.LUCENE_6_6_0, "title", analyzer).parse(querystr);
} catch (org.apache.lucene.queryparser.classic.ParseException e) {
e.printStackTrace();
}
// 3. search
int hitsPerPage = 10;
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// 4. display results
System.out.println("Found " + hits.length + " hits.");
for (int i = 0; i < hits.length; ++i) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));
}
// reader can only be closed when there
// is no need to access the documents any more.
reader.close();
}
private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
Document doc = new Document();
doc.add(new TextField("title", title, Field.Store.YES));
// use a string field for isbn because we don't want it tokenized
doc.add(new StringField("isbn", isbn, Field.Store.YES));
w.addDocument(doc);
}
}
Thanks!
The problem got solved.
Initially, in the build path, only Lucene-core-6.6.0 was added but lucene-queryparser-6.6.0 is a separate jar file that needs to be added separately.
Hey I would like to have the latest tweets from certain users that I will follow to be displayed on a page of my web app. So I followed the tutorial on the git of horsebird client but I don't know where I have to specify the users I want the messages from.
public class TwitterLatestTweets implements Runnable {
private final static String BUNDLE_BASENAME = "configuration.twitter";
private final static String CONSUMER_KEY = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("consumerKey");
private final static String CONSUMER_SECRET = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("consumerSecret");
private final static String TOKEN = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("token");
private final static String SECRET = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("secret");
private List<String> msgList = new ArrayList<String>();
#Override
public void run() {
/**
* Set up your blocking queues: Be sure to size these properly based on
* expected TPS of your stream
*/
BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(100000);
BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>(1000);
/**
* Declare the host you want to connect to, the endpoint, and
* authentication (basic auth or oauth)
*/
Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint();
Authentication hosebirdAuth = new OAuth1(CONSUMER_KEY, CONSUMER_SECRET,
TOKEN, SECRET);
ClientBuilder builder = new ClientBuilder().hosts(hosebirdHosts)
.authentication(hosebirdAuth).endpoint(hosebirdEndpoint)
.processor(new StringDelimitedProcessor(msgQueue))
.eventMessageQueue(eventQueue);
Client hosebirdClient = builder.build();
hosebirdClient.connect();
while (!hosebirdClient.isDone()) {
try {
String msg = msgQueue.take();
msgList.add(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hosebirdClient.stop();
for (String s : msgList) {
System.out.println(s);
}
}
}
}
Is it Constants.STREAM_HOST ? Could you give me an example with the white house twitter (https://twitter.com/whitehouse) ?
You need to add a list of userIds to your endpoint, like this:
hosebirdEndpoint.followings(userIds);
You've got several examples here, in the same github project you've provided in your question. This one uses the same endpoint as in your post.
In here you can find Twitter's documentation on the endpoint, and the full list of the parameters you can use.
I am new to the social network analysis and twitter API.I wanted to collect tweets on certain topic .So i have written the following code
package com;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
public class TwitterSearchAdvance {
public static void main(String[] vishal) throws TwitterException,
IOException {
// List<Tweet> Data = new ArrayList<Tweet>();
StringBuffer stringbuffer = new StringBuffer();
Twitter twitter = new TwitterFactory().getInstance();
for (int page = 0; page <= 4; page++) {
Query query = new Query("Airtel");
// query.setRpp(100); // 100 results per page
QueryResult qr = twitter.search(query);
List<Status> qrTweets = qr.getTweets();
System.out.println("-------------------" + qrTweets.size());
// break out if there are no more tweets
for (Status t : qrTweets) {
System.out.println(t.getCreatedAt() + ": " + t.getText());
stringbuffer.append(t);
stringbuffer.append("\n");
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
"/home/vishal/FirstDocu.txt"), true));
bw.write(stringbuffer.toString());
bw.newLine();
// bw.write(t.getCreatedAt() + ": " + t.getText());
bw.close();
}
}
}
}
But when i run the following program the following error starts coming
Exception in thread "main" java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/configuration.html for the detail.
at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:200)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1833)
at twitter4j.TwitterImpl.search(TwitterImpl.java:282)
at com.TwitterSearchAdvance.main(TwitterSearchAdvance.java:28)
Where do i need to provide credentials in my program
Thanks
Have a look at the options here http://twitter4j.org/en/configuration.html
There are a number of ways to provide credentials to your program:
Properties File
ConfigurationBuilder class
System properties
Environment Variables
All details and instructions can be found in the link
Good day,
I was recently testing Oauth2.0 Installed application authentication for bigquery through java api.
I used
this command line sample
as a source since i want to make it for the users eaiser to give access (it would be ugly to ask them to copy the code)
If i use SetAccessType(Offline) in GoogleAuthorizationCodeflow it says, that it automatically refreshes the access token for me.
In related I'd like to ask, if i authorize a com.google.api.services.bigquery.Bigquery instance with
com.google.api.services.bigquery.Bigquery.Builder.Builder(HttpTransport transport, JsonFactory jsonFactory, HttpRequestInitializer httpRequestInitializer)
using
credentials that have a refresh token, do i have to reauthorize it or it will update the credentials inside itself?
If it does not give me a valid connection to bigquery after one hour (token expiration time)
then which is the best method to reauthorize the client?
Shall i use credentials.RefreshToken() and then just Build another bigquery instance whith the new access token, or there is a better way?
(I may also want to change the credentials Refreshlistener, but the problem is that if i instantinate the credential with GoogleAuthorizationCodeflow.createAndStoreCredential(response, Clientid) after that i cannot get the Refreshlistener. How can i get it, so i may use that class to automatically reauthorize my Bigquery Client < maybe this is the better way is it?)
Where does the codeflow store the refreshed access token (if it refreshes it automatically)?
If i declared it like this:
new GoogleAuthorizationCodeFlow.Builder(
transport, jsonFactory, clientSecrets, scopes).setAccessType("offline")
.setApprovalPrompt("auto").setCredentialStore(new MemoryCredentialStore()).build();
Will it store my refreshed access token always in the MemoryCredentialStore?
So if i use .getCredentialStore().load(userId, credential) it will load the refreshed access token from the memorystore?
Is there a way to increase or decrease the time while an access token is valid? Since for testing purposes i really want to do so.
p.s: I was also looking into this source code of google-api-java-client
and google-oauth-java-client but i still couldn't find the sollution.
Most importantly I was looking into: class Credential at code:
public void intercept(HttpRequest request) throws IOException {
lock.lock();...
but I couldnt figure it out actually when this method is called and I eventually got lost in the problem.
Looking forward to your answer:
Attila
There's a lot of questions here. You will want to use the GoogleCredential class to gain a new access token from an existing refresh token, that you well need to store (using whatever method you want, such as MemoryCredentialStore).
The access token only lasts for an hour and there is not way to change this.
Here is an example using the installed flow:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
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.services.bigquery.Bigquery;
import com.google.api.services.bigquery.Bigquery.Datasets;
import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.model.DatasetList;
class BigQueryInstalledAuthDemo {
// Change this to your current project ID
private static final String PROJECT_NUMBER = "XXXXXXXXXX";
// Load Client ID/secret from client_secrets.json file.
private static final String CLIENTSECRETS_LOCATION = "client_secrets.json";
static GoogleClientSecrets clientSecrets = loadClientSecrets();
private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
// Objects for handling HTTP transport and JSON formatting of API calls
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static GoogleAuthorizationCodeFlow flow = null;
// BigQuery Client
static Bigquery bigquery;
public static void main(String[] args) throws IOException {
// Attempt to Load existing Refresh Token
String storedRefreshToken = loadRefreshToken();
// Check to see if the an existing refresh token was loaded.
// If so, create a credential and call refreshToken() to get a new
// access token.
if (storedRefreshToken != null) {
// Request a new Access token using the refresh token.
GoogleCredential credential = createCredentialWithRefreshToken(
HTTP_TRANSPORT, JSON_FACTORY, new TokenResponse().setRefreshToken(storedRefreshToken));
credential.refreshToken();
bigquery = buildService(credential);
// If there is no refresh token (or token.properties file), start the OAuth
// authorization flow.
} else {
String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(
clientSecrets,
REDIRECT_URI,
Collections.singleton(BigqueryScopes.BIGQUERY)).setState("").build();
System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl);
System.out.println("... and type the code you received here: ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String authorizationCode = in.readLine();
// Exchange the auth code for an access token and refesh token
Credential credential = exchangeCode(authorizationCode);
// Store the refresh token for future use.
storeRefreshToken(credential.getRefreshToken());
bigquery = buildService(credential);
}
// Make API calls using your client.
listDatasets(bigquery, PROJECT_NUMBER);
}
/**
* Builds an authorized BigQuery API client.
*/
private static Bigquery buildService(Credential credential) {
return new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
}
/**
* Build an authorization flow and store it as a static class attribute.
*/
static GoogleAuthorizationCodeFlow getFlow() {
if (flow == null) {
flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
JSON_FACTORY,
clientSecrets,
Collections.singleton(BigqueryScopes.BIGQUERY))
.setAccessType("offline").setApprovalPrompt("force").build();
}
return flow;
}
/**
* Exchange the authorization code for OAuth 2.0 credentials.
*/
static Credential exchangeCode(String authorizationCode) throws IOException {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response =
flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
return flow.createAndStoreCredential(response, null);
}
/**
* No need to go through OAuth dance, get an access token using the
* existing refresh token.
*/
public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
JsonFactory jsonFactory, TokenResponse tokenResponse) {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientSecrets)
.build()
.setFromTokenResponse(tokenResponse);
}
/**
* Helper to load client ID/Secret from file.
*/
private static GoogleClientSecrets loadClientSecrets() {
try {
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(new JacksonFactory(),
BigQueryInstalledAuthDemo.class.getResourceAsStream(CLIENTSECRETS_LOCATION));
return clientSecrets;
} catch (Exception e) {
System.out.println("Could not load clientsecrets.json");
e.printStackTrace();
}
return clientSecrets;
}
/**
* Helper to store a new refresh token in token.properties file.
*/
private static void storeRefreshToken(String refresh_token) {
Properties properties = new Properties();
properties.setProperty("refreshtoken", refresh_token);
System.out.println(properties.get("refreshtoken"));
try {
properties.store(new FileOutputStream("token.properties"), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Helper to load refresh token from the token.properties file.
*/
private static String loadRefreshToken(){
Properties properties = new Properties();
try {
properties.load(new FileInputStream("token.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return (String) properties.get("refreshtoken");
}
/**
*
* List available Datasets.
*/
public static void listDatasets(Bigquery bigquery, String projectId)
throws IOException {
Datasets.List datasetRequest = bigquery.datasets().list(projectId);
DatasetList datasetList = datasetRequest.execute();
if (datasetList.getDatasets() != null) {
List<DatasetList.Datasets> datasets = datasetList.getDatasets();
System.out.println("Available datasets\n----------------");
for (com.google.api.services.bigquery.model.DatasetList.Datasets dataset : datasets) {
System.out.format("%s\n", dataset.getDatasetReference().getDatasetId());
}
}
}
}
An alternative to authorization via storing and using a refresh token to acquire a new access token in your installed application is to use a server to server service account authorization flow. In this case, your application will need to be able to securely store and use a unique private key. Here is an example of this type of flow using the Google Java API Client:
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 JavaCommandLineServiceAccounts {
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();
private static Bigquery bigquery;
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 = new Bigquery.Builder(TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("BigQuery-Service-Accounts/0.1")
.setHttpRequestInitializer(credential).build();
Datasets.List datasetRequest = bigquery.datasets().list("publicdata");
DatasetList datasetList = datasetRequest.execute();
System.out.format("%s\n", datasetList.toPrettyString());
}
}