use of com.google.api.client.auth.oauth2.Credential in project openhab1-addons by openhab.
the class GCalGoogleOAuth method newCredential.
private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) {
Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token").setClientAuthentication(new ClientParametersAuthentication(client_id, client_secret)).setRequestInitializer(null).setClock(Clock.SYSTEM);
builder.addRefreshListener(new DataStoreCredentialRefreshListener(userId, credentialDataStore));
return builder.build();
}
use of com.google.api.client.auth.oauth2.Credential in project openhab1-addons by openhab.
the class GCalEventDownloader method downloadEventFeed.
/**
* Connects to Google-Calendar Service and returns the specified Events
*
* @return the corresponding Events or <code>null</code> if an error
* occurs. <i>Note:</i> We do only return events if their startTime lies between
* <code>now</code> and <code>now + 2 * refreshInterval</code> to reduce
* the amount of events to process.
*/
private static Events downloadEventFeed() {
if (StringUtils.isBlank(calendar_name)) {
logger.warn("Login aborted no calendar name defined");
return null;
}
// authorization
CalendarListEntry calendarID = GCalGoogleOAuth.getCalendarId(calendar_name);
if (calendarID == null) {
return null;
}
DateTime start = new DateTime(new Date(), TimeZone.getTimeZone(calendarID.getTimeZone()));
DateTime end = new DateTime(new Date(start.getValue() + (2 * refreshInterval)), TimeZone.getTimeZone(calendarID.getTimeZone()));
logger.debug("Downloading calendar feed for time interval: {} to {} ", start, end);
Events feed = null;
try {
Credential credential = GCalGoogleOAuth.getCredential(false);
// set up global Calendar instance
Calendar client = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("openHAB").build();
Calendar.Events.List l = client.events().list(calendarID.getId()).setSingleEvents(true).setTimeMin(start).setTimeMax(end);
// add the fulltext filter if it has been configured
if (StringUtils.isNotBlank(filter)) {
l = l.setQ(filter);
}
feed = l.execute();
} catch (IOException e1) {
logger.error("Event fetch failed: {}", e1.getMessage());
}
try {
if (feed != null) {
checkIfFullCalendarFeed(feed.getItems());
}
return feed;
} catch (Exception e) {
logger.error("downloading CalendarEventFeed throws exception: {}", e.getMessage());
}
return null;
}
use of com.google.api.client.auth.oauth2.Credential in project OpenRefine by OpenRefine.
the class FusionTableHandler method getFusionTablesService.
public static Fusiontables getFusionTablesService(String token) {
Credential credential = new GoogleCredential().setAccessToken(token);
Fusiontables fusiontables = new Fusiontables.Builder(GDataExtension.HTTP_TRANSPORT, GDataExtension.JSON_FACTORY, credential).setApplicationName(GDataExtension.SERVICE_APP_NAME).build();
;
return fusiontables;
}
use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.
the class Auth method authorize.
/**
* Authorizes the installed application to access user's protected data.
*
* @param scopes list of scopes needed to run youtube upload.
* @param credentialDatastore name of the credential datastore to cache OAuth tokens
*/
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
// Load client secrets.
Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/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");
System.exit(1);
}
// 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");
}
use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.
the class YouTubeAnalyticsReports method main.
/**
* This code authorizes the user, uses the YouTube Data API to retrieve
* information about the user's YouTube channel, and then fetches and
* prints statistics for the user's channel using the YouTube Analytics API.
*
* @param args command line args (not used).
*/
public static void main(String[] args) {
// These scopes are required to access information about the
// authenticated user's YouTube channel as well as Analytics
// data for that channel.
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/youtube.readonly");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "analyticsreports");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("youtube-analytics-api-report-example").build();
// This object is used to make YouTube Analytics API requests.
analytics = new YouTubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("youtube-analytics-api-report-example").build();
// Construct a request to retrieve the current user's channel ID.
YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet");
channelRequest.setMine(true);
channelRequest.setFields("items(id,snippet/title)");
ChannelListResponse channels = channelRequest.execute();
// List channels associated with the user.
List<Channel> listOfChannels = channels.getItems();
// The user's default channel is the first item in the list.
Channel defaultChannel = listOfChannels.get(0);
String channelId = defaultChannel.getId();
PrintStream writer = System.out;
if (channelId == null) {
writer.println("No channel found.");
} else {
writer.println("Default Channel: " + defaultChannel.getSnippet().getTitle() + " ( " + channelId + " )\n");
printData(writer, "Views Over Time.", executeViewsOverTimeQuery(analytics, channelId));
printData(writer, "Top Videos", executeTopVideosQuery(analytics, channelId));
printData(writer, "Demographics", executeDemographicsQuery(analytics, channelId));
}
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
Aggregations