Search in sources :

Example 11 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 12 with Credential

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

the class RetryHttpInitializerWrapper method initialize.

@Override
public void initialize(HttpRequest request) {
    // Turn off request logging, this can end up logging OAUTH
    // tokens which should not ever be in a build log
    final boolean loggingEnabled = false;
    request.setLoggingEnabled(loggingEnabled);
    request.setCurlLoggingEnabled(loggingEnabled);
    disableHttpTransportLogging();
    request.setReadTimeout((int) DEFAULT_READ_TIMEOUT_MILLIS);
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
    final Credential credential = credentialSupplier.get();
    request.setInterceptor(credential);
    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {

        @Override
        public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
            // Turn off request logging unless debug mode is enabled
            request.setLoggingEnabled(loggingEnabled);
            request.setCurlLoggingEnabled(loggingEnabled);
            if (credential.handleResponse(request, response, supportsRetry)) {
                // something specific to authentication, and no backoff is desired.
                return true;
            } else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
                // Otherwise, we defer to the judgement of our internal backoff handler.
                LOG.info("Retrying " + request.getUrl().toString());
                return true;
            } else {
                return false;
            }
        }
    });
    request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) Credential(com.google.api.client.auth.oauth2.Credential) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) HttpResponse(com.google.api.client.http.HttpResponse) IOException(java.io.IOException) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff)

Example 13 with Credential

use of com.google.api.client.auth.oauth2.Credential in project YCSB by brianfrankcooper.

the class GoogleDatastoreClient method init.

/**
   * Initialize any state for this DB. Called once per DB instance; there is
   * one DB instance per client thread.
   */
