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

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

Introduction

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

Prototype

GoogleClientSecrets

Source Link

Usage

From source file:br.usp.poli.lta.cereda.macro.util.GoogleDriveController.java

License:Open Source License

/**
 * Construtor.//www .  j  a v a2s  .c  o  m
 */
private GoogleDriveController() {

    // originalmente, o servio  invlido
    service = null;

    // tenta obter a configurao do Google Drive a partir de um arquivo de
    // propriedades localizado no diretrio de usurio
    File config = new File(
            System.getProperty("user.home").concat(File.separator).concat("me-driveconfig.properties"));

    // se a configurao no existe, lanar exceo
    if (!config.exists()) {
        exception = new TextRetrievalException(
                "No encontrei o arquivo de configurao do Google Drive ('me-driveconfig.properties') no diretrio do usurio.");
    } else {

        // a configurao existe, carrega o mapa de chaves e valores e
        // faz a autenticao no Google Drive
        Properties properties = new Properties();
        try {

            // obtm o arquivo de propriedades e verifica se as chaves so
            // vlidas
            properties.load(new FileReader(config));
            if (properties.containsKey("id") && properties.containsKey("secret")) {

                // cria as chaves de acesso de acordo com as informaes
                // contidas no arquivo de propriedades
                GoogleClientSecrets secrets = new GoogleClientSecrets();
                GoogleClientSecrets.Details details = new GoogleClientSecrets.Details();
                details.setClientId(properties.getProperty("id"));
                details.setClientSecret(properties.getProperty("secret"));
                secrets.setInstalled(details);

                // cria um novo transporte HTTP e a factory do JSON para
                // parsing da API do Google Drive
                HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
                JsonFactory factory = JacksonFactory.getDefaultInstance();

                // define o diretrio do usurio como o local para
                // armazenamento das credenciais de autenticao do
                // Google Drive
                FileDataStoreFactory store = new FileDataStoreFactory(
                        new File(System.getProperty("user.home")));

                // cria um fluxo de autorizao do Google a partir de todas
                // as informaes coletadas anteriormente
                GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, factory,
                        secrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setDataStoreFactory(store)
                                .build();

                // cria uma nova credencial a partir da autorizao
                Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                        .authorize("user");

                // cria efetivamente um novo servio do Google Drive
                // utilizando as informaes coletadas anteriormente
                service = new Drive.Builder(transport, factory, credential)
                        .setApplicationName("macro-expander/1.0").build();
            } else {
                // as chaves so invlidas, configura uma nova exceo
                exception = new TextRetrievalException(
                        "O arquivo de configurao do Google Drive ('me-driveconfig.properties') no possui as chaves 'id' e 'secret'.");
            }
        } catch (IOException ex) {
            // erro de leitura do arquivo de configurao
            exception = new TextRetrievalException(
                    "No consegui ler o arquivo de configurao do Google Drive ('me-driveconfig.properties') no diretrio do usurio.");
        } catch (GeneralSecurityException ex) {
            // erro de conexo
            exception = new TextRetrievalException("No foi possvel estabelecer uma conexo segura.");
        }
    }
}

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   w  w  w . j  a va 2  s .  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.appengine.tck.teamcity.ReportsFeature.java

License:Open Source License

