Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets getDetails

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets getDetails

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets getDetails.

Prototype

public Details getDetails() 

Source Link

Document

Returns the details for either installed or web applications.

Usage

From source file:com.evolveum.polygon.connector.googleapps.Main.java

License:Open Source License

static Map<String, Object> getConfigurationMap(File clientJson)
        throws IOException, URISyntaxException, Exception {
    System.setProperty("https.protocols", "TLSv1.2");

    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new FileReader(clientJson));

    Credential credential = new AuthorizationCodeInstalledApp(
            new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                    .setAccessType("offline").setApprovalPrompt("force")
                    .setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build(),
            new AbstractPromptReceiver() {
                @Override/*w w w  . j a  va 2 s.co m*/
                public String getRedirectUri() throws IOException {
                    return GoogleOAuthConstants.OOB_REDIRECT_URI;
                }
            }).authorize("user");

    Map<String, Object> configMap = new LinkedHashMap<String, Object>(3);
    configMap.put("clientId", clientSecrets.getDetails().getClientId());
    configMap.put("clientSecret", clientSecrets.getDetails().getClientSecret());
    configMap.put("refreshToken", credential.getRefreshToken());
    return configMap;
}

From source file:com.example.irvinmundo.weirdwords.FusionTablesSample.java

License:Apache License

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(FusionTablesSample.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(/*w w w.ja  v a  2s .  co m*/
                "Enter Client ID and Secret from https://code.google.com/apis/console/?api=fusiontables "
                        + "into fusiontables-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, Collections.singleton(FusiontablesScopes.FUSIONTABLES))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:com.example.samcarey.InsertFusionTables.java

License:Apache License

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(InsertFusionTables.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(/*  www  .  java  2  s .  co  m*/
                "Enter Client ID and Secret from https://code.google.com/apis/console/?api=fusiontables "
                        + "into fusiontables-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, Collections.singleton(FusiontablesScopes.FUSIONTABLES))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:com.gemmystar.api.youtube.YoutubeService.java

License:Open Source License

/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param scopes//from  ww  w  .  j  av a  2 s . c  o  m
 *            list of scopes needed to run youtube upload.
 */
private Credential authorize() throws Exception {

    //if (apiJsonFile.exists() == false) {
    //   throw new FileNotFoundException("file not found. " + apiJsonFile.getAbsolutePath());
    //}

    if (authCodeInstalledApp == null) {

        synchronized (syncObj) {

            if (authCodeInstalledApp == null) {

                // Load client secrets.
                GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                        new InputStreamReader(
                                YoutubeService.class.getResourceAsStream("/client_secret_gemmystar.json")));

                // 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 youtube-cmdline-uploadvideo-sample/src/main/resources/client_secrets.json");
                    System.exit(1);
                }

                // Set up file credential store.
                FileCredentialStore credentialStore = new FileCredentialStore(
                        //new File(System.getProperty("user.home"), ".credentials/youtube-api-uploadvideo.json"),
                        apiJsonFile, JSON_FACTORY);

                // Set up authorization code flow.
                GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
                        JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore).build();

                // Build the local server and bind it to port 9099
                LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(9099).build();

                authCodeInstalledApp = new AuthorizationCodeInstalledApp(flow, localReceiver);
            }
        }

    }

    // Authorize.
    return authCodeInstalledApp.authorize("user");
}

From source file:com.github.drbookings.google.GoogleCalendarSync.java

License:Open Source License

/**
 * Authorizes the installed application to access user's protected data.
 *//*from  ww  w  . j a v a  2  s. c  o m*/
private static Credential authorize() throws Exception {
    // load client secrets
    final GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(GoogleCalendarSync.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        if (logger.isErrorEnabled()) {
            logger.error("Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                    + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
        }
        return null;
    }
    // set up authorization code flow
    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
            JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("557837674207-61uehop5b0u5enflhc7ata9a75sf731e.apps.googleusercontent.com");
}

From source file:com.github.valentin.fedoskin.fb2me.desktop.drive.DriveSample.java

License:Apache License

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            DriveSample.class.getResourceAsStream("/client_secrets.json"));
    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=drive "
                + "into drive-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);/*from w  w  w. ja va2  s . co  m*/
    }
    // set up file credential store
    FileCredentialStore credentialStore = new FileCredentialStore(
            new java.io.File(System.getProperty("user.home"), ".credentials/drive.json"), JSON_FACTORY);
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setCredentialStore(credentialStore)
                    .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:com.google.appengine.tck.teamcity.ReportsFeature.java

License:Open Source License

