Search in sources :

Example 1 with HttpRequestInitializer

use of com.google.api.client.http.HttpRequestInitializer in project api-samples by youtube.

the class GeolocationSearch method main.

/**
     * Initialize a YouTube object to search for videos on YouTube. Then
     * display the name and thumbnail image of each video in the result set.
     *
     * @param args command line args.
     */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = GeolocationSearch.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);
    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : " + e.getMessage());
        System.exit(1);
    }
    try {
        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {

            @Override
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-geolocationsearch-sample").build();
        // Prompt the user to enter a query term.
        String queryTerm = getInputQuery();
        // Prompt the user to enter location coordinates.
        String location = getInputLocation();
        // Prompt the user to enter a location radius.
        String locationRadius = getInputLocationRadius();
        // Define the API request for retrieving search results.
        YouTube.Search.List search = youtube.search().list("id,snippet");
        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        search.setLocation(location);
        search.setLocationRadius(locationRadius);
        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");
        // As a best practice, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/videoId)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        // Call the API and print results.
        SearchListResponse searchResponse = search.execute();
        List<SearchResult> searchResultList = searchResponse.getItems();
        List<String> videoIds = new ArrayList<String>();
        if (searchResultList != null) {
            // Merge video IDs
            for (SearchResult searchResult : searchResultList) {
                videoIds.add(searchResult.getId().getVideoId());
            }
            Joiner stringJoiner = Joiner.on(',');
            String videoId = stringJoiner.join(videoIds);
            // Call the YouTube Data API's youtube.videos.list method to
            // retrieve the resources that represent the specified videos.
            YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet, recordingDetails").setId(videoId);
            VideoListResponse listResponse = listVideosRequest.execute();
            List<Video> videoList = listResponse.getItems();
            if (videoList != null) {
                prettyPrint(videoList.iterator(), queryTerm);
            }
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) SearchListResponse(com.google.api.services.youtube.model.SearchListResponse) Joiner(com.google.api.client.util.Joiner) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) SearchResult(com.google.api.services.youtube.model.SearchResult) IOException(java.io.IOException) Properties(java.util.Properties) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) VideoListResponse(com.google.api.services.youtube.model.VideoListResponse)

Example 2 with HttpRequestInitializer

use of com.google.api.client.http.HttpRequestInitializer in project beam by apache.

the class InjectorUtils method getClient.

/**
   * Builds a new Pubsub client and returns it.
   */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException {
    checkNotNull(httpTransport);
    checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    if (credential.getClientAuthentication() != null) {
        System.out.println("\n***Warning! You are not using service account credentials to " + "authenticate.\nYou need to use service account credentials for this example," + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + "out of PubSub quota very quickly.\nSee " + "https://developers.google.com/identity/protocols/application-default-credentials.");
        System.exit(1);
    }
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer).setApplicationName(APP_NAME).build();
}
Also used : GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 3 with HttpRequestInitializer

use of com.google.api.client.http.HttpRequestInitializer in project beam by apache.

the class V1TestUtil method getDatastore.

/**
   * Build a new datastore client.
   */
static Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) {
    Credentials credential = pipelineOptions.as(GcpOptions.class).getGcpCredential();
    HttpRequestInitializer initializer;
    if (credential != null) {
        initializer = new ChainingHttpRequestInitializer(new HttpCredentialsAdapter(credential), new RetryHttpRequestInitializer());
    } else {
        initializer = new RetryHttpRequestInitializer();
    }
    DatastoreOptions.Builder builder = new DatastoreOptions.Builder().projectId(projectId).initializer(initializer);
    return DatastoreFactory.get().create(builder.build());
}
Also used : RetryHttpRequestInitializer(org.apache.beam.sdk.util.RetryHttpRequestInitializer) GcpOptions(org.apache.beam.sdk.extensions.gcp.options.GcpOptions) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) DatastoreOptions(com.google.datastore.v1.client.DatastoreOptions) RetryHttpRequestInitializer(org.apache.beam.sdk.util.RetryHttpRequestInitializer) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) ChainingHttpRequestInitializer(com.google.cloud.hadoop.util.ChainingHttpRequestInitializer) Credentials(com.google.auth.Credentials) ChainingHttpRequestInitializer(com.google.cloud.hadoop.util.ChainingHttpRequestInitializer)

Example 4 with HttpRequestInitializer

use of com.google.api.client.http.HttpRequestInitializer in project DataflowJavaSDK-examples by GoogleCloudPlatform.

the class InjectorUtils method getClient.

/**
   * Builds a new Pubsub client and returns it.
   */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException {
    checkNotNull(httpTransport);
    checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    if (credential.getClientAuthentication() != null) {
        System.out.println("\n***Warning! You are not using service account credentials to " + "authenticate.\nYou need to use service account credentials for this example," + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + "out of PubSub quota very quickly.\nSee " + "https://developers.google.com/identity/protocols/application-default-credentials.");
        System.exit(1);
    }
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer).setApplicationName(APP_NAME).build();
}
Also used : GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 5 with HttpRequestInitializer

use of com.google.api.client.http.HttpRequestInitializer 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

HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)11 HttpRequest (com.google.api.client.http.HttpRequest)8 IOException (java.io.IOException)5 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 GenericUrl (com.google.api.client.http.GenericUrl)3 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)3 HttpTransport (com.google.api.client.http.HttpTransport)3 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)3 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)2 HttpResponse (com.google.api.client.http.HttpResponse)2 YouTube (com.google.api.services.youtube.YouTube)2 SearchListResponse (com.google.api.services.youtube.model.SearchListResponse)2 SearchResult (com.google.api.services.youtube.model.SearchResult)2 Credentials (com.google.auth.Credentials)2 HttpCredentialsAdapter (com.google.auth.http.HttpCredentialsAdapter)2 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)2 InputStream (java.io.InputStream)2 Method (java.lang.reflect.Method)2 Properties (java.util.Properties)2 Test (org.junit.Test)2