Search in sources :

Example 1 with Credential

use of com.google.api.client.auth.oauth2.Credential in project che by eclipse.

the class OAuthAuthenticator method getToken.

/**
     * Return authorization token by userId.
     * <p/>
     * WARN!!!. DO not use it directly.
     *
     * @param userId
     *         user identifier
     * @return token value or {@code null}. When user have valid token then it will be returned,
     * when user have expired token and it can be refreshed then refreshed value will be returned,
     * when none token found for user then {@code null} will be returned,
     * when user have expired token and it can't be refreshed then {@code null} will be returned
     * @throws IOException
     *         when error occurs during token loading
     * @see org.eclipse.che.api.auth.oauth.OAuthTokenProvider#getToken(String, String)
     */
public OAuthToken getToken(String userId) throws IOException {
    if (!isConfigured()) {
        throw new IOException("Authenticator is not configured");
    }
    Credential credential = flow.loadCredential(userId);
    if (credential == null) {
        return null;
    }
    final Long expirationTime = credential.getExpiresInSeconds();
    if (expirationTime != null && expirationTime < 0) {
        boolean tokenRefreshed;
        try {
            tokenRefreshed = credential.refreshToken();
        } catch (IOException ioEx) {
            tokenRefreshed = false;
        }
        if (tokenRefreshed) {
            credential = flow.loadCredential(userId);
        } else {
            // and null result should be returned
            try {
                invalidateToken(userId);
            } catch (IOException ignored) {
            }
            return null;
        }
    }
    return newDto(OAuthToken.class).withToken(credential.getAccessToken());
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException)

Example 2 with Credential

use of com.google.api.client.auth.oauth2.Credential in project gradle-play-publisher by ZeroBrain.

the class AndroidPublisherHelper method init.

/**
     * Performs all necessary setup steps for running requests against the API.
     *
     * @param applicationName the name of the application: com.example.app
     * @param authStore
     * @return the {@Link AndroidPublisher} service
     * @throws java.security.GeneralSecurityException
     * @throws java.io.IOException
     */
protected static AndroidPublisher init(String applicationName, File secretFile, File authStore) throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName), "applicationName cannot be null or empty!");
    // Authorization.
    newTrustedTransport();
    Credential credential;
    credential = authorizeWithInstalledApplication(secretFile, authStore);
    // Set up and return API client.
    return new AndroidPublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName).build();
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential)

Example 3 with Credential

use of com.google.api.client.auth.oauth2.Credential in project openhab1-addons by openhab.

the class GCalGoogleOAuth method loadCredential.

private static Credential loadCredential(String userId, DataStore<StoredCredential> credentialDataStore) throws IOException {
    Credential credential = newCredential(userId, credentialDataStore);
    if (credentialDataStore != null) {
        StoredCredential stored = credentialDataStore.get(userId);
        if (stored == null) {
            return null;
        }
        credential.setAccessToken(stored.getAccessToken());
        credential.setRefreshToken(stored.getRefreshToken());
        credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds());
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded credential");
            logger.debug("device access token: {}", stored.getAccessToken());
            logger.debug("device refresh_token: {}", stored.getRefreshToken());
            logger.debug("device expires_in: {}", stored.getExpirationTimeMilliseconds());
        }
    }
    return credential;
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential)

Example 4 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class ListBroadcasts method main.

/**
     * List broadcasts for the user's channel.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for read-only access to the
    // authenticated user's account, but not other types of account access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "listbroadcasts");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-listbroadcasts-sample").build();
        // Create a request to list broadcasts.
        YouTube.LiveBroadcasts.List liveBroadcastRequest = youtube.liveBroadcasts().list("id,snippet");
        // Indicate that the API response should not filter broadcasts
        // based on their status.
        liveBroadcastRequest.setBroadcastStatus("all");
        // Execute the API request and return the list of broadcasts.
        LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
        List<LiveBroadcast> returnedList = returnedListResponse.getItems();
        // Print information from the API response.
        System.out.println("\n================== Returned Broadcasts ==================\n");
        for (LiveBroadcast broadcast : returnedList) {
            System.out.println("  - Id: " + broadcast.getId());
            System.out.println("  - Title: " + broadcast.getSnippet().getTitle());
            System.out.println("  - Description: " + broadcast.getSnippet().getDescription());
            System.out.println("  - Published At: " + broadcast.getSnippet().getPublishedAt());
            System.out.println("  - Scheduled Start Time: " + broadcast.getSnippet().getScheduledStartTime());
            System.out.println("  - Scheduled End Time: " + broadcast.getSnippet().getScheduledEndTime());
            System.out.println("\n-------------------------------------------------------------\n");
        }
    } 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();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) LiveBroadcast(com.google.api.services.youtube.model.LiveBroadcast) LiveBroadcastListResponse(com.google.api.services.youtube.model.LiveBroadcastListResponse) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException)

Example 5 with Credential

use of com.google.api.client.auth.oauth2.Credential in project api-samples by youtube.

the class CreateReportingJob method main.

/**
     * Create a reporting job.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    /*
         * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
         * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
         * use this scope.
         */
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "createreportingjob");
        // This object is used to make YouTube Reporting API requests.
        youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-createreportingjob-sample").build();
        // Prompt the user to specify the name of the job to be created.
        String name = getNameFromUser();
        if (listReportTypes()) {
            createReportingJob(getReportTypeIdFromUser(), name);
        }
    } 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();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) YouTubeReporting(com.google.api.services.youtubereporting.YouTubeReporting) IOException(java.io.IOException)

Aggregations

Credential (com.google.api.client.auth.oauth2.Credential)31 IOException (java.io.IOException)23 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 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 Comment (com.google.api.services.youtube.model.Comment)2 CommentSnippet (com.google.api.services.youtube.model.CommentSnippet)2