protected void handleBuildFinished(SRunningBuild build, SBuildFeatureDescriptor feature) {
    final Map<String, String> parameters = feature.getParameters();
    final BuildStatistics fullBuildStatistics = build.getFullStatistics();

    // prepare the endpoint authentication
    final GoogleClientSecrets secrets = new GoogleClientSecrets().setInstalled(
            new GoogleClientSecrets.Details().setClientId(parameters.get(constants.getApplicationClientId()))
                    .setClientSecret(parameters.get(constants.getApplicationClientSecret())));

    final Credential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
            .setClientSecrets(secrets).setTransport(httpTransport).build();

    credential.setAccessToken(parameters.get(constants.getApplicationAccessToken()));
    credential.setRefreshToken(parameters.get(constants.getApplicationRefreshToken()));

    // build the test report
    final Reports reports = new Reports.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(constants.getApplicationName()).build();

    final String buildTypeExternalId = build.getBuildTypeExternalId();
    final Integer buildNumber = Integer.valueOf(build.getBuildNumber());

    final TestReport testReport = new TestReport().setBuildTypeId(buildTypeExternalId).setBuildId(buildNumber)
            .setBuildDate(new DateTime(build.getStartDate())).setBuildDuration(build.getDuration())
            .setNumberOfFailedTests(fullBuildStatistics.getFailedTestCount())
            .setNumberOfIgnoredTests(fullBuildStatistics.getIgnoredTestCount())
            .setNumberOfPassedTests(fullBuildStatistics.getPassedTestCount());

    final List<Test> failedTests = new ArrayList<>();
    for (STestRun oneTestRun : fullBuildStatistics.getFailedTests()) {
        final STest failedTest = oneTestRun.getTest();
        final TestName failedTestName = failedTest.getName();

        failedTests.add(new Test().setPackageName(failedTestName.getPackageName())
                .setClassName(failedTestName.getClassName()).setMethodName(failedTestName.getTestMethodName())
                .setError(oneTestRun.getFailureInfo().getStacktraceMessage()));
    }//from ww  w.  j  av a 2 s  . com
    testReport.setFailedTests(failedTests);

    log.info(String.format("Pushing build results for '%s' [%s] ...", buildTypeExternalId, buildNumber));
    // publish results to appspot application
    try {
        reports.tests().insert(testReport).execute();

        log.info(String.format("Build results push for '%s' [%s] is done.", buildTypeExternalId, buildNumber));
    } catch (IOException e) {
        log.warning(
                String.format("Error pushing build results for '%s' [%s]!", buildTypeExternalId, buildNumber));
        throw new RuntimeException(e);
    }
}

From source file:com.google.cloud.hadoop.util.CredentialFactory.java

License:Open Source License

/**
 * Initialized OAuth2 credential for the "installed application" flow; where the credential
 * typically represents an actual end user (instead of a service account), and is stored
 * as a refresh token in a local FileCredentialStore.
 * @param clientId OAuth2 client ID identifying the 'installed app'
 * @param clientSecret OAuth2 client secret
 * @param filePath full path to a ".json" file for storing the credential
 * @param scopes list of well-formed scopes desired in the credential
 * @return credential with desired scopes, possibly obtained from loading {@code filePath}.
 * @throws IOException on IO error//from www.ja  v  a2s  . com
 */
public Credential getCredentialFromFileCredentialStoreForInstalledApp(String clientId, String clientSecret,
        String filePath, List<String> scopes) throws IOException, GeneralSecurityException {
    LOG.debug("getCredentialFromFileCredentialStoreForInstalledApp({}, {}, {}, {})", clientId, clientSecret,
            filePath, scopes);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(clientId), "clientId must not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(clientSecret), "clientSecret must not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(filePath), "filePath must not be null or empty");
    Preconditions.checkArgument(scopes != null, "scopes must not be null or empty");

    // Initialize client secrets.
    GoogleClientSecrets.Details details = new GoogleClientSecrets.Details();
    details.setClientId(clientId);
    details.setClientSecret(clientSecret);
    GoogleClientSecrets clientSecrets = new GoogleClientSecrets();
    clientSecrets.setInstalled(details);

    // Set up file credential store.
    FileCredentialStore credentialStore = new FileCredentialStore(new File(filePath), JSON_FACTORY);

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

    // Authorize access.
    return new AuthorizationCodeInstalledApp(flow, new GooglePromptReceiver()).authorize("user");
}

From source file:com.kenshoo.integrations.plugins.connectors.util.OAuthUtil.java

License:Apache License

public static GoogleClientSecrets createGoogleClientSecrets(OAuthClientData authClientData) {

    GoogleClientSecrets clientSecrets = new GoogleClientSecrets();

    Details web = new Details();
    web.setClientId(authClientData.getClientId());
    web.setClientSecret(authClientData.getSecret());
    web.setRedirectUris(Collections.singletonList(authClientData.getRedirectUri()));
    web.setAuthUri(GOOGLE_AUTH_ENDPOINT);
    web.setTokenUri(GOOGLE_TOKEN_ENDPOINT);
    clientSecrets.setWeb(web);/*from  www.ja  v  a  2 s. co  m*/

    return clientSecrets;
}

From source file:com.NSSWare.MultiSync.GoogleDriveSyncer.java