protected void handleTokens(Map<String, String> params) {
    final GoogleClientSecrets secrets = new GoogleClientSecrets().setInstalled(
            new GoogleClientSecrets.Details().setClientId(params.get(constants.getApplicationClientId()))
                    .setClientSecret(params.get(constants.getApplicationClientSecret())));

    try {//from  ww w  .  j a  v  a  2s .c o  m
        final GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(this.httpTransport,
                this.jsonFactory, secrets.getDetails().getClientId(), secrets.getDetails().getClientSecret(),
                params.get(constants.getApplicationOauthCode()), constants.getRedirectUri()).execute();

        params.put(constants.getApplicationRefreshToken(), tokenResponse.getRefreshToken());
        params.put(constants.getApplicationAccessToken(), tokenResponse.getAccessToken());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.play.developerapi.publisher.samples.AndroidPublisherHelper.java

License:Open Source License

/**
 * Ensure the client secrets file has been filled out.
 *
 * @param clientSecrets the GoogleClientSecrets containing data from the
 *            file/*from  w  ww. ja  v a2s . c  om*/
 */
private static void checkClientSecretsFile(GoogleClientSecrets clientSecrets) {
    if (clientSecrets.getDetails().getClientId().startsWith("[[INSERT")
            || clientSecrets.getDetails().getClientSecret().startsWith("[[INSERT")) {
        log.error("Enter Client ID and Secret from " + "APIs console into resources/client_secrets.json.");
        System.exit(1);
    }
}

From source file:com.google.sample.games.PlayerServlet.java

License:Apache License

/**
 * Exchanges the authcode for an access token credential.  The credential
 * is the associated with the given player.
 *
 * @param authCode - the non-null authcode passed from the client.
 * @param player   - the player object which the given authcode is
 *                 associated with./*from  www  .  j  a v  a 2 s  .  com*/
 * @return the HTTP response code indicating the outcome of the exchange.
 */
private int exchangeAuthCode(String authCode, Player player) {
    try {

        // The client_secret.json file is downloaded from the Google API
        // console.  This is used to identify your web application.  The
        // contents of this file should not be shared.
        //
        // For the sample, this file is expected to be in the root of the
        // sample (at the same level as the top level build.gradle file).
        File secretFile = new File("client_secret.json");

        // If we don't have the file, we can't access any APIs, so return
        // an error.
        if (!secretFile.exists()) {
            log("Secret file : " + secretFile.getAbsolutePath() + "  does not exist!");
            return HttpServletResponse.SC_FORBIDDEN;
        }

        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(),
                new FileReader(secretFile));

        // For the sample server, make sure that the client secret file
        // has been updated with actual values.
        if (clientSecrets.getDetails().getClientId().equals("ReplaceMe")) {
            String message = "client_secret.json is not configured "
                    + "correctly!  Download your app's information and place " + "it in client_secret.json";
            log("ERROR: " + message);
            throw new IllegalStateException(message);
        }

        // small hack here to extract the application id of the game from
        // the client id.
        String applicationId = extractApplicationId(clientSecrets.getDetails().getClientId());

        GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(HTTPTransport,
                JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v4/token",
                clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(),
                authCode, "").execute();

        log("hasRefresh == " + (tokenResponse.getRefreshToken() != null));
        log("Exchanging authCode: " + authCode + " for token");
        Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
                .setJsonFactory(JacksonFactory.getDefaultInstance()).setTransport(HTTPTransport)
                .setTokenServerEncodedUrl("https://www.googleapis" + ".com/oauth2/v4/token")
                .setClientAuthentication(new HttpExecuteInterceptor() {
                    @Override
                    public void intercept(HttpRequest request) throws IOException {

                    }
                }).build().setFromTokenResponse(tokenResponse);

        player.setCredential(credential);

        // Now that we have a credential, we can access the Games API.
        PlayGamesAPI api = new PlayGamesAPI(player, applicationId, HTTPTransport,
                JacksonFactory.getDefaultInstance());

        // Call the verify method, which checks that the access token has
        // access to the Games API, and that the player id used by the
        // client matches the playerId associated with the accessToken.
        boolean ok = api.verifyPlayer();

        // This does not add much that is not available on the client, but
        // is used to demonstrate calling a Games API on the server.
        if (ok) {
            ok = api.updatePlayerInfo();
            if (ok) {
                // persist the player.
                savePlayer(api.getPlayer());
            }
        }

        return ok ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}

From source file:com.jayway.maven.plugins.android.common.AndroidPublisherHelper.java

License:Open Source License

/**
 * Ensure the client secrets file has been filled out.
 *
 * @param clientSecrets the GoogleClientSecrets containing data from the
 *            file/* www  . ja v a 2 s  .c  om*/
 */
private static void checkClientSecretsFile(GoogleClientSecrets clientSecrets) {
    if (clientSecrets.getDetails().getClientId().startsWith("[[INSERT")
            || clientSecrets.getDetails().getClientSecret().startsWith("[[INSERT")) {
        LOG.error("Enter Client ID and Secret from " + "APIs console into resources/client_secrets.json.");
        System.exit(1);
    }
}