Search in sources :

Example 16 with Credential

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();
}
Also used : ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) DataStoreCredentialRefreshListener(com.google.api.client.auth.oauth2.DataStoreCredentialRefreshListener)

Example 17 with Credential

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;
}
Also used : CalendarListEntry(com.google.api.services.calendar.model.CalendarListEntry) Credential(com.google.api.client.auth.oauth2.Credential) Events(com.google.api.services.calendar.model.Events) Calendar(com.google.api.services.calendar.Calendar) TimeRangeCalendar(org.openhab.io.gcal.internal.util.TimeRangeCalendar) IOException(java.io.IOException) DateTime(com.google.api.client.util.DateTime) EventDateTime(com.google.api.services.calendar.model.EventDateTime) Date(java.util.Date) ConfigurationException(org.osgi.service.cm.ConfigurationException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException)

Example 18 with Credential

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;
}
Also used : GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) Credential(com.google.api.client.auth.oauth2.Credential) Fusiontables(com.google.api.services.fusiontables.Fusiontables) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential)

Example 19 with Credential

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");
}
Also used : FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) InputStreamReader(java.io.InputStreamReader) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) AuthorizationCodeInstalledApp(com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp) GoogleClientSecrets(com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets) LocalServerReceiver(com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver) File(java.io.File)

Example 20 with Credential

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();
    }
}
Also used : PrintStream(java.io.PrintStream) Credential(com.google.api.client.auth.oauth2.Credential) Channel(com.google.api.services.youtube.model.Channel) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) YouTubeAnalytics(com.google.api.services.youtubeAnalytics.YouTubeAnalytics) ChannelListResponse(com.google.api.services.youtube.model.ChannelListResponse)

Aggregations

Credential (com.google.api.client.auth.oauth2.Credential)33 IOException (java.io.IOException)24 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)21 YouTube (com.google.api.services.youtube.YouTube)20 StoredCredential (com.google.api.client.auth.oauth2.StoredCredential)5 InputStreamContent (com.google.api.client.http.InputStreamContent)4 AuthorizationCodeInstalledApp (com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp)3 LocalServerReceiver (com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver)3 GoogleAuthorizationCodeFlow (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow)3 GoogleClientSecrets (com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets)3 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3 FileDataStoreFactory (com.google.api.client.util.store.FileDataStoreFactory)3 ArrayList (java.util.ArrayList)3 Calendar (java.util.Calendar)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)2 HttpRequest (com.google.api.client.http.HttpRequest)2 DateTime (com.google.api.client.util.DateTime)2 Channel (com.google.api.services.youtube.model.Channel)2 ChannelListResponse (com.google.api.services.youtube.model.ChannelListResponse)2