public static GoogleAuthorizationCodeFlow getFlow(List<String> scopes) throws IOException {
    if (flow == null) {

        GoogleClientSecrets.Details installed = new GoogleClientSecrets.Details();

        installed.setAuthUri(AUTH_URI);
        installed.setClientId(CLIENT_ID);
        installed.setClientSecret(CLIENT_SECRET);
        installed.setRedirectUris(REDIRECT_URIS);
        installed.setTokenUri(TOKEN_URI);

        GoogleClientSecrets clientSecret = new GoogleClientSecrets();

        clientSecret.setInstalled(installed);

        flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecret, scopes)
                .setAccessType("offline").setApprovalPrompt("force").build();
    }/*from   www.ja va2  s. c om*/
    return flow;
}

From source file:net.starschema.clouddb.cmdlineverification.Oauth2Bigquery.java

License:Open Source License

/**
 * Authorizes the installed application to access user's protected data. if
 * possible, gets the credential from xml file at PathForXmlStore
 *
 * @param transport   HTTP transport/*from  w w  w  .  j a v  a 2s  .  co m*/
 * @param jsonFactory JSON factory
 * @param receiver    verification code receiver
 * @param scopes      OAuth 2.0 scopes
 */
public static Credential authorize(HttpTransport transport, JsonFactory jsonFactory,
        VerificationCodeReceiver receiver, List<String> scopes, String clientid, String clientsecret)
        throws Exception {

    BQXMLCredentialStore Store = new BQXMLCredentialStore(Oauth2Bigquery.PathForXmlStore);

    GoogleClientSecrets.Details details = new Details();
    details.setClientId(clientid);
    details.setClientSecret(clientsecret);
    details.set("Factory", CmdlineUtils.getJsonFactory());
    details.setAuthUri("https://accounts.google.com/o/oauth2/auth");
    details.setTokenUri("https://accounts.google.com/o/oauth2/token");
    GoogleClientSecrets secr = new GoogleClientSecrets().setInstalled(details);
    GoogleCredential CredentialForReturn = new GoogleCredential.Builder()
            .setJsonFactory(CmdlineUtils.getJsonFactory()).setTransport(CmdlineUtils.getHttpTransport())
            .setClientSecrets(secr).build();

    if (Store.load(clientid + ":" + clientsecret, CredentialForReturn) == true) {
        return CredentialForReturn;
    }
    try {
        String redirectUri = receiver.getRedirectUri();
        GoogleClientSecrets clientSecrets = Oauth2Bigquery.loadClientSecrets(jsonFactory, clientid,
                clientsecret);
        Oauth2Bigquery.codeflow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, clientSecrets,
                scopes).setAccessType("offline").setApprovalPrompt("auto").setCredentialStore(Store).build();
        Oauth2Bigquery
                .browse(Oauth2Bigquery.codeflow.newAuthorizationUrl().setRedirectUri(redirectUri).build());
        // receive authorization code and exchange it for an access token
        String code = receiver.waitForCode();
        GoogleTokenResponse response = Oauth2Bigquery.codeflow.newTokenRequest(code).setRedirectUri(redirectUri)
                .execute();
        // store credential and return it

        // Also ads a RefreshListener, so the token will be always
        // automatically refreshed.
        return Oauth2Bigquery.codeflow.createAndStoreCredential(response, clientid + ":" + clientsecret);
    } finally {
        receiver.stop();
    }
}

From source file:org.grails.plugin.google.drive.GoogleDrive.java

License:Apache License

static Credential authorize(String clientId, String clientSecret, String credentialsPath,
        String credentialStore, HttpTransport httpTransport, JsonFactory jsonFactory) throws IOException {
    GoogleClientSecrets.Details installedDetails = new GoogleClientSecrets.Details();
    installedDetails.setClientId(clientId);
    installedDetails.setClientSecret(clientSecret);

    GoogleClientSecrets clientSecrets = new GoogleClientSecrets();
    clientSecrets.setInstalled(installedDetails);

    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new java.io.File(credentialsPath));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialStore);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setCredentialDataStore(datastore)
                    .build();//from  www .j  a  va 2  s .com

    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

From source file:tv.bioscope.taskqueue.TaskQueueWorker.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 = new GoogleClientSecrets();
    GoogleClientSecrets.Details installed = new GoogleClientSecrets.Details();
    installed.setClientId(CLIENT_ID);/*w w w  . j  av a2s .  c o  m*/
    installed.setClientSecret(CLIENT_SECRET);
    clientSecrets.setInstalled(installed);

    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=taskqueue into "
                        + "taskqueue-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(TaskqueueScopes.TASKQUEUE))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}