@Override
public void init() throws DBException {
    String debug = getProperties().getProperty("googledatastore.debug", null);
    if (null != debug && "true".equalsIgnoreCase(debug)) {
        logger.setLevel(Level.DEBUG);
    }
    // We need the following 3 essential properties to initialize datastore:
    //
    // - DatasetId,
    // - Path to private key file,
    // - Service account email address.
    String datasetId = getProperties().getProperty("googledatastore.datasetId", null);
    if (datasetId == null) {
        throw new DBException("Required property \"datasetId\" missing.");
    }
    String privateKeyFile = getProperties().getProperty("googledatastore.privateKeyFile", null);
    if (privateKeyFile == null) {
        throw new DBException("Required property \"privateKeyFile\" missing.");
    }
    String serviceAccountEmail = getProperties().getProperty("googledatastore.serviceAccountEmail", null);
    if (serviceAccountEmail == null) {
        throw new DBException("Required property \"serviceAccountEmail\" missing.");
    }
    // Below are properties related to benchmarking.
    String readConsistencyConfig = getProperties().getProperty("googledatastore.readConsistency", null);
    if (readConsistencyConfig != null) {
        try {
            this.readConsistency = ReadConsistency.valueOf(readConsistencyConfig.trim().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new DBException("Invalid read consistency specified: " + readConsistencyConfig + ". Expecting STRONG or EVENTUAL.");
        }
    }
    //
    // Entity Grouping Mode (googledatastore.entitygroupingmode), see
    // documentation in conf/googledatastore.properties.
    //
    String entityGroupingConfig = getProperties().getProperty("googledatastore.entityGroupingMode", null);
    if (entityGroupingConfig != null) {
        try {
            this.entityGroupingMode = EntityGroupingMode.valueOf(entityGroupingConfig.trim().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new DBException("Invalid entity grouping mode specified: " + entityGroupingConfig + ". Expecting ONE_ENTITY_PER_GROUP or " + "MULTI_ENTITY_PER_GROUP.");
        }
    }
    this.rootEntityName = getProperties().getProperty("googledatastore.rootEntityName", "YCSB_ROOT_ENTITY");
    try {
        // Setup the connection to Google Cloud Datastore with the credentials
        // obtained from the configure.
        DatastoreOptions.Builder options = new DatastoreOptions.Builder();
        Credential credential = DatastoreHelper.getServiceAccountCredential(serviceAccountEmail, privateKeyFile);
        logger.info("Using JWT Service Account credential.");
        logger.info("DatasetID: " + datasetId + ", Service Account Email: " + serviceAccountEmail + ", Private Key File Path: " + privateKeyFile);
        datastore = DatastoreFactory.get().create(options.credential(credential).projectId(datasetId).build());
    } catch (GeneralSecurityException exception) {
        throw new DBException("Security error connecting to the datastore: " + exception.getMessage(), exception);
    } catch (IOException exception) {
        throw new DBException("I/O error connecting to the datastore: " + exception.getMessage(), exception);
    }
    logger.info("Datastore client instance created: " + datastore.toString());
}
Also used : DBException(com.yahoo.ycsb.DBException) Credential(com.google.api.client.auth.oauth2.Credential) GeneralSecurityException(java.security.GeneralSecurityException) DatastoreOptions(com.google.datastore.v1.client.DatastoreOptions) IOException(java.io.IOException)

Example 14 with Credential

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

the class UploadVideo method main.

/**
     * Upload the user-selected video to the user's YouTube channel. The code
     * looks for the video in the application's project folder and uses OAuth
     * 2.0 to authorize the API request.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();
        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);
        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();
        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);
        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4"));
        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();
        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    } 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 : VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) Credential(com.google.api.client.auth.oauth2.Credential) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) VideoStatus(com.google.api.services.youtube.model.VideoStatus) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 15 with Credential

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

the class GCalGoogleOAuth method getCredential.

/**
     * <p>
     * Perform OAuth2 authorization with Google server based on provided client_id and client_secret and
     * stores credential in local persistent store.
     * </p>
     *
     * @param newCredential If true try to obtain new credential (user interaction required)
     * @return Authorization credential object.
     */
public static Credential getCredential(boolean newCredential) {
    Credential credential = null;
    try {
        File tokenPath = null;
        String userdata = System.getProperty("smarthome.userdata");
        if (StringUtils.isEmpty(userdata)) {
            tokenPath = new File("etc");
        } else {
            tokenPath = new File(userdata);
        }
        File tokenFile = new File(tokenPath, TOKEN_PATH);
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(tokenFile);
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("gcal_oauth2_token");
        credential = loadCredential("openhab", datastore);
        if (credential == null && newCredential) {
            if (StringUtils.isBlank(client_id) || StringUtils.isBlank(client_secret)) {
                logger.warn("OAuth2 credentials are not provided");
                return null;
            }
            GenericUrl genericUrl = new GenericUrl("https://accounts.google.com/o/oauth2/device/code");
            Map<String, String> mapData = new HashMap<String, String>();
            mapData.put("client_id", client_id);
            mapData.put("scope", CalendarScopes.CALENDAR);
            UrlEncodedContent content = new UrlEncodedContent(mapData);
            HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

                @Override
                public void initialize(HttpRequest request) {
                    request.setParser(new JsonObjectParser(JSON_FACTORY));
                }
            });
            HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl, content);
            Device device = postRequest.execute().parseAs(Device.class);
            // no access token/secret specified so display the authorisation URL in the log
            logger.info("################################################################################################");
            logger.info("# Google-Integration: U S E R   I N T E R A C T I O N   R E Q U I R E D !!");
            logger.info("# 1. Open URL '{}'", device.verification_url);
            logger.info("# 2. Type provided code {} ", device.user_code);
            logger.info("# 3. Grant openHAB access to your Google calendar");
            logger.info("# 4. openHAB will automatically detect the permiossions and complete the authentication process");
            logger.info("# NOTE: You will only have {} mins before openHAB gives up waiting for the access!!!", device.expires_in);
            logger.info("################################################################################################");
            if (logger.isDebugEnabled()) {
                logger.debug("Got access code");
                logger.debug("user code : {}", device.user_code);
                logger.debug("device code : {}", device.device_code);
                logger.debug("expires in: {}", device.expires_in);
                logger.debug("interval : {}", device.interval);
                logger.debug("verification_url : {}", device.verification_url);
            }
            mapData = new HashMap<String, String>();
            mapData.put("client_id", client_id);
            mapData.put("client_secret", client_secret);
            mapData.put("code", device.device_code);
            mapData.put("grant_type", "http://oauth.net/grant_type/device/1.0");
            content = new UrlEncodedContent(mapData);
            postRequest = requestFactory.buildPostRequest(new GenericUrl("https://accounts.google.com/o/oauth2/token"), content);
            DeviceToken deviceToken;
            do {
                deviceToken = postRequest.execute().parseAs(DeviceToken.class);
                if (deviceToken.access_token != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Got access token");
                        logger.debug("device access token: {}", deviceToken.access_token);
                        logger.debug("device token_type: {}", deviceToken.token_type);
                        logger.debug("device refresh_token: {}", deviceToken.refresh_token);
                        logger.debug("device expires_in: {}", deviceToken.expires_in);
                    }
                    break;
                }
                logger.debug("waiting for {} seconds", device.interval);
                Thread.sleep(device.interval * 1000);
            } while (true);
            StoredCredential dataCredential = new StoredCredential();
            dataCredential.setAccessToken(deviceToken.access_token);
            dataCredential.setRefreshToken(deviceToken.refresh_token);
            dataCredential.setExpirationTimeMilliseconds((long) deviceToken.expires_in * 1000);
            datastore.set(TOKEN_STORE_USER_ID, dataCredential);
            credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
        }
    } catch (Exception e) {
        logger.warn("getCredential got exception: {}", e.getMessage());
    }
    return credential;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) HashMap(java.util.HashMap) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) File(java.io.File)

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