Search in sources :

Example 6 with Credential

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

the class ChannelSectionLocalizations method main.

/**
     * Set and retrieve localized metadata for a channel section.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "localizations");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-localizations-sample").build();
        // Prompt the user to specify the action of the be achieved.
        String actionString = getActionFromUser();
        System.out.println("You chose " + actionString + ".");
        //Map the user input to the enum values.
        Action action = Action.valueOf(actionString.toUpperCase());
        switch(action) {
            case SET:
                setChannelSectionLocalization(getId("channel section"), getDefaultLanguage(), getLanguage(), getMetadata("title"));
                break;
            case GET:
                getChannelSectionLocalization(getId("channel section"), getLanguage());
                break;
            case LIST:
                listChannelSectionLocalizations(getId("channel section"));
                break;
        }
    } 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) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube)

Example 7 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 8 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 9 with Credential

use of com.google.api.client.auth.oauth2.Credential in project HearthStats.net-Uploader by HearthStats.

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://code.google.com/apis/console/?api=youtube" + "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) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) 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)

Example 10 with Credential

use of com.google.api.client.auth.oauth2.Credential in project Ardent by adamint.

the class Ardent method authorize.

public static Credential authorize() throws IOException {
    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new StringReader(clientSecret));
    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    Credential credential;
    if (!testingBot)
        credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver.Builder().setHost("ardentbot.tk").setPort(1337).build()).authorize("703818195441-no5nh31a0rfcogq8k9ggsvsvkq5ai0ih.apps.googleusercontent.com");
    else {
        credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver.Builder().setHost("localhost").setPort(1337).build()).authorize("703818195441-no5nh31a0rfcogq8k9ggsvsvkq5ai0ih.apps.googleusercontent.com");
    }
    //System.out.println(credential.refreshToken());
    return credential;
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) 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)

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