Java Examples for com.google.api.client.googleapis.auth.oauth2.GoogleCredential

The following java examples will help you to understand the usage of com.google.api.client.googleapis.auth.oauth2.GoogleCredential. These source code samples are taken from different open source projects.

Example 1
Project: bigquery-samples-python-master  File: BigqueryServiceFactory.java View source code
// [START get_service]
private static Bigquery createAuthorizedClient() throws IOException {
    Collection<String> BIGQUERY_SCOPES = BigqueryScopes.all();
    HttpTransport TRANSPORT = new NetHttpTransport();
    JsonFactory JSON_FACTORY = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(TRANSPORT, JSON_FACTORY);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(BIGQUERY_SCOPES);
    }
    return new Bigquery.Builder(TRANSPORT, JSON_FACTORY, credential).setApplicationName("BigQuery Samples").build();
}
Example 2
Project: Review-Reporter-master  File: AndroidPublisherBuilder.java View source code
public Credential authorizeWithServiceAccount(String serviceAccountEmail, String credentialsPath, HttpTransport httpTransport, JsonFactory jsonFactory) throws Exception {
    return new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountEmail).setServiceAccountScopes(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)).setServiceAccountPrivateKeyFromP12File(new File(credentialsPath)).build();
}
Example 3
Project: cloudbreak-master  File: TagsUtil.java View source code
protected static void checkTagsGcp(ApplicationContext applicationContext, String applicationName, String projectId, String serviceAccountId, String p12File, String availabilityZone, List<String> instanceIdList, Map<String, String> tagsToCheckMap) throws Exception {
    String serviceAccountPrivateKey = ResourceUtil.readBase64EncodedContentFromResource(applicationContext, p12File);
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), new ByteArrayInputStream(Base64.decodeBase64(serviceAccountPrivateKey)), "notasecret", "privatekey", "notasecret");
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    GoogleCredential googleCredential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId).setServiceAccountScopes(Collections.singletonList(ComputeScopes.COMPUTE)).setServiceAccountPrivateKey(privateKey).build();
    Compute compute = new Compute.Builder(httpTransport, jsonFactory, null).setApplicationName(applicationName).setHttpRequestInitializer(googleCredential).build();
    Compute.Instances instances = compute.instances();
    for (String id : instanceIdList) {
        Compute.Instances.Get response = instances.get(projectId, availabilityZone, id);
        com.google.api.services.compute.model.Instance instance = response.execute();
        Tags gcpTags = instance.getTags();
        Map<String, String> extractedTags = new HashMap<>();
        List<String> tagList = gcpTags.getItems();
        for (String i : tagList) {
            String[] tmpTagList = i.split("-");
            if (tmpTagList.length > 1) {
                extractedTags.put(tmpTagList[0], tmpTagList[1]);
            }
        }
        TagsUtil.checkTags(tagsToCheckMap, extractedTags);
        extractedTags.clear();
    }
}
Example 4
Project: Liferay-plugins-master  File: GoogleDirectoryUtil.java View source code
private static Directory _getDirectory() throws Exception {
    if (_directory != null) {
        return _directory;
    }
    GoogleCredential googleCredential = GoogleCredentialUtil.getGoogleCredential();
    Directory.Builder builder = new Directory.Builder(googleCredential.getTransport(), googleCredential.getJsonFactory(), googleCredential);
    _directory = builder.build();
    return _directory;
}
Example 5
Project: PFMeetingAPI-master  File: GoogleServiceImpl.java View source code
public void storeToken(String email, String code) throws Exception {
    try {
        // Actualiza el código de autorización a un acceso y a un token de actualización.
        GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(globalVal.getHttpTransport(), globalVal.getJSON_FACTORY(), globalVal.getClientId(), globalVal.getClientSecret(), code, "postmessage").execute();
        if (tokenResponse.getRefreshToken() != null) {
            Token tok = new Token();
            tok.setEmail(email);
            tok.setToken(tokenResponse.getAccessToken());
            tok.setResfreshToken(tokenResponse.getRefreshToken());
            try {
                bbdd.putToken(tok);
            } catch (Exception e) {
            }
        }
        // Crea una representación credencial de los datos del token.
        GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(globalVal.getJSON_FACTORY()).setTransport(globalVal.getHttpTransport()).setClientSecrets(globalVal.getClientId(), globalVal.getClientSecret()).build().setFromTokenResponse(tokenResponse);
    } catch (TokenResponseException e) {
    } catch (IOException e) {
        throw new Exception(e.getStackTrace().toString());
    }
}
Example 6
Project: typhon-master  File: GooglePlaySample.java View source code
public static void main(String[] args) throws Exception {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), // 生�的P12文件
    new FileInputStream(new File("{P12 key file}")), "notasecret", "privatekey", "notasecret");
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(transport).setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(// e.g.: 626891557797-frclnjv31rn4ss81ch746g9t6pd3mmej@developer.gserviceaccount.com
    "{Email address}").setServiceAccountScopes(AndroidPublisherScopes.all()).setServiceAccountPrivateKey(privateKey).build();
    AndroidPublisher publisher = new AndroidPublisher.Builder(transport, JacksonFactory.getDefaultInstance(), credential).build();
    AndroidPublisher.Purchases.Products products = publisher.purchases().products();
    // �数详细说明: https://developers.google.com/android-publisher/api-ref/purchases/products/get
    AndroidPublisher.Purchases.Products.Get product = products.get("{packageName}", "{productId}", "{token}");
    // 获�订�信�
    // 返回信�说明: https://developers.google.com/android-publisher/api-ref/purchases/products
    // 通过consumptionState, purchaseState�以判断订�的状�
    ProductPurchase purchase = product.execute();
}
Example 7
Project: opencast-master  File: GoogleAPICredentialRequestorTest.java View source code
@Test
public void testClientSecrets() throws IOException, ParseException {
    final String clientId = "clientId";
    final String credentialDataStore = "credentialDataStore";
    final String dataStoreDirectory = "dataStoreDirectory";
    final File clientSecrets = UnitTestUtils.getMockClientSecretsFile(clientId, testFolder.newFile("client-secrets-youtube-v3.json"));
    try {
        final OAuth2CredentialFactory credentialFactory = createMock(OAuth2CredentialFactory.class);
        expect(credentialFactory.getDataStore(credentialDataStore, dataStoreDirectory)).andReturn(createMock(DataStore.class)).once();
        expect(credentialFactory.getGoogleCredential(anyObject(DataStore.class), anyObject(ClientCredentials.class))).andReturn(new GoogleCredential()).once();
        replay(credentialFactory);
        GoogleAPICredentialRequestor.setCredentialFactory(credentialFactory);
        GoogleAPICredentialRequestor.main(new String[] { clientSecrets.getAbsolutePath(), credentialDataStore, dataStoreDirectory });
    } finally {
        if (clientSecrets != null) {
            clientSecrets.delete();
        }
    }
}
Example 8
Project: abelana-master  File: CloudStorage.java View source code
/**
   * Returns a Google Cloud Storage upload url.
   *
   * @param name the filename
   * @return a URL
   */
public static String getUploadUrl(final String name) {
    try {
        GoogleCredential googleCredentials = GoogleCredential.getApplicationDefault().createScoped(Collections.singleton(STORAGE_SCOPE));
        String uri = "https://www.googleapis.com/upload/storage/v1/b/" + URLEncoder.encode(BackendConstants.UPLOAD_BUCKET_NAME, "UTF-8") + "/o?uploadType=resumable&name=" + URLEncoder.encode(name, "UTF-8");
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory(googleCredentials);
        GenericUrl url = new GenericUrl(uri);
        HttpRequest request = requestFactory.buildPostRequest(url, new EmptyContent());
        try {
            HttpResponse response = request.execute();
            if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_OK) {
                return response.getHeaders().getLocation();
            } else {
                LOGGER.severe("Could not get upload URL, HTTP code = " + response.getStatusCode());
            }
        } catch (IOException e) {
            LOGGER.severe("API request to Google Cloud Storage failed: " + e.getMessage());
        }
    } catch (IOException e) {
        LOGGER.severe("Could not get credentials: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOGGER.severe("Could not start the transport layer for upload: " + e.getMessage());
    }
    return null;
}
Example 9
Project: async-datastore-client-master  File: ExampleAsync.java View source code
public static void main(final String... args) throws Exception {
    final DatastoreConfig config = DatastoreConfig.builder().connectTimeout(5000).requestTimeout(1000).maxConnections(5).requestRetry(3).project("my-dataset").namespace("my-namespace").credential(GoogleCredential.getApplicationDefault()).build();
    final Datastore datastore = Datastore.create(config);
    // Add a two entities asynchronously
    final ListenableFuture<MutationResult> addFirst = addData(datastore);
    final ListenableFuture<MutationResult> addSecond = addDataInTransaction(datastore);
    final ListenableFuture<List<Object>> addBoth = Futures.allAsList(addFirst, addSecond);
    // Query the entities we've just inserted
    final ListenableFuture<QueryResult> query = Futures.transform(addBoth, (List<Object> result) -> {
        return queryData(datastore);
    });
    // Print the query results before clean up
    final ListenableFuture<MutationResult> delete = Futures.transform(query, (QueryResult result) -> {
        for (final Entity entity : result) {
            System.out.println("Employee name: " + entity.getString("fullname"));
            System.out.println("Employee age: " + entity.getInteger("age"));
        }
        return deleteData(datastore);
    });
    Futures.addCallback(delete, new FutureCallback<MutationResult>() {

        @Override
        public void onSuccess(final MutationResult result) {
            System.out.println("All complete.");
        }

        @Override
        public void onFailure(final Throwable throwable) {
            System.err.println("Storage exception: " + Throwables.getRootCause(throwable).getMessage());
        }
    });
}
Example 10
Project: aw-reporting-master  File: InstalledOAuth2Authenticator.java View source code
/*
   * Get new OAuth2 Credential from the user from the command line OAuth2 dance.
   */
private Credential getNewOAuth2Credential() throws OAuthException {
    GoogleAuthorizationCodeFlow authorizationFlow = getAuthorizationFlow();
    String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
    System.out.println("\n**ACTION REQUIRED** Paste this url in your browser" + " and authenticate using your **AdWords Admin Account**: \n\n" + authorizeUrl + '\n');
    // Wait for the authorization code.
    System.out.println("Type the code you received on the web page here: ");
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
        String authorizationCode = reader.readLine();
        // Authorize the OAuth2 token.
        GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode);
        tokenRequest.setRedirectUri(CALLBACK_URL);
        GoogleTokenResponse tokenResponse = tokenRequest.execute();
        //  Create the credential.
        Credential credential = new GoogleCredential.Builder().setClientSecrets(clientId, clientSecret).setJsonFactory(new JacksonFactory()).setTransport(new NetHttpTransport()).build().setFromTokenResponse(tokenResponse);
        return credential;
    } catch (IOException e) {
        throw new OAuthException("An error occured obtaining the OAuth2Credential", e);
    }
}
Example 11
Project: java-docs-samples-master  File: Snippets.java View source code
/**
   * Creates an authorized CloudKMS client service using Application Default Credentials.
   *
   * @return an authorized CloudKMS client
   * @throws IOException if there's an error getting the default credentials.
   */
public static CloudKMS createAuthorizedClient() throws IOException {
    // Create the credential
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    // Authorize the client using Application Default Credentials
    // @see https://g.co/dv/identity/protocols/application-default-credentials
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    // Check for this case, and inject the scope if required.
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(CloudKMSScopes.all());
    }
    return new CloudKMS.Builder(transport, jsonFactory, credential).setApplicationName("CloudKMS snippets").build();
}
Example 12
Project: ManalithBot-master  File: CalendarPlugin.java View source code
@BotCommand({ "다��정" })
public String getCalendar() throws Exception {
    GoogleCredential credentials = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport()).setJsonFactory(jsonFactory).setServiceAccountId(accountId).setServiceAccountScopes(Arrays.asList(CalendarScopes.CALENDAR_READONLY)).setServiceAccountPrivateKeyFromP12File(new File(p12path)).build();
    Calendar client = new Calendar.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credentials).setApplicationName(appName).build();
    List<Event> events = client.events().list(calendarId).setMaxResults(1).setTimeMin(new DateTime(new Date())).setOrderBy("startTime").setSingleEvents(true).execute().getItems();
    if (!events.isEmpty()) {
        Event event = events.get(0);
        return String.format("%s : %s %s - %s", FORMAT.format(new Date(event.getStart().getDateTime().getValue())), StringUtils.defaultIfBlank(event.getSummary(), ""), StringUtils.defaultIfBlank(event.getDescription(), ""), event.getCreator().getDisplayName()).replace("\n", "");
    }
    return "표시할 내용� 없습니다.";
}
Example 13
Project: myLazyClock-master  File: CalendarGoogleStrategy.java View source code
/**
     * Find the first event before 24h before endDay in google calendar in params
     * @param params Need some params : <br/>
     *  - <strong> tokenRequest </strong> content the google refreshToken of user <br/>
     *  - <strong> gCalId </strong> content the id of calendar <br/>
     *  - <strong> apiId </strong> and <strong> apiSecret </strong> generate by maven in services.ConstantAPI <br/>
     *
     * @param beginDate Lower bound date in which search event
     * @param endDate Upper bound date in which search event
     *
     * @return CalendarEvent the first event find
     * @throws org.myLazyClock.calendarApi.exception.EventNotFoundException if not event found in specific day
     */
@Override
public CalendarEvent getFirstEvent(Map<String, String> params, java.util.Calendar beginDate, java.util.Calendar endDate) throws EventNotFoundException, ForbiddenCalendarException {
    if (beginDate == null || endDate == null || params == null || params.get("tokenRequest") == null || params.get("tokenRequest").equals("") || params.get("gCalId") == null || params.get("gCalId").equals("")) {
        throw new EventNotFoundException();
    }
    DateTime startTime = new DateTime(beginDate.getTime());
    DateTime endTime = new DateTime(endDate.getTime());
    CalendarEvent returnEvent = null;
    try {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setClientSecrets(params.get("apiId"), params.get("apiSecret")).build().setRefreshToken(params.get("tokenRequest"));
        Calendar service = new Calendar.Builder(httpTransport, jsonFactory, null).setApplicationName("myLazyClock").setHttpRequestInitializer(credential).build();
        Events events = service.events().list(params.get("gCalId")).setTimeMin(startTime).setTimeMax(endTime).setOrderBy("startTime").setSingleEvents(true).execute();
        int i = 0;
        while (returnEvent == null) {
            Event event;
            try {
                event = events.getItems().get(i);
                i++;
            } catch (IndexOutOfBoundsException e) {
                throw new EventNotFoundException();
            }
            try {
                CalendarEvent calendarEvent = new CalendarEvent();
                calendarEvent.setName(event.getSummary());
                calendarEvent.setBeginDate(new Date(event.getStart().getDateTime().getValue()));
                calendarEvent.setEndDate(new Date(event.getEnd().getDateTime().getValue()));
                calendarEvent.setAddress(event.getLocation());
                returnEvent = calendarEvent;
            } catch (NullPointerException e) {
                returnEvent = null;
            }
        }
    } catch (GeneralSecurityException e) {
        throw new ForbiddenCalendarException("Accés interdit au calendrier de Google");
    } catch (IOException e) {
        throw new EventNotFoundException(e);
    }
    return returnEvent;
}
Example 14
Project: onetouch_goog_drive-master  File: GoogDriveOpen.java View source code
private void processFile() {
    if (token == null) {
        startActivityForResult(new Intent(this, GetAccountActivity.class), Constant.REQ_CODE_ACNT);
        return;
    }
    final HttpTransport transport = AndroidHttp.newCompatibleTransport();
    final JsonFactory jsonFactory = new AndroidJsonFactory();
    GoogleCredential credential = new GoogleCredential.Builder().setClientSecrets(Constant.CLIENT_API_ID, Constant.CLIENT_API_SECRET).build();
    credential.setAccessToken(token.accessToken);
    final Drive drive = new Drive.Builder(transport, jsonFactory, credential).setApplicationName("OneTouchGDrive").setJsonHttpRequestInitializer(new GoogleKeyInitializer(Constant.SIMPLE_API_KEY)).build();
    new RoboAsyncTask<String>(this, handler) {

        @Override
        public String call() throws Exception {
            try {
                PermissionList list = drive.permissions().list(mFileId).execute();
                for (Object v : list.values()) {
                    Log.d(Constant.LOG_TAG, "perm item:" + v);
                }
                Permission anyoneReadPerm = new Permission();
                //anyoneReadPerm.setValue("anyone");
                anyoneReadPerm.setType("anyone");
                anyoneReadPerm.setRole("reader");
                drive.permissions().insert(mFileId, anyoneReadPerm).execute();
                File file = drive.files().get(mFileId).execute();
                Log.d(Constant.LOG_TAG, "title:" + file.getTitle());
                Log.d(Constant.LOG_TAG, "download url:" + file.getDownloadUrl());
                Log.d(Constant.LOG_TAG, "kind:" + file.getKind());
                Log.d(Constant.LOG_TAG, "web content link:" + file.getWebContentLink());
                return file.getWebContentLink();
            } catch (IOException e) {
                Log.w(Constant.LOG_TAG, "failed to get file", e);
                return null;
            }
        }

        @Override
        protected void onSuccess(String shareUrl) throws Exception {
            Util.showToast("url:" + shareUrl);
        }

        @Override
        protected void onThrowable(Throwable t) throws RuntimeException {
            Util.showToast("failed:" + t);
        }
    }.execute();
}
Example 15
Project: play-publisher-bootstrapper-master  File: AndroidPublisherHelper.java View source code
/**
     * Global instance of the {@link com.google.api.client.util.store.DataStoreFactory}. The best practice is to
     * make it a single globally shared instance across your application.
     */
private static Credential authorizeWithServiceAccount(String serviceAccountEmail, File pk12File) throws GeneralSecurityException, IOException {
    log.info(String.format("Authorizing using Service Account: %s", serviceAccountEmail));
    // Build service account credential.
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setServiceAccountId(serviceAccountEmail).setServiceAccountScopes(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)).setServiceAccountPrivateKeyFromP12File(pk12File).build();
    return credential;
}
Example 16
Project: account-provisioning-for-google-apps-master  File: GoogleClient.java View source code
/**
   * Retrieves the service account credentials.
   *
   * @param serviceAccountEmail Service email from the Google Developer Console
   *        project.
   * @param keyPath Where the p12 file is stored.
   * @return GoogleCredential object with the active section.
   * @throws GeneralSecurityException
   * @throws IOException
   */
protected GoogleCredential getCredentialForServiceAccount(String serviceAccountEmail, String keyPath) throws GeneralSecurityException, IOException {
    return new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountEmail).setServiceAccountScopes(Collections.singleton(DirectoryScopes.ADMIN_DIRECTORY_USER)).setServiceAccountPrivateKeyFromP12File(new File(keyPath)).setServiceAccountUser(authUser).build();
}
Example 17
Project: api-client-java-master  File: AppIdentityCredentialTest.java View source code
public void testAppEngineCredentialWrapper() throws IOException {
    final String expectedAccessToken = "ExpectedAccessToken";
    final Collection<String> emptyScopes = Collections.emptyList();
    HttpTransport transport = new MockHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    MockAppIdentityService appIdentity = new MockAppIdentityService();
    appIdentity.setAccessTokenText(expectedAccessToken);
    AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(emptyScopes);
    builder.setAppIdentityService(appIdentity);
    AppIdentityCredential appCredential = builder.build();
    GoogleCredential wrapper = new AppIdentityCredential.AppEngineCredentialWrapper(appCredential, transport, jsonFactory);
    HttpRequest request = transport.createRequestFactory().buildRequest("get", null, null);
    assertTrue(wrapper.createScopedRequired());
    try {
        wrapper.intercept(request);
        fail("Should not be able to use credential without scopes.");
    } catch (Exception expected) {
    }
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 1);
    GoogleCredential scopedWrapper = wrapper.createScoped(SCOPES);
    assertNotSame(wrapper, scopedWrapper);
    scopedWrapper.intercept(request);
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 2);
    HttpHeaders headers = request.getHeaders();
    String authHeader = headers.getAuthorization();
    assertTrue(authHeader.contains(expectedAccessToken));
}
Example 18
Project: async-google-pubsub-client-master  File: PublisherBenchmark.java View source code
public static void main(final String... args) throws IOException {
    final String project = Util.defaultProject();
    GoogleCredential credential;
    // Use credentials from file if available
    try {
        credential = GoogleCredential.fromStream(new FileInputStream("credentials.json")).createScoped(PubsubScopes.all());
    } catch (IOException e) {
        credential = GoogleCredential.getApplicationDefault().createScoped(PubsubScopes.all());
    }
    final Pubsub pubsub = Pubsub.builder().credential(credential).compressionLevel(Deflater.BEST_SPEED).enabledCipherSuites(nonGcmCiphers()).build();
    final Publisher publisher = Publisher.builder().pubsub(pubsub).concurrency(128).project(project).build();
    LoggingConfigurator.configureDefaults("benchmark", WARN);
    final String topicPrefix = TEST_NAME_PREFIX + ThreadLocalRandom.current().nextInt();
    final List<String> topics = IntStream.range(0, 100).mapToObj( i -> topicPrefix + "-" + i).collect(toList());
    topics.stream().map( topic -> pubsub.createTopic(project, topic)).collect(toList()).forEach(Futures::getUnchecked);
    final List<Message> messages = IntStream.range(0, 1000).mapToObj( i -> {
        final StringBuilder s = new StringBuilder();
        while (s.length() < MESSAGE_SIZE) {
            s.append(ThreadLocalRandom.current().nextInt());
        }
        return Message.ofEncoded(s.toString());
    }).collect(toList());
    final ProgressMeter meter = new ProgressMeter();
    final ProgressMeter.Metric requests = meter.group("operations").metric("publishes", "messages");
    for (int i = 0; i < 100000; i++) {
        benchSend(publisher, messages, topics, requests);
    }
}
Example 19
Project: beam-master  File: InjectorUtils.java View source code
/**
   * 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();
}
Example 20
Project: camel-master  File: GooglePubsubConnectionFactory.java View source code
private Pubsub buildClient(HttpTransport httpTransport) throws Exception {
    GoogleCredential credential = null;
    if (!Strings.isNullOrEmpty(serviceAccount) && !Strings.isNullOrEmpty(serviceAccountKey)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Service Account and Key have been set explicitly. Initialising PubSub using Service Account " + serviceAccount);
        }
        credential = createFromAccountKeyPair(httpTransport);
    }
    if (credential == null && !Strings.isNullOrEmpty(credentialsFileLocation)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Key File Name has been set explicitly. Initialising PubSub using Key File " + credentialsFileLocation);
        }
        credential = createFromFile();
    }
    if (credential == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("No explicit Service Account or Key File Name have been provided. Initialising PubSub using defaults ");
        }
        credential = createDefault();
    }
    Pubsub.Builder builder = new Pubsub.Builder(httpTransport, jsonFactory, credential).setApplicationName("camel-google-pubsub");
    // Local emulator, SOCKS proxy, etc.
    if (serviceURL != null) {
        builder.setRootUrl(serviceURL);
    }
    return builder.build();
}
Example 21
Project: cloud-pubsub-samples-java-master  File: StockInjector.java View source code
/**
   * Creates a Cloud Pub/Sub client.
   */
public Pubsub createPubsubClient() throws IOException, GeneralSecurityException {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(transport, JSON_FACTORY, initializer).build();
}
Example 22
Project: DataflowJavaSDK-examples-master  File: InjectorUtils.java View source code
/**
   * 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();
}
Example 23
Project: director-google-plugin-master  File: GoogleCredentials.java View source code
private Compute buildCompute() {
    try {
        JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential;
        if (jsonKey != null) {
            credential = GoogleCredential.fromStream(new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY).createScoped(Collections.singleton(ComputeScopes.COMPUTE));
        } else {
            Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE);
            credential = GoogleCredential.getApplicationDefault(httpTransport, JSON_FACTORY).createScoped(COMPUTE_SCOPES);
        }
        return new Compute.Builder(httpTransport, JSON_FACTORY, null).setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)).setHttpRequestInitializer(credential).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 24
Project: dlibrary-master  File: GoogleAccount.java View source code
private Credential authorize() throws Exception {
    Set<String> scopes = new HashSet<String>();
    scopes.add(AnalyticsScopes.ANALYTICS);
    scopes.add(AnalyticsScopes.ANALYTICS_EDIT);
    scopes.add(AnalyticsScopes.ANALYTICS_MANAGE_USERS);
    scopes.add(AnalyticsScopes.ANALYTICS_PROVISION);
    scopes.add(AnalyticsScopes.ANALYTICS_READONLY);
    credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(emailAddress).setServiceAccountScopes(scopes).setServiceAccountPrivateKeyFromP12File(new File(certificateLocation)).build();
    return credential;
}
Example 25
Project: DSpace-master  File: GoogleAccount.java View source code
private Credential authorize() throws Exception {
    Set<String> scopes = new HashSet<String>();
    scopes.add(AnalyticsScopes.ANALYTICS);
    scopes.add(AnalyticsScopes.ANALYTICS_EDIT);
    scopes.add(AnalyticsScopes.ANALYTICS_MANAGE_USERS);
    scopes.add(AnalyticsScopes.ANALYTICS_PROVISION);
    scopes.add(AnalyticsScopes.ANALYTICS_READONLY);
    credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(emailAddress).setServiceAccountScopes(scopes).setServiceAccountPrivateKeyFromP12File(new File(certificateLocation)).build();
    return credential;
}
Example 26
Project: gdfs-master  File: Util.java View source code
public static Drive newGDrive(String accessToken) {
    //		final HttpTransport transport = AndroidHttp.newCompatibleTransport();
    final HttpTransport transport = new NetHttpTransport();
    final JsonFactory jsonFactory;
    if (hasHoneycomb()) {
        jsonFactory = new AndroidJsonFactory();
    } else {
        jsonFactory = new JacksonFactory();
    }
    String clientApiId = GDFSApp.ctx.getResources().getString(R.string.client_api_id);
    String clientApiSecret = GDFSApp.ctx.getResources().getString(R.string.client_api_secret);
    String simpleApiKey = GDFSApp.ctx.getResources().getString(R.string.simple_api_key);
    GoogleCredential credential = new GoogleCredential.Builder().setClientSecrets(clientApiId, clientApiSecret).build();
    credential.setAccessToken(accessToken);
    return new Drive.Builder(transport, jsonFactory, credential).setApplicationName(GDFSApp.ctx.getResources().getString(R.string.app_name)).setJsonHttpRequestInitializer(new GoogleKeyInitializer(simpleApiKey)).build();
}
Example 27
Project: google-api-java-client-master  File: AppIdentityCredentialTest.java View source code
public void testAppEngineCredentialWrapper() throws IOException {
    final String expectedAccessToken = "ExpectedAccessToken";
    final Collection<String> emptyScopes = Collections.emptyList();
    HttpTransport transport = new MockHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    MockAppIdentityService appIdentity = new MockAppIdentityService();
    appIdentity.setAccessTokenText(expectedAccessToken);
    AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(emptyScopes);
    builder.setAppIdentityService(appIdentity);
    AppIdentityCredential appCredential = builder.build();
    GoogleCredential wrapper = new AppIdentityCredential.AppEngineCredentialWrapper(appCredential, transport, jsonFactory);
    HttpRequest request = transport.createRequestFactory().buildRequest("get", null, null);
    assertTrue(wrapper.createScopedRequired());
    try {
        wrapper.intercept(request);
        fail("Should not be able to use credential without scopes.");
    } catch (Exception expected) {
    }
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 1);
    GoogleCredential scopedWrapper = wrapper.createScoped(SCOPES);
    assertNotSame(wrapper, scopedWrapper);
    scopedWrapper.intercept(request);
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 2);
    HttpHeaders headers = request.getHeaders();
    String authHeader = headers.getAuthorization();
    assertTrue(authHeader.contains(expectedAccessToken));
}
Example 28
Project: google-cloud-datastore-master  File: DatastoreHelper.java View source code
private static Credential getCredentialFromEnv() throws GeneralSecurityException, IOException {
    if (System.getenv(LOCAL_HOST_ENV_VAR) != null) {
        logger.log(Level.INFO, "{0} environment variable was set. Not using credentials.", new Object[] { LOCAL_HOST_ENV_VAR });
        return null;
    }
    String serviceAccount = System.getenv(SERVICE_ACCOUNT_ENV_VAR);
    String privateKeyFile = System.getenv(PRIVATE_KEY_FILE_ENV_VAR);
    if (serviceAccount != null && privateKeyFile != null) {
        logger.log(Level.INFO, "{0} and {1} environment variables were set. " + "Using service account credential.", new Object[] { SERVICE_ACCOUNT_ENV_VAR, PRIVATE_KEY_FILE_ENV_VAR });
        return getServiceAccountCredential(serviceAccount, privateKeyFile);
    }
    return GoogleCredential.getApplicationDefault().createScoped(DatastoreOptions.SCOPES);
}
Example 29
Project: googleads-adxbuyer-examples-master  File: BuyerServiceHelper.java View source code
/**
   * Creates a new API service
   * @return the new, authenticated and authorized service
   * @throws GeneralSecurityException
   * @throws IOException
   */
protected static AdExchangeBuyer getNewService() throws GeneralSecurityException, IOException {
    /** Global instance of the HTTP transport. */
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    /** Global instance of the JSON factory. */
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    Credential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(AdExchangeBuyerScopes.all()).setServiceAccountPrivateKeyFromP12File(P12_FILE).build();
    return new AdExchangeBuyer.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME).build();
}
Example 30
Project: googleads-java-lib-master  File: AdHocReportDownloadHelperTest.java View source code
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    Enum<?> downloadFormat = TestDownloadFormat.CSV;
    Mockito.<Enum<?>>when(reportRequest.getDownloadFormat()).thenReturn(downloadFormat);
    credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
    credential.setAccessToken("TEST_ACCESS_TOKEN");
    AdWordsSession session = new AdWordsSession.Builder().withUserAgent("TEST_APP").withOAuth2Credential(credential).withEndpoint(testHttpServer.getServerUrl()).withDeveloperToken("TEST_DEVELOPER_TOKEN").withClientCustomerId("TEST_CLIENT_CUSTOMER_ID").build();
    helper = new GenericAdWordsServices().getBootstrapper().getInstanceOf(session, AdHocReportDownloadHelper.class);
    exceptionBuilder = new DetailedReportDownloadResponseException.Builder() {

        @Override
        public DetailedReportDownloadResponseException build(int httpStatus, String errorText) {
            return new DetailedReportDownloadResponseException(httpStatus, errorText);
        }
    };
}
Example 31
Project: ishacrmserver-master  File: GSpreadSheetApi.java View source code
public APIResponse readSpreadsheetContents(@Named("spreadSheetKey") String gsKey, HttpServletRequest req, User user) {
    try {
        SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
        URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/1ce55J6l5IjXCOVfFklL9i6c0kYOHu-p9rabM9YdpBTg");
        String authString = req.getHeader("Authorization");
        String strBearer = "Bearer ";
        String accessToken = authString.substring(strBearer.length());
        System.out.println(accessToken);
        GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
        service.setOAuth2Credentials(credential);
        SpreadsheetEntry spreadsheet = service.getEntry(metafeedUrl, SpreadsheetEntry.class);
        URL listFeedUrl = ((WorksheetEntry) spreadsheet.getWorksheets().get(0)).getListFeedUrl();
        // Print entries
        ListFeed feed = (ListFeed) service.getFeed(listFeedUrl, ListFeed.class);
        for (ListEntry entry : feed.getEntries()) {
            System.out.println("new row");
            for (String tag : entry.getCustomElements().getTags()) {
                System.out.println("     " + tag + ": " + entry.getCustomElements().getValue(tag));
            }
        }
        return new APIResponse().status(Status.SUCCESS);
    } catch (Exception ex) {
        return APIUtils.toAPIResponse(ex, true, new RequestInfo().req(req));
    }
}
Example 32
Project: jdrivesync-master  File: CredentialStore.java View source code
public Optional<Credential> load() {
    Properties properties = new Properties();
    try {
        File file = getAuthenticationFile(options);
        if (!file.exists() || !file.canRead()) {
            LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials.");
            return Optional.empty();
        }
        properties.load(new FileReader(file));
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory).setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
        credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN));
        credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN));
        return Optional.of(credential);
    } catch (IOException e) {
        throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e);
    }
}
Example 33
Project: jelectrum-master  File: JelectrumDBCloudData.java View source code
private DatastoreOptions.Builder getDatastoreOptions() throws java.security.GeneralSecurityException, java.io.IOException {
    DatastoreOptions.Builder options = new DatastoreOptions.Builder();
    GoogleCredential cred = openCredential();
    options.dataset(conf.get("google_project"));
    //options.host("https://www.googleapis.com/datastore/v1/datasets/hhtt-nodes-184");
    options.credential(cred);
    return options;
}
Example 34
Project: nomulus-master  File: SheepCounterExample.java View source code
private static Monitoring createAuthorizedMonitoringClient() throws IOException {
    // Grab the Application Default Credentials from the environment.
    // Generate these with 'gcloud beta auth application-default login'
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(MonitoringScopes.all());
    // Create and return the CloudMonitoring service object
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    return new Monitoring.Builder(httpTransport, jsonFactory, credential).setApplicationName("Monitoring Sample").build();
}
Example 35
Project: simplejavayoutubeuploader-master  File: YouTubeProvider.java View source code
public Credential getCredential(final Account account) {
    if (!credentials.containsKey(account)) {
        final Credential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory).setTransport(httpTransport).setClientSecrets(GDATAConfig.CLIENT_ID, GDATAConfig.CLIENT_SECRET).addRefreshListener(new CredentialRefreshListener() {

            @Override
            public void onTokenResponse(final Credential credential, final TokenResponse tokenResponse) throws IOException {
                LOGGER.info("Token refreshed");
            }

            @Override
            public void onTokenErrorResponse(final Credential credential, final TokenErrorResponse tokenErrorResponse) throws IOException {
                LOGGER.error("Token refresh error {}", tokenErrorResponse.toPrettyString());
            }
        }).build();
        credential.setRefreshToken(account.getRefreshToken());
        credentials.put(account, credential);
    }
    return credentials.get(account);
}
Example 36
Project: thundr-bigquery-master  File: BigqueryInjectionConfiguration.java View source code
/**
	 * Build a {@link GoogleCredential} for accessing Google APIs (eg: BigQuery).
	 */
private GoogleCredential buildBigQueryGoogleCredential(UpdatableInjectionContext injectionContext) {
    String certificate = injectionContext.get(String.class, "googleApiCertificate");
    String accountId = injectionContext.get(String.class, "googleApiAccountId");
    String clientId = injectionContext.get(String.class, "googleApiClientId");
    String clientSecret = injectionContext.get(String.class, "googleApiClientSecret");
    try {
        File privateKey = new File(getClass().getResource(certificate).toURI());
        GoogleCredential.Builder builder = new GoogleCredential.Builder();
        builder.setTransport(new NetHttpTransport());
        builder.setServiceAccountId(accountId);
        builder.setJsonFactory(new GsonFactory());
        builder.setClientSecrets(clientId, clientSecret);
        builder.setServiceAccountScopes("https://www.googleapis.com/auth/bigquery");
        builder.setServiceAccountPrivateKeyFromP12File(privateKey);
        return builder.build();
    } catch (Exception e) {
        throw new InjectionException(e, "Error creating BigQuery Google credential: %s", e.getMessage());
    }
}
Example 37
Project: vtechworks-master  File: GoogleAccount.java View source code
private Credential authorize() throws Exception {
    Set<String> scopes = new HashSet<String>();
    scopes.add(AnalyticsScopes.ANALYTICS);
    scopes.add(AnalyticsScopes.ANALYTICS_EDIT);
    scopes.add(AnalyticsScopes.ANALYTICS_MANAGE_USERS);
    scopes.add(AnalyticsScopes.ANALYTICS_PROVISION);
    scopes.add(AnalyticsScopes.ANALYTICS_READONLY);
    credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(emailAddress).setServiceAccountScopes(scopes).setServiceAccountPrivateKeyFromP12File(new File(certificateLocation)).build();
    return credential;
}
Example 38
Project: 1ed-master  File: CloudStorageUtil.java View source code
// Autoriza o acesso com "Server-Side Authorization"
private Credential authorize(String accountId, File p12File) throws Exception {
    Set<String> scopes = new HashSet<String>();
    scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
    scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
    scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);
    // Autoriza a aplicação
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(accountId).setServiceAccountPrivateKeyFromP12File(p12File).setServiceAccountScopes(scopes).build();
    return credential;
}
Example 39
Project: Commandr-Android-master  File: ReadUnreadGmailActivity.java View source code
@Override
protected String doInBackground(Void... params) {
    try {
        String token = GoogleAuthUtil.getToken(ReadUnreadGmailActivity.this, accountName, GMAIL_SCOPE);
        GoogleCredential credential = new GoogleCredential().setAccessToken(token);
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        mailService = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).build();
        // Retrieve a page of Threads; max of 100 by default.
        ListMessagesResponse response = mailService.users().messages().list("me").setQ("is:unread in:inbox").execute();
        List<Message> messages = new ArrayList<Message>();
        while (response.getMessages() != null) {
            messages.addAll(response.getMessages());
            if (response.getNextPageToken() != null) {
                String pageToken = response.getNextPageToken();
                response = mailService.users().messages().list("me").setQ("is:unread in:inbox").setPageToken(pageToken).execute();
            } else {
                break;
            }
        }
        String toSpeak;
        switch(messages.size()) {
            case 0:
                toSpeak = getString(R.string.no_unread) + " ";
                break;
            case 1:
                toSpeak = getString(R.string.one_unread) + " ";
                break;
            default:
                toSpeak = getString(R.string.there_are) + " " + messages.size() + " " + getString(R.string.unread_messages) + " ";
                break;
        }
        for (Message message : messages) {
            message = mailService.users().messages().get("me", message.getId()).setFormat("full").setFields("payload, snippet").execute();
            for (MessagePartHeader header : message.getPayload().getHeaders()) {
                if (header.getName().equals("From")) {
                    toSpeak += header.getValue().split("<")[0].trim().replace("\\", "").replace("\"", "") + " " + getString(R.string.sent) + " ";
                }
            }
            toSpeak += message.getSnippet() + ". ";
        }
        return toSpeak;
    } catch (UserRecoverableAuthException e) {
        startActivityForResult(e.getIntent(), 1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return getString(R.string.error_gmail);
}
Example 40
Project: embulk-output-gcs-master  File: GcsAuthentication.java View source code
/**
     * @see https://developers.google.com/accounts/docs/OAuth2ServiceAccount#authorizingrequests
     */
private GoogleCredential getServiceAccountCredential() throws IOException, GeneralSecurityException {
    // @see https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/java/latest/com/google/api/services/bigquery/BigqueryScopes.html
    return new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountEmail.orNull()).setServiceAccountScopes(ImmutableList.of(StorageScopes.DEVSTORAGE_READ_WRITE)).setServiceAccountPrivateKeyFromP12File(new File(p12KeyFilePath.get())).build();
}
Example 41
Project: fenixedu-cms-master  File: AdminSites.java View source code
private Analytics getUserAnalytics() {
    GoogleCredential credential = GoogleAPI.getInstance().getAuthenticatedUser(Authenticate.getUser()).get().getAuthenticatedSDK();
    return new Analytics.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(PortalConfiguration.getInstance().getApplicationTitle().getContent(Locale.ENGLISH)).build();
}
Example 42
Project: firebase-admin-java-master  File: FirebaseCredentials.java View source code
/**
     * Returns the associated GoogleCredential for this class. This implementation is cached by
     * default.
     */
final Task<GoogleCredential> getCertificate() {
    synchronized (this) {
        if (googleCredential != null) {
            return Tasks.forResult(googleCredential);
        }
    }
    return Tasks.call(new Callable<GoogleCredential>() {

        @Override
        public GoogleCredential call() throws Exception {
            // Retrieve a new credential. This is a network operation that can be repeated and is
            // done outside of the lock.
            GoogleCredential credential = fetchCredential();
            synchronized (BaseCredential.this) {
                googleCredential = credential;
            }
            return credential;
        }
    });
}
Example 43
Project: google-api-java-client-samples-master  File: PredictionSample.java View source code
/** Authorizes the installed application to access user's protected data. */
private static GoogleCredential authorize() throws Exception {
    return new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(SERVICE_ACCT_EMAIL).setServiceAccountPrivateKeyFromP12File(new File(PredictionSample.class.getResource("/" + SERVICE_ACCT_KEYFILE).getFile())).setServiceAccountScopes(Arrays.asList(PredictionScopes.PREDICTION, StorageScopes.DEVSTORAGE_READ_ONLY)).build();
}
Example 44
Project: Google-Plus-Mini-master  File: GetUsernameTask.java View source code
@Override
protected Boolean doInBackground(String... params) {
    //        Log.i(TAG, "inBackground");
    try {
        token = fetchToken();
        if (token != null) {
            GoogleCredential cred = new GoogleCredential().setAccessToken(token);
            PlusDomains plusDomains = new PlusDomains.Builder(new NetHttpTransport(), new JacksonFactory(), cred).build();
            me = plusDomains.people().get("me").execute();
            displayName = me.getDisplayName();
            aboutMe = me.getAboutMe();
            image_url = me.getImage().getUrl();
            occupation = me.getOccupation();
            organizations = "";
            if (me.getOrganizations() != null) {
                List<Person.Organizations> tmp = me.getOrganizations();
                for (Person.Organizations o : tmp) {
                    organizations = organizations + " " + o.getName() + ",";
                }
                organizations = organizations.substring(0, organizations.length() - 1);
            }
            listCircles = plusDomains.circles().list("me");
            if (listCircles != null) {
                circleFeed = listCircles.execute();
                circles = circleFeed.getItems();
                circle_list = new String[circles.size()];
                circle_children = new String[circles.size()][];
                circle_children_people = new Person[circles.size()][];
                while (circles != null) {
                    int i = 0;
                    for (Circle circle : circles) {
                        String name = circle.getDisplayName();
                        circle_list[i] = name;
                        String id = circle.getId();
                        listPeople = plusDomains.people().listByCircle(id);
                        PeopleFeed peopleFeed = listPeople.execute();
                        if (peopleFeed.getItems() != null && peopleFeed.getItems().size() > 0) {
                            circle_children[i] = new String[peopleFeed.getItems().size()];
                            circle_children_people[i] = new Person[peopleFeed.getItems().size()];
                            int j = 0;
                            for (Person person : peopleFeed.getItems()) {
                                circle_children[i][j] = person.getDisplayName();
                                circle_children_people[i][j] = person;
                                j++;
                            }
                        } else {
                            circle_children[i] = new String[0];
                            circle_children_people[i] = new Person[0];
                        }
                        i++;
                    }
                    if (circleFeed.getNextPageToken() != null) {
                        listCircles.setPageToken(circleFeed.getNextPageToken());
                        circleFeed = listCircles.execute();
                        circles = circleFeed.getItems();
                    } else {
                        circles = null;
                    }
                }
            }
        }
    } catch (IOException e) {
        Log.d("", "exception", e);
    }
    return true;
}
Example 45
Project: Midgard-master  File: DownloadDrive.java View source code
public static void main(String[] args) {
    try {
        try {
            // check for valid setup
            String p12Content = Files.readFirstLine(new java.io.File("key.p12"), Charset.defaultCharset());
            // service account credential (uncomment setServiceAccountUser for domain-wide delegation)
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(SCOPES).setServiceAccountPrivateKeyFromP12File(new java.io.File("key.p12")).build();
            Drive service = new Builder(TRANSPORT, JSON_FACTORY, credential).build();
            System.out.println("Before");
            File file = service.files().get("0B_4L9UB-A6C3dkJveW04MnJHQzg").execute();
            GenericUrl u = new GenericUrl(file.getDownloadUrl());
            Get request = service.files().get(file.getId());
            System.out.println(file.getTitle());
            MediaHttpDownloader mhd = request.getMediaHttpDownloader();
            mhd.setChunkSize(10 * 0x100000);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("test.txt"));
            System.out.println(bos.toString());
            System.out.println(u.toString());
            mhd.download(u, bos);
            //HttpResponse response = service.getRequestFactory().buildGetRequest(u).execute();
            //response.getContent();
            System.out.println("After");
            // success!
            return;
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}
Example 46
Project: nuxeo-labs-master  File: Publisher.java View source code
@OperationMethod(collector = DocumentModelCollector.class)
public DocumentModel run(DocumentModel input) {
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        OAuth2ServiceProvider serviceProvider = Framework.getLocalService(OAuth2ServiceProviderRegistry.class).getProvider("googledrive");
        Credential storedCredential = serviceProvider.loadCredential(userEmailAddress);
        Credential credential = new GoogleCredential.Builder().setClientSecrets(serviceProvider.getClientId(), serviceProvider.getClientSecret()).setJsonFactory(JSON_FACTORY).setTransport(httpTransport).build().setRefreshToken(storedCredential.getRefreshToken()).setAccessToken(storedCredential.getAccessToken());
        // Initialize Tasks service with valid OAuth credentials	    	
        Tasks service = new Tasks.Builder(httpTransport, JSON_FACTORY, credential).build();
        // Create a Task and publish it
        DateTime dueDateTime = new DateTime(dueDate.getTime());
        Task task = new Task().setTitle(title).setNotes(notes).setDue(dueDateTime);
        task = service.tasks().insert("@default", task).execute();
    } catch (GeneralSecurityExceptionIOException |  e) {
        throw new NuxeoException(e);
    }
    return input;
}
Example 47
Project: seco-master  File: GsUploadManager.java View source code
private static Storage getService(String credentialsPath, int connectTimeoutMs, int readTimeoutMs) throws Exception {
    if (mStorageService == null) {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential;
        try {
            // Lookup if configured path from the properties; otherwise fallback to Google Application default
            if (credentialsPath != null && !credentialsPath.isEmpty()) {
                credential = GoogleCredential.fromStream(new FileInputStream(credentialsPath), httpTransport, JSON_FACTORY).createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM));
            } else {
                credential = GoogleCredential.getApplicationDefault(httpTransport, JSON_FACTORY);
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to load Google credentials : " + credentialsPath, e);
        }
        mStorageService = new Storage.Builder(httpTransport, JSON_FACTORY, setHttpBackoffTimeout(credential, connectTimeoutMs, readTimeoutMs)).setApplicationName("com.pinterest.secor").build();
    }
    return mStorageService;
}
Example 48
Project: secor-master  File: GsUploadManager.java View source code
private static Storage getService(String credentialsPath, int connectTimeoutMs, int readTimeoutMs) throws Exception {
    if (mStorageService == null) {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential;
        try {
            // Lookup if configured path from the properties; otherwise fallback to Google Application default
            if (credentialsPath != null && !credentialsPath.isEmpty()) {
                credential = GoogleCredential.fromStream(new FileInputStream(credentialsPath), httpTransport, JSON_FACTORY).createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM));
            } else {
                credential = GoogleCredential.getApplicationDefault(httpTransport, JSON_FACTORY);
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to load Google credentials : " + credentialsPath, e);
        }
        mStorageService = new Storage.Builder(httpTransport, JSON_FACTORY, setHttpBackoffTimeout(credential, connectTimeoutMs, readTimeoutMs)).setApplicationName("com.pinterest.secor").build();
    }
    return mStorageService;
}
Example 49
Project: spydra-master  File: LifecycleIT.java View source code
private boolean isClusterCollected(SpydraArgument arguments) throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential.fromStream(new ByteArrayInputStream(gcpUtils.credentialJsonFromEnv().getBytes()));
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
    }
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    Dataproc dataprocService = new Dataproc.Builder(httpTransport, jsonFactory, credential).setApplicationName("Google Cloud Platform Sample").build();
    Dataproc.Projects.Regions.Clusters.List request = dataprocService.projects().regions().clusters().list(arguments.getCluster().getOptions().get(SpydraArgument.OPTION_PROJECT), "global");
    ListClustersResponse response;
    do {
        response = request.execute();
        if (response.getClusters() == null)
            continue;
        String clusterName = arguments.getCluster().getName();
        for (Cluster cluster : response.getClusters()) {
            if (cluster.getClusterName().equals(clusterName)) {
                String status = cluster.getStatus().getState();
                LOGGER.info("Cluster state is" + status);
                return status.equals("DELETING");
            }
        }
        request.setPageToken(response.getNextPageToken());
    } while (response.getNextPageToken() != null);
    return true;
}
Example 50
Project: streamreduce-core-master  File: GoogleAnalyticsClient.java View source code
private Analytics initializeAnalytics() {
    if (analytics == null) {
        GoogleAnalyticsProvider provider = new GoogleAnalyticsProvider();
        TokenResponse tokenResponse = new TokenResponse().setRefreshToken(getConnectionCredentials().getOauthRefreshToken());
        GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory).setTransport(transport).setClientSecrets(provider.getClientId(), provider.getClientSecret()).build().setFromTokenResponse(tokenResponse);
        analytics = new Analytics.Builder(transport, jsonFactory, credential).build();
    }
    return analytics;
}
Example 51
Project: super-share-master  File: ServiceFactory.java View source code
public static String getAccessToken(AbstractGoogleJsonClient jsonClient) {
    GoogleCredential googleCredential = ((Intializer) jsonClient.getRequestFactory().getInitializer()).credential;
    if (googleCredential.getAccessToken() == null || googleCredential.getExpirationTimeMilliseconds() <= System.currentTimeMillis()) {
        try {
            System.out.println("Access token is null so refreshing token");
            googleCredential.refreshToken();
        } catch (IOException e) {
            System.err.println("Error refreshing token for " + googleCredential.getServiceAccountUser());
            throw new ClientException(e);
        }
    }
    return googleCredential.getAccessToken();
}
Example 52
Project: SyncYourCloud-master  File: DriveGoogle.java View source code
public Boolean validateToken(String code) {
    GoogleTokenResponse response;
    try {
        response = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory, app_key, app_secret, code, app_redirect_uri).execute();
        credential = new GoogleCredential().setFromTokenResponse(response);
        //Create a new authorized API client
        service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
        uid = credential.getServiceAccountId();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}
Example 53
Project: tech-gallery-master  File: UserServiceTGImpl.java View source code
/**
   * This method should be executed whenever a user logs in It check whether the
   * user exists on TG's datastore and create them, if not. It also checks if
   * the user's email has been changed and update it, in case it was changed.
   *
   * @param user
   *          A Google AppEngine API user
   * @return A response with the user data as it is on TG datastore
   *
   * @throws InternalServerErrorException
   *           in case something goes wrong
   * @throws NotFoundException
   *           in case the information are not founded
   * @throws BadRequestException
   *           in case a request with problem were made.
   * @throws OAuthRequestException
   *           in case of authentication problem
   * @throws IOException
   *           in case of a IO exception
   */
@Override
public TechGalleryUser handleLogin(Integer timezoneOffset, final User user, HttpServletRequest req) throws NotFoundException, BadRequestException, InternalServerErrorException, IOException, OAuthRequestException {
    authorize(user);
    String userEmail = user.getEmail();
    String header = req.getHeader("Authorization");
    // "Bearer
    String accesstoken = header.substring(header.indexOf(' ')).trim();
    // ".length
    GoogleCredential credential = new GoogleCredential().setAccessToken(accesstoken);
    Plus plus = new Plus.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(i18n.t("Tech Gallery")).build();
    Person person = plus.people().get("me").execute();
    TechGalleryUser tgUser = userDao.findByGoogleId(user.getUserId());
    // Couldn't find by googleID. Try email
    if (tgUser == null) {
        tgUser = userDao.findByEmail(userEmail);
    }
    // Ok, we couldn't find it. Create it.
    if (tgUser == null) {
        tgUser = new TechGalleryUser();
    }
    updateUserInformation(user, person, tgUser);
    tgUser.setTimezoneOffset(timezoneOffset);
    addUser(tgUser);
    log.info("User " + tgUser.getName() + " added/updated");
    return tgUser;
}
Example 54
Project: UsuarioLecturista-master  File: UploadFileToGCSJob.java View source code
@Override
public void onRun() throws Throwable {
    // convert key into class File. from inputStream to file. in an aux class.
    File file = createFileFromInputStream();
    NetHttpTransport httpTransport = new NetHttpTransport();
    String emailAddress = "382197999605-nc5h44q7v54mgn915eqvtd71is4r46jg@developer.gserviceaccount.com";
    // Google credentials
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(emailAddress).setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)).setServiceAccountPrivateKeyFromP12File(file).build();
    String imageName = generateIdentifierForImage();
    String URI = "https://storage.googleapis.com/" + mBucketName + "/" + imageName + ".jpg";
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
    GenericUrl url = new GenericUrl(URI);
    byte[] mImageBytes = bitmapToByteArray(mImageBitmap);
    HttpContent contentSend = new ByteArrayContent("image/jpeg", mImageBytes);
    HttpRequest putRequest = requestFactory.buildPutRequest(url, contentSend);
    HttpResponse response = putRequest.execute();
    if (response.isSuccessStatusCode()) {
        Logger.i(response.getStatusMessage() + "Uploading image");
        responseOk = true;
        MainActivity.bus.post(new UploadImageEvent(UploadImageEvent.Type.COMPLETED, 1, imageName));
    }
}
Example 55
Project: Priam-master  File: GoogleEncryptedFileSystem.java View source code
/** Authorizes the installed application to access user's protected data, code from https://developers.google.com/maps-engine/documentation/oauth/serviceaccount
	 * and http://javadoc.google-api-java-client.googlecode.com/hg/1.8.0-beta/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.html 
	 */
private Credential constructGcsCredential() throws Exception {
    if (this.credential != null) {
        return this.credential;
    }
    synchronized (this) {
        if (this.credential == null) {
            String service_acct_email = new String(this.gcsCredential.getValue(KEY.GCS_SERVICE_ID));
            if (this.config.getGcsServiceAccountPrivateKeyLoc() == null || this.config.getGcsServiceAccountPrivateKeyLoc().isEmpty()) {
                throw new NullPointerException("Fast property for the the GCS private key file is null/empty.");
            }
            //Take the encrypted private key, decrypted into an in-transit file which is passed to GCS
            File gcsPrivateKeyHandle = new File(this.config.getGcsServiceAccountPrivateKeyLoc() + ".output");
            OutputStream os = new FileOutputStream(gcsPrivateKeyHandle);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            ByteArrayOutputStream byteos = new ByteArrayOutputStream();
            byte[] gcsPrivateKeyPlainText = this.gcsCredential.getValue(KEY.GCS_PRIVATE_KEY_LOC);
            try {
                byteos.write(gcsPrivateKeyPlainText);
                byteos.writeTo(bos);
            } catch (IOException e) {
                throw new IOException("Exception when writing decrypted gcs private key value to disk.", e);
            } finally {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new IOException("Exception when closing decrypted gcs private key value to disk.", e);
                }
            }
            Collection<String> scopes = new ArrayList<String>(1);
            scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
            this.credential = new GoogleCredential.Builder().setTransport(this.httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(service_acct_email).setServiceAccountScopes(scopes).setServiceAccountPrivateKeyFromP12File(//Cryptex decrypted service account key derive from the GCS console
            gcsPrivateKeyHandle).build();
        }
    }
    return this.credential;
}
Example 56
Project: android-maven-plugin-master  File: AndroidPublisherHelper.java View source code
private static Credential authorizeWithServiceAccount(String serviceAccountEmail, File pk12File) throws GeneralSecurityException, IOException {
    LOG.info(String.format("Authorizing using Service Account: %s", serviceAccountEmail));
    // Build service account credential.
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(serviceAccountEmail).setServiceAccountScopes(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)).setServiceAccountPrivateKeyFromP12File(pk12File == null ? new File(SRC_RESOURCES_KEY_P12) : pk12File).build();
    return credential;
}
Example 57
Project: atricore-idbus-master  File: GoogleAuthzTokenConsumerProducer.java View source code
protected void doProcessAuthzTokenResponse(CamelMediationExchange exchange, AuthorizationCodeResponseUrl authnResp) throws Exception {
    CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();
    CamelMediationMessage out = (CamelMediationMessage) exchange.getOut();
    MediationState mediationState = in.getMessage().getState();
    OpenIDConnectProxyMediator mediator = (OpenIDConnectProxyMediator) channel.getIdentityMediator();
    // OpenID Connect authorization code response
    String code = authnResp.getCode();
    if (authnResp.getError() != null) {
        // onError(req, resp, responseUrl);
        logger.error("Error received [" + authnResp.getError() + "] " + authnResp.getErrorDescription() + ", uri:" + authnResp.getErrorDescription());
        throw new OpenIDConnectException("OpenId Connect error: " + authnResp.getError() + " " + authnResp.getErrorDescription());
    } else if (code == null) {
        logger.error("Missing authorization code ");
        throw new OpenIDConnectException("Illegal response, no authorization code received ");
    }
    // Validate relay state
    String expectedRelayState = (String) mediationState.getLocalVariable("urn:OPENID-CONNECT:1.0:relayState");
    String relayState = authnResp.getState();
    if (!expectedRelayState.equals(relayState)) {
        // Invalid response
        if (logger.isDebugEnabled())
            logger.debug("Invalid state [" + relayState + "], expected [" + expectedRelayState + "]");
        throw new OpenIDConnectException("Illegal response, received OpenID Connect state is not valid");
    }
    // ---------------------------------------------------------------
    // Request access token
    // ---------------------------------------------------------------
    EndpointDescriptor accessTokenConsumerLocation = resolveAccessTokenConsumerEndpoint(OpenIDConnectConstants.GoogleAuthzTokenConsumerService_QNAME.toString());
    GenericUrl requestUrl = new GenericUrl(mediator.getAccessTokenServiceLocation());
    // URL used to get the access token.
    AuthorizationCodeTokenIdRequest request = new AuthorizationCodeTokenIdRequest(mediator.getHttpTransport(), mediator.getJacksonFactory(), requestUrl, code, mediator.getClientId(), mediator.getClientSecret());
    request.setRedirectUri(accessTokenConsumerLocation.getLocation());
    IdTokenResponse idTokenResponse = (IdTokenResponse) mediator.sendMessage(request, accessTokenConsumerLocation, channel);
    IdToken idToken = idTokenResponse.parseIdToken();
    String accessToken = idTokenResponse.getAccessToken();
    Long accessTokenExpiresIn = idTokenResponse.getExpiresInSeconds();
    String googleSubject = idToken.getPayload().getSubject();
    String email = (String) idToken.getPayload().get("email");
    if (logger.isDebugEnabled())
        logger.debug("Authz token resolved to " + email);
    if (logger.isTraceEnabled())
        logger.trace("Access token [" + accessToken + "]");
    if (logger.isTraceEnabled())
        logger.trace("Access token expires in [" + accessTokenExpiresIn + "]");
    if (logger.isTraceEnabled())
        logger.trace("Subject [" + googleSubject + "]");
    // get user info
    Oauth2 userInfoService = new Oauth2.Builder(mediator.getHttpTransport(), mediator.getJacksonFactory(), new GoogleCredential().setAccessToken(accessToken)).build();
    int retry = 0;
    Userinfoplus user = null;
    while (retry <= MAX_NUM_OF_USER_INFO_RETRIES) {
        try {
            user = userInfoService.userinfo().get().execute();
            break;
        } catch (IOException e) {
            retry++;
            logger.error(e.getMessage(), e);
            if (retry <= MAX_NUM_OF_USER_INFO_RETRIES) {
                logger.debug("Getting Google user info, retry: " + retry);
            } else {
                logger.error("Failed to get Google user info!");
            }
        }
    }
    SubjectType subject;
    List<SubjectAttributeType> attrs = new ArrayList<SubjectAttributeType>();
    subject = new SubjectType();
    SubjectNameIDType a = new SubjectNameIDType();
    a.setName(email);
    a.setFormat(NameIDFormat.EMAIL.getValue());
    a.setLocalName(email);
    a.setNameQualifier(getFederatedProvider().getName().toUpperCase());
    a.setLocalNameQualifier(getFederatedProvider().getName().toUpperCase());
    subject.getAbstractPrincipal().add(a);
    SubjectAttributeType accessTokenAttr = new SubjectAttributeType();
    accessTokenAttr.setName("accessToken");
    accessTokenAttr.setValue(accessToken);
    attrs.add(accessTokenAttr);
    SubjectAttributeType accessTokenExpiresInAttr = new SubjectAttributeType();
    accessTokenExpiresInAttr.setName("accessTokenExpiresIn");
    accessTokenExpiresInAttr.setValue(accessTokenExpiresIn + "");
    attrs.add(accessTokenExpiresInAttr);
    SubjectAttributeType openIdSubjectAttr = new SubjectAttributeType();
    openIdSubjectAttr.setName("openIdSubject");
    openIdSubjectAttr.setValue(googleSubject);
    attrs.add(openIdSubjectAttr);
    SubjectAttributeType authnCtxClassAttr = new SubjectAttributeType();
    authnCtxClassAttr.setName("authnCtxClass");
    authnCtxClassAttr.setValue(AuthnCtxClass.PPT_AUTHN_CTX.getValue());
    attrs.add(authnCtxClassAttr);
    if (user != null) {
        addUserAttributes(user, attrs);
    }
    SPAuthnResponseType ssoResponse = new SPAuthnResponseType();
    ssoResponse.setID(uuidGenerator.generateId());
    ssoResponse.setIssuer(getFederatedProvider().getName());
    SPInitiatedAuthnRequestType ssoRequest = (SPInitiatedAuthnRequestType) in.getMessage().getState().getLocalVariable("urn:org:atricore:idbus:sso:protocol:SPInitiatedAuthnRequest");
    if (ssoRequest != null) {
        ssoResponse.setInReplayTo(ssoRequest.getID());
    }
    ssoResponse.setSessionIndex(uuidGenerator.generateId());
    ssoResponse.setSubject(subject);
    ssoResponse.getSubjectAttributes().addAll(attrs);
    // ------------------------------------------------------------------------------
    // Send SP Authentication response
    // ------------------------------------------------------------------------------
    SPInitiatedAuthnRequestType authnRequest = (SPInitiatedAuthnRequestType) mediationState.getLocalVariable("urn:OPENID-CONNECT:1.0:authnRequest");
    // Send response back
    String destinationLocation = resolveSpProxyACS(authnRequest);
    if (logger.isTraceEnabled())
        logger.trace("Sending response to " + destinationLocation);
    EndpointDescriptor destination = new EndpointDescriptorImpl("EmbeddedSPAcs", "AssertionConsumerService", OpenIDConnectBinding.SSO_ARTIFACT.getValue(), destinationLocation, null);
    out.setMessage(new MediationMessageImpl(ssoResponse.getID(), ssoResponse, "SPAuthnResponse", "", destination, in.getMessage().getState()));
    exchange.setOut(out);
    return;
}
Example 58
Project: cloudpelican-lsd-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    // Parse params
    JsonParser jp = new JsonParser();
    JsonObject settings = jp.parse(new String(Base64.decodeBase64(args[0].getBytes()))).getAsJsonObject();
    String projectId = settings.get("project_id").getAsString();
    String serviceAccountId = settings.get("service_account_id").getAsString();
    String pk12KeyBase64 = settings.get("pk12base64").getAsString();
    // Init key
    PrivateKey pk12;
    try {
        byte[] keyBytes = Base64.decodeBase64(pk12KeyBase64.getBytes());
        ByteArrayInputStream bis = new ByteArrayInputStream(keyBytes);
        pk12 = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), bis, "notasecret", "privatekey", "notasecret");
        LOG.info("Loaded PK12 key");
    } catch (Exception e) {
        LOG.info(e.getMessage());
        System.exit(1);
        e.printStackTrace();
        return;
    }
    // Transport
    HttpTransport httpTransport;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Exception e) {
        LOG.info(e.getMessage());
        e.printStackTrace();
        System.exit(1);
        return;
    }
    // JSON
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    // Build a service account credential.
    GoogleCredential googleCredential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(serviceAccountId).setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE)).setServiceAccountPrivateKey(pk12).build();
    // BigQuery
    Bigquery bigquery = new Bigquery.Builder(httpTransport, JSON_FACTORY, googleCredential).setApplicationName(Main.class.getSimpleName()).build();
    // Start a Query Job
    String querySql = settings.get("query").getAsString();
    JobReference jobId = startQuery(bigquery, projectId, querySql);
    // Poll for Query Results, return result output
    Job completedJob = checkQueryResults(bigquery, projectId, jobId);
    // Return and display the results of the Query Job
    displayQueryResults(bigquery, projectId, completedJob);
}
Example 59
Project: elasticsearch-master  File: GoogleCloudStorageService.java View source code
@Override
public Storage createClient(String serviceAccount, String application, TimeValue connectTimeout, TimeValue readTimeout) throws Exception {
    try {
        GoogleCredential credentials = (DEFAULT.equalsIgnoreCase(serviceAccount)) ? loadDefault() : loadCredentials(serviceAccount);
        NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        Storage.Builder storage = new Storage.Builder(httpTransport, JacksonFactory.getDefaultInstance(), new DefaultHttpRequestInitializer(credentials, connectTimeout, readTimeout));
        storage.setApplicationName(application);
        logger.debug("initializing client with service account [{}/{}]", credentials.getServiceAccountId(), credentials.getServiceAccountUser());
        return storage.build();
    } catch (IOException e) {
        throw new ElasticsearchException("Error when loading Google Cloud Storage credentials file", e);
    }
}
Example 60
Project: glassmaker-master  File: MirrorTemplate.java View source code
private Credential getCredential() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) auth;
    String accessToken = (String) token.getDetails();
    GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
    return credential;
}
Example 61
Project: gobblin-master  File: GoogleCommon.java View source code
/**
   * As Google API only accepts java.io.File for private key, and this method copies private key into local file system.
   * Once Google credential is instantiated, it deletes copied private key file.
   *
   * @param privateKeyPath
   * @param fsUri
   * @param id
   * @param transport
   * @param serviceAccountScopes
   * @return Credential
   * @throws IOException
   * @throws GeneralSecurityException
   */
private static Credential buildCredentialFromP12(String privateKeyPath, Optional<String> fsUri, Optional<String> id, HttpTransport transport, Collection<String> serviceAccountScopes) throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(id.isPresent(), "user id is required.");
    FileSystem fs = getFileSystem(fsUri);
    Path keyPath = getPrivateKey(fs, privateKeyPath);
    final File localCopied = copyToLocal(fs, keyPath);
    localCopied.deleteOnExit();
    try {
        return new GoogleCredential.Builder().setTransport(transport).setJsonFactory(JSON_FACTORY).setServiceAccountId(id.get()).setServiceAccountPrivateKeyFromP12File(localCopied).setServiceAccountScopes(serviceAccountScopes).build();
    } finally {
        boolean isDeleted = localCopied.delete();
        if (!isDeleted) {
            throw new RuntimeException(localCopied.getAbsolutePath() + " has not been deleted.");
        }
    }
}
Example 62
Project: googleapps-grouper-provisioner-master  File: GoogleGrouperConnector.java View source code
public void initialize(String consumerName, final GoogleAppsSyncProperties properties) throws GeneralSecurityException, IOException {
    this.consumerName = consumerName;
    this.properties = properties;
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    final GoogleCredential googleDirectoryCredential = GoogleAppsSdkUtils.getGoogleDirectoryCredential(properties.getServiceAccountEmail(), properties.getServiceAccountPKCS12FilePath(), properties.getServiceImpersonationUser(), httpTransport, JSON_FACTORY);
    final GoogleCredential googleGroupssettingsCredential = GoogleAppsSdkUtils.getGoogleGroupssettingsCredential(properties.getServiceAccountEmail(), properties.getServiceAccountPKCS12FilePath(), properties.getServiceImpersonationUser(), httpTransport, JSON_FACTORY);
    directoryClient = new Directory.Builder(httpTransport, JSON_FACTORY, googleDirectoryCredential).setApplicationName("Google Apps Grouper Provisioner").build();
    groupssettingsClient = new Groupssettings.Builder(httpTransport, JSON_FACTORY, googleGroupssettingsCredential).setApplicationName("Google Apps Grouper Provisioner").build();
    addressFormatter.setGroupIdentifierExpression(properties.getGroupIdentifierExpression()).setSubjectIdentifierExpression(properties.getSubjectIdentifierExpression()).setDomain(properties.getGoogleDomain());
    GoogleCacheManager.googleUsers().setCacheValidity(properties.getGoogleUserCacheValidity());
    GoogleCacheManager.googleGroups().setCacheValidity(properties.getGoogleGroupCacheValidity());
    grouperSubjects.setCacheValidity(5);
    grouperSubjects.seed(1000);
    grouperGroups.setCacheValidity(5);
    grouperGroups.seed(100);
    recentlyManipulatedObjectsList = new RecentlyManipulatedObjectsList(properties.getRecentlyManipulatedQueueSize(), properties.getRecentlyManipulatedQueueDelay());
}
Example 63
Project: GoogleCloudStorage-master  File: CredentialBuilder.java View source code
/**
     * Here the actual Credentials are built with any parameters provided to this class, such
     * as JsonFactory, Scope and HttpTransport. If any parameters are not provided, stock
     * options will be used.
     *
     * @return
     * @throws IOException
     * @throws GeneralSecurityException
     */
public Credential build() throws IOException, GeneralSecurityException {
    GoogleCredential.Builder credential = new GoogleCredential.Builder();
    Log.d(TAG, "Initiated Builder");
    // 1. Service Account ID
    credential.setServiceAccountId(accountID);
    Log.d(TAG, "Setup Account ID");
    // 2. Private Key
    credential.setServiceAccountPrivateKeyFromP12File(getGoogleCloudKeyFile(context, key_resource_ID));
    Log.d(TAG, "Setup Private Key");
    // 3. HttpTransport
    if (httpTransport != null) {
        credential.setTransport(httpTransport);
        Log.d(TAG, "Setup given HttpTransport");
    } else {
        credential.setTransport(new ApacheHttpTransport());
        Log.d(TAG, "Setup stock HttpTransport (ApacheHttpTransport)");
    }
    // 4. Scope
    if (scopes != null && scopes.size() > 0) {
        credential.setServiceAccountScopes(scopes);
        Log.d(TAG, "Setup given scope");
    } else {
        scopes = new ArrayList<>();
        scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
        credential.setServiceAccountScopes(scopes);
        Log.d(TAG, "Setup stock scope (DEVSTORAGE_FULL_CONTROL)");
    }
    // 5. JsonFactory
    if (jsonFactory != null) {
        credential.setJsonFactory(jsonFactory);
        Log.d(TAG, "Setup given JsonFactory");
    } else {
        credential.setJsonFactory(new JacksonFactory());
        Log.d(TAG, "Setup stock JsonFactory (JacksonFactory)");
    }
    // 6. Build
    GoogleCredential builtCredential = credential.build();
    Log.d(TAG, "Building Google Credential");
    Log.d(TAG, "Returning built Credential");
    return builtCredential;
}
Example 64
Project: gradle-android-publisher-master  File: AndroidPublisherHelper.java View source code
private static Credential authorizeWithServiceAccount(String serviceAccountEmail, File serviceAccountKeyFile) throws GeneralSecurityException, IOException {
    log.info(String.format("Authorizing using Service Account: %s", serviceAccountEmail));
    // Build service account credential.
    log.info("Using service key file: " + serviceAccountKeyFile.getAbsolutePath());
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setServiceAccountId(serviceAccountEmail).setServiceAccountScopes(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)).setServiceAccountPrivateKeyFromP12File(serviceAccountKeyFile).build();
    return credential;
}
Example 65
Project: incubator-streams-master  File: YoutubeProvider.java View source code
@VisibleForTesting
protected YouTube createYouTubeClient() throws IOException, GeneralSecurityException {
    GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setServiceAccountId(getConfig().getOauth().getServiceAccountEmailAddress()).setServiceAccountScopes(scopes);
    if (StringUtils.isNotEmpty(getConfig().getOauth().getPathToP12KeyFile())) {
        File p12KeyFile = new File(getConfig().getOauth().getPathToP12KeyFile());
        if (p12KeyFile.exists() && p12KeyFile.isFile() && p12KeyFile.canRead()) {
            credentialBuilder = credentialBuilder.setServiceAccountPrivateKeyFromP12File(p12KeyFile);
        }
    }
    Credential credential = credentialBuilder.build();
    return new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("Streams Application").build();
}
Example 66
Project: Momus-master  File: DevController.java View source code
@RequestMapping("/gdoc")
@ResponseBody
public String gdocTest() {
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = null;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityExceptionIOException |  e) {
        e.printStackTrace();
    }
    try {
        if (credential == null) {
            String email = "68986569027-ecn9md3ej7krhquhvamf7phfovro8aru@developer.gserviceaccount.com";
            ClassPathResource classPathResource = new ClassPathResource("googlekey.p12");
            File file = classPathResource.getFile();
            Collection<String> scopes = new ArrayList<>();
            scopes.add("https://www.googleapis.com/auth/drive");
            logger.info("making credentials");
            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(email).setServiceAccountPrivateKeyFromP12File(//                    .setServiceAccountPrivateKey
            file).setServiceAccountScopes(scopes).build();
            logger.info("made credentials");
        }
        if (drive == null) {
            drive = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName("momustest-molten-aurora-752").build();
            logger.info("made drive");
        }
        long start = System.currentTimeMillis();
        // list all files
        Drive.Files.List request = drive.files().list();
        FileList fileList = request.execute();
        List<com.google.api.services.drive.model.File> items = fileList.getItems();
        for (com.google.api.services.drive.model.File item : items) {
            logger.info("file: {}", item);
        //                Map<String, String> exportLinks = item.getExportLinks();//.get("text/html");
        //                String s = exportLinks.get("text/plain"); // will crash for stuff not having this
        //                logger.debug("test");
        }
        About execute = drive.about().get().execute();
        // insert file
        //            com.google.api.services.drive.model.File insertFile = new com.google.api.services.drive.model.File();
        //            insertFile.setTitle("mats2.odt");
        //            insertFile.setMimeType("application/vnd.google-apps.document");
        //            com.google.api.services.drive.model.File uploaded = drive.files().insert(insertFile).execute();
        //            logger.info("uploaded file id({}): {}", uploaded.getId(), uploaded);
        //
        //            Permission permission = new Permission();
        //            permission.setRole("writer");
        //            permission.setType("anyone");
        //            permission.setValue("default");
        //            permission.setWithLink(true);
        //
        //            drive.permissions().insert(uploaded.getId(), permission).execute();
        long end = System.currentTimeMillis();
        long timeUsed = end - start;
        logger.debug("Time spent: {}ms", timeUsed);
    } catch (GeneralSecurityExceptionIOException |  e) {
        logger.debug("Ex: ", e);
    }
    return "gdoc ok";
}
Example 67
Project: OpenRefine-master  File: FusionTableHandler.java View source code
public static Fusiontables getFusionTablesService(String token) {
    Credential credential = new GoogleCredential().setAccessToken(token);
    Fusiontables fusiontables = new Fusiontables.Builder(GDataExtension.HTTP_TRANSPORT, GDataExtension.JSON_FACTORY, credential).setApplicationName(GDataExtension.SERVICE_APP_NAME).build();
    ;
    return fusiontables;
}
Example 68
Project: playstorepublisher-master  File: AndroidPublisherHelper.java View source code
private static Credential authorizeWithServiceAccount(String serviceAccountEmail) throws GeneralSecurityException, IOException {
    log.info(String.format("Authorizing using Service Account: %s", serviceAccountEmail));
    // Build service account credential.
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setServiceAccountId(serviceAccountEmail).setServiceAccountScopes(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)).setServiceAccountPrivateKeyFromP12File(new File(SRC_RESOURCES_KEY_P12)).build();
    return credential;
}
Example 69
Project: pubsub-master  File: Driver.java View source code
private void runMaxSubscriberThroughputTest() throws Throwable {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory).createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
    Monitoring monitoring = new Monitoring.Builder(transport, jsonFactory, credential).setApplicationName("Cloud Pub/Sub Loadtest Framework").build();
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    for (AtomicLong backlogSize = new AtomicLong(0); backlogSize.get() < maxSubscriberThroughputTestBacklog; Client.requestRate = (int) (Client.requestRate * 1.1)) {
        runTest(() -> {
            try {
                Date startDate = new Date();
                startDate.setTime(Timestamps.toMillis(Client.startTime));
                controller.waitForPublisherClients();
                ListTimeSeriesResponse response = monitoring.projects().timeSeries().list("projects/" + project).setFilter("metric.type = " + "\"pubsub.googleapis.com/subscription/num_undelivered_messages\"").setIntervalStartTime(dateFormatter.format(startDate)).setIntervalEndTime(dateFormatter.format(new Date())).execute();
                // Get most recent point.
                Point latestBacklogSize = null;
                for (TimeSeries timeSeries : response.getTimeSeries()) {
                    for (Point point : timeSeries.getPoints()) {
                        if (latestBacklogSize == null || dateFormatter.parse(point.getInterval().getStartTime()).after(dateFormatter.parse(latestBacklogSize.getInterval().getStartTime()))) {
                            latestBacklogSize = point;
                        }
                    }
                }
                if (latestBacklogSize != null) {
                    backlogSize.set(latestBacklogSize.getValue().getInt64Value());
                }
            } catch (Throwable t) {
                throw new RuntimeException("Error getting backlog stats.", t);
            }
        });
    }
    log.info("We accumulated a backlog during this test, refer to the last run " + "for the maximum throughput attained before accumulating backlog.");
    controller.shutdown(null);
}
Example 70
Project: tatami-master  File: UserXAuthController.java View source code
private Person getGoogleUserInfo(String authorizationCode) throws IOException {
    String clientId = env.getProperty("tatami.google.clientId");
    String clientSecret = env.getProperty("tatami.google.clientSecret");
    HttpTransport transport = new NetHttpTransport();
    JacksonFactory jacksonFactory = new JacksonFactory();
    TokenResponse accessCode = new GoogleAuthorizationCodeTokenRequest(transport, jacksonFactory, clientId, clientSecret, authorizationCode, "http://localhost/callback").execute();
    GoogleCredential googleCredential = new GoogleCredential.Builder().setJsonFactory(new JacksonFactory()).setTransport(transport).setClientSecrets(clientId, clientSecret).build().setFromTokenResponse(accessCode);
    Plus plus = new Plus.Builder(transport, jacksonFactory, googleCredential).setApplicationName("Tatami").build();
    return plus.people().get("me").execute();
}
Example 71
Project: toolkit-master  File: JavaSampleMethodToViewTransformer.java View source code
private void addStaticImports(SampleTransformerContext context) {
    SampleConfig sampleConfig = context.getSampleConfig();
    SampleTypeTable typeTable = context.getSampleTypeTable();
    if (sampleConfig.authType() != AuthType.NONE) {
        typeTable.saveNicknameFor("com.google.api.client.googleapis.auth.oauth2.GoogleCredential");
    }
    typeTable.saveNicknameFor("com.google.api.client.googleapis.javanet.GoogleNetHttpTransport");
    typeTable.saveNicknameFor("com.google.api.client.http.HttpTransport");
    typeTable.saveNicknameFor("com.google.api.client.json.jackson2.JacksonFactory");
    typeTable.saveNicknameFor("com.google.api.client.json.JsonFactory");
    typeTable.saveNicknameFor("java.io.IOException");
    typeTable.saveNicknameFor("java.security.GeneralSecurityException");
    if (sampleConfig.authType() == AuthType.APPLICATION_DEFAULT_CREDENTIALS) {
        typeTable.saveNicknameFor("java.util.Arrays");
    }
}
Example 72
Project: appinventor-sources-master  File: FusiontablesControl.java View source code
/**
   * Executes a Fusiontable query with an OAuth 2.0 authenticated
   * request.  Requests are authenticated by attaching an
   * Authentication header to the Http request.  The header
   * takes the form 'Authentication Oauth <access_token>'.
   *
   * Requests take the form of SQL strings, using an Sql
   * object from the Google API Client library.  Apparently
   * the Sql object handles the decision of whether the request
   * should be a GET or a POST.  Queries such as 'show tables'
   * and 'select' are supposed to be GETs and queries such as
   * 'insert' are supposed to be POSTS.
   *
   * See <a href="https://developers.google.com/fusiontables/docs/v2/using">https://developers.google.com/fusiontables/docs/v2/using</a>
   *
   * @param query the raw SQL string used by App Inventor
   * @param authToken the OAuth 2.0 access token
   * @return the HttpResponse if the request succeeded, or null
   */
public com.google.api.client.http.HttpResponse sendQuery(String query, String authToken) {
    // In case we get an error without a message
    errorMessage = standardErrorMessage;
    Log.i(LOG_TAG, "executing " + query);
    com.google.api.client.http.HttpResponse response = null;
    // Create a Fusiontables service object (from Google API client lib)
    Fusiontables service = new Fusiontables.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), new GoogleCredential()).setApplicationName("App Inventor Fusiontables/v2.0").setJsonHttpRequestInitializer(new GoogleKeyInitializer(ApiKey())).build();
    try {
        // Construct the SQL query and get a CSV result
        Sql sql = ((Fusiontables) service).query().sql(query);
        sql.put("alt", "csv");
        // Add the authToken to authentication header
        sql.setOauthToken(authToken);
        response = sql.executeUnparsed();
    } catch (GoogleJsonResponseException e) {
        e.printStackTrace();
        errorMessage = e.getMessage();
        Log.e(LOG_TAG, "JsonResponseException");
        Log.e(LOG_TAG, "e.getMessage() is " + e.getMessage());
        Log.e(LOG_TAG, "response is " + response);
    } catch (IOException e) {
        e.printStackTrace();
        errorMessage = e.getMessage();
        Log.e(LOG_TAG, "IOException");
        Log.e(LOG_TAG, "e.getMessage() is " + e.getMessage());
        Log.e(LOG_TAG, "response is " + response);
    }
    return response;
}
Example 73
Project: fluxtream-app-master  File: SmsBackupUpdater.java View source code
private GoogleCredential getCredentials(ApiKey apiKey) throws UpdateFailedException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    // Get all the attributes for this connector's oauth token from the stored attributes
    String accessToken = guestService.getApiKeyAttribute(apiKey, "accessToken");
    final String refreshToken = guestService.getApiKeyAttribute(apiKey, "refreshToken");
    final String clientId = guestService.getApiKeyAttribute(apiKey, "google.client.id");
    final String clientSecret = guestService.getApiKeyAttribute(apiKey, "google.client.secret");
    final GoogleCredential.Builder builder = new GoogleCredential.Builder();
    builder.setTransport(httpTransport);
    builder.setJsonFactory(jsonFactory);
    builder.setClientSecrets(clientId, clientSecret);
    GoogleCredential credential = builder.build();
    final Long tokenExpires = Long.valueOf(guestService.getApiKeyAttribute(apiKey, "tokenExpires"));
    credential.setExpirationTimeMilliseconds(tokenExpires);
    credential.setAccessToken(accessToken);
    credential.setRefreshToken(refreshToken);
    try {
        if (tokenExpires < System.currentTimeMillis()) {
            boolean tokenRefreshed = false;
            // Don't worry about checking if we are running on a mirrored test instance.
            // Refreshing tokens independently on both the main server and a mirrored instance
            // seems to work just fine.
            // Try to swap the expired access token for a fresh one.
            tokenRefreshed = credential.refreshToken();
            if (tokenRefreshed) {
                Long newExpireTime = credential.getExpirationTimeMilliseconds();
                // Update stored expire time
                guestService.setApiKeyAttribute(apiKey, "accessToken", credential.getAccessToken());
                guestService.setApiKeyAttribute(apiKey, "tokenExpires", newExpireTime.toString());
            }
        }
    } catch (TokenResponseException e) {
        notificationsService.addNamedNotification(apiKey.getGuestId(), Notification.Type.WARNING, connector().statusNotificationName(), "Heads Up. We failed in our attempt to automatically refresh your Google authentication tokens.<br>" + "Please head to <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a>,<br>" + "scroll to the Google Calendar connector, and renew your tokens (look for the <i class=\"icon-resize-small icon-large\"></i> icon)");
        guestService.setApiKeyStatus(apiKey.getId(), ApiKey.Status.STATUS_PERMANENT_FAILURE, Utils.stackTrace(e), ApiKey.PermanentFailReason.NEEDS_REAUTH);
        throw new UpdateFailedException("refresh token attempt permanently failed due to a bad token refresh response", e, true, ApiKey.PermanentFailReason.NEEDS_REAUTH);
    } catch (IOException e) {
        throw new UpdateFailedException("refresh token attempt failed", e, true, ApiKey.PermanentFailReason.NEEDS_REAUTH);
    }
    return credential;
}
Example 74
Project: google-sites-liberation-master  File: GuiMain.java View source code
/**
   * Retrieve OAuth 2.0 credentials.
   * 
   * @return OAuth 2.0 Credential instance.
   * @throws IOException
   */
private Credential getCredentials() throws IOException {
    String code = tokenField.getText();
    HttpTransport transport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY";
    // Step 2: Exchange -->
    GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI).execute();
    // Build a new GoogleCredential instance and return it.
    return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET).setJsonFactory(jsonFactory).setTransport(transport).build().setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
Example 75
Project: myrobotlab-master  File: GoogleCloud.java View source code
// [START main]
/**
   * Annotates an image using the Vision API.
   */
// [END main]
// [START get_vision_service]
/**
   * Connects to the Vision API using Application Default Credentials.
   */
public Vision getVisionService(String credJsonFile) throws IOException, GeneralSecurityException {
    /*
     * GoogleCredential credential = new
     * GoogleCredential().setAccessToken(accessToken); Plus plus = new
     * Plus.builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
     * credential) .setApplicationName("Google-PlusSample/1.0") .build();
     */
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(credJsonFile)).createScoped(VisionScopes.all());
    /*
     * JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
     * 
     * HttpTransport httpTransport =
     * GoogleNetHttpTransport.newTrustedTransport();
     * 
     * InputStream inputStream = IOUtils.toInputStream(serviceAccountJson);
     * 
     * GoogleCredential credential = GoogleCredential.fromStream(inputStream,
     * httpTransport, jsonFactory);
     * 
     * credential =
     * credential.createScoped(Collections.singleton(AndroidPublisherScopes.
     * ANDROIDPUBLISHER));
     * 
     * AndroidPublisher androidPublisher = new AndroidPublisher(httpTransport,
     * jsonFactory, credential);
     */
    // GoogleCredential credential =
    // GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential).setApplicationName(APPLICATION_NAME).build();
}
Example 76
Project: zeppelin-master  File: BigQueryInterpreter.java View source code
//Function that Creates an authorized client to Google Bigquery.
private static Bigquery createAuthorizedClient() throws IOException {
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
        Collection<String> bigqueryScopes = BigqueryScopes.all();
        credential = credential.createScoped(bigqueryScopes);
    }
    return new Bigquery.Builder(transport, jsonFactory, credential).setApplicationName("Zeppelin/1.0 (GPN:Apache Zeppelin;)").build();
}
Example 77
Project: dasein-cloud-google-master  File: Google.java View source code
private GoogleCredential getCreds(HttpTransport transport, JsonFactory jsonFactory, Collection<String> scopes) throws Exception {
    byte[] p12Bytes = null;
    String p12Password = "";
    String serviceAccountId = "";
    List<ContextRequirements.Field> fields = getContextRequirements().getConfigurableValues();
    try {
        for (ContextRequirements.Field f : fields) {
            if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                byte[][] keyPair = (byte[][]) getContext().getConfigurationValue(f);
                p12Bytes = keyPair[0];
                p12Password = new String(keyPair[1], "utf-8");
            } else if (f.compatName != null && f.compatName.equals(ContextRequirements.Field.ACCESS_KEYS))
                serviceAccountId = (String) getContext().getConfigurationValue(f);
        }
    } catch (Exception ex) {
        throw new CloudException(CloudErrorType.AUTHENTICATION, 400, "Bad Credentials", "An authentication error has occurred: Bad Credentials");
    }
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    InputStream p12AsStream = new ByteArrayInputStream(p12Bytes);
    keyStore.load(p12AsStream, p12Password.toCharArray());
    GoogleCredential creds = new GoogleCredential.Builder().setTransport(transport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId).setServiceAccountScopes(scopes).setServiceAccountPrivateKey(//This is always the password for p12 files
    (PrivateKey) keyStore.getKey("privateKey", p12Password.toCharArray())).build();
    return creds;
}
Example 78
Project: DriveCopy-master  File: DriveSdoImpl.java View source code
protected Drive getService(@Nonnull TokenBO token) {
    final GoogleCredential credential = new GoogleCredential.Builder().setClientSecrets(token.getClientId(), token.getClientSecret()).setJsonFactory(jsonFactory).setTransport(httpTransport).build().setRefreshToken(token.getRefreshToken()).setAccessToken(token.getAccessToken());
    return new Drive.Builder(httpTransport, jsonFactory, new HttpRequestInitializer() {

        public void initialize(HttpRequest httpRequest) {
            try {
                // initialize credentials
                credential.initialize(httpRequest);
                // set connect and read timeouts
                httpRequest.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
                httpRequest.setReadTimeout(HTTP_REQUEST_TIMEOUT);
            } catch (IOException ex) {
                logger.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
    }).setApplicationName("DriveCopy").build();
}
Example 79
Project: es-google-drive-river-master  File: DriveConnector.java View source code
/**
    * Actually connect to specified drive, exchanging refresh token for an up-to-date
    * set of credentials. If folder name specified, we also retrieve subfolders to scan. 
    * @param folderName The name of the root folder to scan.
    */
public void connectUserDrive(String folderName) throws IOException {
    this.folderName = folderName;
    logger.info("Establishing connection to Google Drive");
    // We'll use some transport and json factory for sure.
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    TokenResponse tokenResponse = null;
    try {
        tokenResponse = new GoogleRefreshTokenRequest(httpTransport, jsonFactory, refreshToken, clientId, clientSecret).execute();
    } catch (IOException ioe) {
        logger.error("IOException while refreshing a token request", ioe);
    }
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setClientSecrets(clientId, clientSecret).build().setFromTokenResponse(tokenResponse);
    //credential.setRefreshToken(refreshToken);
    service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
    logger.info("Connection established.");
    if (folderName != null) {
        logger.info("Retrieving scanned subfolders under folder {}, this may take a while...", folderName);
        subfoldersId = getSubfoldersId(folderName);
        logger.info("Subfolders to scan found");
        if (logger.isDebugEnabled()) {
            logger.debug("Found {} valid subfolders under folder {}", subfoldersId.size(), folderName);
        }
    }
}
Example 80
Project: gatein-portal-master  File: GoogleProcessorImpl.java View source code
@Override
public GoogleAccessTokenContext validateTokenAndUpdateScopes(GoogleAccessTokenContext accessTokenContext) {
    GoogleRequest<Tokeninfo> googleRequest = new GoogleRequest<Tokeninfo>() {

        @Override
        protected Tokeninfo invokeRequest(GoogleAccessTokenContext accessTokenContext) throws IOException {
            GoogleTokenResponse tokenData = accessTokenContext.getTokenData();
            Oauth2 oauth2 = getOAuth2InstanceImpl(tokenData);
            GoogleCredential credential = getGoogleCredential(tokenData);
            return oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
        }

        @Override
        protected OAuthException createException(IOException cause) {
            if (cause instanceof HttpResponseException) {
                return new OAuthException(OAuthExceptionCode.ACCESS_TOKEN_ERROR, "Error when obtaining tokenInfo: " + cause.getMessage(), cause);
            } else {
                return new OAuthException(OAuthExceptionCode.IO_ERROR, "IO Error when obtaining tokenInfo: " + cause.getMessage(), cause);
            }
        }
    };
    Tokeninfo tokenInfo = googleRequest.executeRequest(accessTokenContext, this);
    // If there was an error in the token info, abort.
    if (tokenInfo.containsKey("error")) {
        throw new OAuthException(OAuthExceptionCode.ACCESS_TOKEN_ERROR, "Error during token validation: " + tokenInfo.get("error").toString());
    }
    if (!tokenInfo.getIssuedTo().equals(clientID)) {
        throw new OAuthException(OAuthExceptionCode.ACCESS_TOKEN_ERROR, "Token's client ID does not match app's. clientID from tokenINFO: " + tokenInfo.getIssuedTo());
    }
    if (log.isTraceEnabled()) {
        log.trace("Successfully validated accessToken from google: " + tokenInfo);
    }
    String[] scopes = tokenInfo.getScope().split(" ");
    return new GoogleAccessTokenContext(accessTokenContext.getTokenData(), scopes);
}
Example 81
Project: ignite-master  File: TcpDiscoveryGoogleStorageIpFinder.java View source code
/**
     * Google Cloud Storage initialization.
     *
     * @throws IgniteSpiException In case of error.
     */
private void init() throws IgniteSpiException {
    if (initGuard.compareAndSet(false, true)) {
        if (srvcAccountId == null || srvcAccountP12FilePath == null || projectName == null || bucketName == null) {
            throw new IgniteSpiException("One or more of the required parameters is not set [serviceAccountId=" + srvcAccountId + ", serviceAccountP12FilePath=" + srvcAccountP12FilePath + ", projectName=" + projectName + ", bucketName=" + bucketName + "]");
        }
        try {
            NetHttpTransport httpTransport;
            try {
                httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            } catch (GeneralSecurityExceptionIOException |  e) {
                throw new IgniteSpiException(e);
            }
            GoogleCredential cred;
            try {
                cred = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(srvcAccountId).setServiceAccountPrivateKeyFromP12File(new File(srvcAccountP12FilePath)).setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)).build();
            } catch (Exception e) {
                throw new IgniteSpiException("Failed to authenticate on Google Cloud Platform", e);
            }
            try {
                storage = new Storage.Builder(httpTransport, JacksonFactory.getDefaultInstance(), cred).setApplicationName(projectName).build();
            } catch (Exception e) {
                throw new IgniteSpiException("Failed to open a storage for given project name: " + projectName, e);
            }
            boolean createBucket = false;
            try {
                Storage.Buckets.Get getBucket = storage.buckets().get(bucketName);
                getBucket.setProjection("full");
                getBucket.execute();
            } catch (GoogleJsonResponseException e) {
                if (e.getStatusCode() == 404) {
                    U.warn(log, "Bucket doesn't exist, will create it [bucketName=" + bucketName + "]");
                    createBucket = true;
                } else
                    throw new IgniteSpiException("Failed to open the bucket: " + bucketName, e);
            } catch (Exception e) {
                throw new IgniteSpiException("Failed to open the bucket: " + bucketName, e);
            }
            if (createBucket) {
                Bucket newBucket = new Bucket();
                newBucket.setName(bucketName);
                try {
                    Storage.Buckets.Insert insertBucket = storage.buckets().insert(projectName, newBucket);
                    insertBucket.setProjection("full");
                    insertBucket.setPredefinedDefaultObjectAcl("projectPrivate");
                    insertBucket.execute();
                } catch (Exception e) {
                    throw new IgniteSpiException("Failed to create the bucket: " + bucketName, e);
                }
            }
        } finally {
            initLatch.countDown();
        }
    } else {
        try {
            U.await(initLatch);
        } catch (IgniteInterruptedCheckedException e) {
            throw new IgniteSpiException("Thread has been interrupted.", e);
        }
        if (storage == null)
            throw new IgniteSpiException("IpFinder has not been initialized properly");
    }
}
Example 82
Project: iosched-2013-master  File: SyncHelper.java View source code
private Googledevelopers getConferenceAPIClient() {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new AndroidJsonFactory();
    GoogleCredential credential = new GoogleCredential().setAccessToken(AccountUtils.getAuthToken(mContext));
    //       ID normally embedded an an OAuth token. Most apps will use one or the other.
    return new Googledevelopers.Builder(httpTransport, jsonFactory, null).setApplicationName(NetUtils.getUserAgent(mContext)).setGoogleClientRequestInitializer(new CommonGoogleClientRequestInitializer(Config.API_KEY)).setHttpRequestInitializer(credential).build();
}
Example 83
Project: muikku-master  File: GoogleCalendarClient.java View source code
private GoogleCredential getServiceAccountCredential() throws GeneralSecurityException, IOException {
    String accountEmail = System.getProperty("muikku.googleServiceAccount.accountEmail");
    if (StringUtils.isBlank(accountEmail)) {
        throw new GeneralSecurityException("muikku.googleServiceAccount.accountEmail environment property is missing");
    }
    String accountUser = System.getProperty("muikku.googleServiceAccount.accountUser");
    if (StringUtils.isBlank(accountUser)) {
        throw new GeneralSecurityException("muikku.googleServiceAccount.accountUser environment property is missing");
    }
    String keyFilePath = System.getProperty("muikku.googleServiceAccount.keyFile");
    if (StringUtils.isBlank(keyFilePath)) {
        throw new GeneralSecurityException("muikku.googleServiceAccount.keyFile environment property is missing");
    }
    java.io.File keyFile = new java.io.File(keyFilePath);
    if (!keyFile.exists()) {
        throw new GeneralSecurityException("muikku.googleServiceAccount.keyFile environment property is pointing into non-existing file");
    }
    return new GoogleCredential.Builder().setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).setServiceAccountId(accountEmail).setServiceAccountScopes(Arrays.asList(CalendarScopes.CALENDAR)).setServiceAccountPrivateKeyFromP12File(keyFile).setServiceAccountUser(accountUser).build();
}
Example 84
Project: picketlink-master  File: GoogleProcessor.java View source code
public GoogleAccessTokenContext validateTokenAndUpdateScopes(GoogleAccessTokenContext accessTokenContext) throws SocialException {
    GoogleRequest<Tokeninfo> googleRequest = new GoogleRequest<Tokeninfo>() {

        @Override
        protected Tokeninfo invokeRequest(GoogleAccessTokenContext accessTokenContext) throws IOException {
            GoogleTokenResponse tokenData = accessTokenContext.getTokenData();
            Oauth2 oauth2 = getOAuth2Instance(accessTokenContext);
            GoogleCredential credential = getGoogleCredential(tokenData);
            return oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
        }

        @Override
        protected SocialException createException(IOException cause) {
            if (cause instanceof HttpResponseException) {
                return new SocialException(SocialExceptionCode.ACCESS_TOKEN_ERROR, "Error when obtaining tokenInfo: " + cause.getMessage(), cause);
            } else {
                return new SocialException(SocialExceptionCode.IO_ERROR, "IO Error when obtaining tokenInfo: " + cause.getMessage(), cause);
            }
        }
    };
    Tokeninfo tokenInfo = googleRequest.executeRequest(accessTokenContext, this);
    // If there was an error in the token info, abort.
    if (tokenInfo.containsKey(OAuthConstants.ERROR_PARAMETER)) {
        throw new SocialException(SocialExceptionCode.ACCESS_TOKEN_ERROR, "Error during token validation: " + tokenInfo.get("error").toString());
    }
    if (!tokenInfo.getIssuedTo().equals(clientID)) {
        throw new SocialException(SocialExceptionCode.ACCESS_TOKEN_ERROR, "Token's client ID does not match app's. clientID from tokenINFO: " + tokenInfo.getIssuedTo());
    }
    if (log.isTraceEnabled()) {
        log.trace("Successfully validated accessToken from google: " + tokenInfo);
    }
    return new GoogleAccessTokenContext(accessTokenContext.getTokenData(), tokenInfo.getScope());
}
Example 85
Project: rakam-master  File: WebUserHttpService.java View source code
@JsonRequest
@Path("/login_with_google")
public Response<WebUser> loginWithGoogle(@ApiParam("access_token") String accessToken) {
    GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
    Oauth2 oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName("Oauth2").build();
    Userinfoplus userinfo;
    try {
        userinfo = oauth2.userinfo().get().execute();
        if (!userinfo.getVerifiedEmail()) {
            throw new RakamException("The Google email must be verified", BAD_REQUEST);
        }
        Optional<WebUser> userByEmail = service.getUserByEmail(userinfo.getEmail());
        WebUser user = userByEmail.orElseGet(() -> service.createUser(userinfo.getEmail(), null, userinfo.getGivenName(), userinfo.getGender(), userinfo.getLocale(), userinfo.getId(), false));
        return getLoginResponseForUser(user);
    } catch (IOException e) {
        LOGGER.error(e);
        throw new RakamException("Unable to login", INTERNAL_SERVER_ERROR);
    }
}
Example 86
Project: SlideshowFX-master  File: DriveHostingConnector.java View source code
@Override
public boolean checkAccessToken() {
    boolean valid = false;
    if (this.credential == null) {
        this.credential = new GoogleCredential();
        this.credential.setAccessToken(this.accessToken);
    }
    Drive service = new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), this.credential).setApplicationName(APPLICATION_NAME).build();
    try {
        service.about().get().setFields("user, storageQuota").execute();
        valid = true;
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Can not determine if access token is valid", e);
    }
    return valid;
}
Example 87
Project: carbon-identity-master  File: GoogleProvisioningConnector.java View source code
/**
     * Build and returns a Directory service object authorized with the service accounts that act on
     * behalf of the given user.
     *
     * @return Directory service object that is ready to make requests.
     * @throws IdentityProvisioningException
     */
protected Directory getDirectoryService() throws IdentityProvisioningException {
    boolean isDebugEnabled = log.isDebugEnabled();
    if (isDebugEnabled) {
        log.debug("Starting getDirectoryService() of " + GoogleProvisioningConnector.class);
    }
    String serviceAccountEmailKey = "google_prov_service_acc_email";
    String adminEmailKey = "google_prov_admin_email";
    String privateKeyKey = "google_prov_private_key";
    String applicationNameKey = "google_prov_application_name";
    /** Email of the Service Account */
    String serviceAccountId = this.configHolder.getValue(serviceAccountEmailKey);
    /** Admin email */
    String serviceAccountUser = this.configHolder.getValue(adminEmailKey);
    /** Path to the Service Account's Private Key file */
    String serviceAccountPrivateKeyString = this.configHolder.getValue(privateKeyKey);
    /** Application name */
    String applicationName = this.configHolder.getValue(applicationNameKey);
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    if (isDebugEnabled) {
        log.debug("serviceAccountId" + serviceAccountId);
        log.debug("setServiceAccountScopes" + Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER));
        log.debug("setServiceAccountUser" + serviceAccountUser);
    }
    Directory service = null;
    try {
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId).setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER)).setServiceAccountUser(serviceAccountUser).setServiceAccountPrivateKeyFromP12File(googlePrvKey).build();
        service = new Directory.Builder(httpTransport, jsonFactory, credential).setHttpRequestInitializer(credential).setApplicationName(applicationName).build();
    } catch (GeneralSecurityExceptionIOException |  e) {
        throw new IdentityProvisioningException("Error while obtaining connection from google", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Ending getDirectoryService() of " + GoogleProvisioningConnector.class);
    }
    return service;
}
Example 88
Project: cloudsync-master  File: RemoteGoogleDriveConnector.java View source code
@Override
public void init(String backupName, CmdOptions options) throws CloudsyncException {
    RemoteGoogleDriveOptions googleDriveOptions = new RemoteGoogleDriveOptions(options, backupName);
    Integer history = options.getHistory();
    showProgress = options.showProgress();
    retries = options.getRetries();
    waitretry = options.getWaitRetry() * 1000;
    networkErrorBehavior = options.getNetworkErrorBehavior();
    charset = options.getCharset();
    cacheFiles = new HashMap<>();
    cacheParents = new HashMap<>();
    this.basePath = Helper.trim(googleDriveOptions.getClientBasePath(), SEPARATOR);
    this.backupName = backupName;
    this.historyCount = history;
    this.historyName = history > 0 ? backupName + " " + new SimpleDateFormat("yyyy.MM.dd_HH.mm.ss").format(new Date()) : null;
    final HttpTransport httpTransport = new NetHttpTransport();
    final JsonFactory jsonFactory = new JacksonFactory();
    if (StringUtils.isNotEmpty(googleDriveOptions.getServiceAccountUser())) {
        // Service Account auth - https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#service_accounts
        try {
            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(googleDriveOptions.getServiceAccountEmail()).setServiceAccountScopes(Collections.singletonList(DriveScopes.DRIVE)).setServiceAccountUser(googleDriveOptions.getServiceAccountUser()).setServiceAccountPrivateKeyFromP12File(new java.io.File(googleDriveOptions.getServiceAccountPrivateKeyP12Path())).build();
        } catch (GeneralSecurityExceptionIOException |  e) {
            throw new CloudsyncException("Can't init remote google drive connector", e);
        }
    } else {
        // Installed Applications auth - https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#installed_applications
        final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, googleDriveOptions.getClientID(), googleDriveOptions.getClientSecret(), Collections.singletonList(DriveScopes.DRIVE)).setAccessType("offline").setApprovalPrompt("auto").build();
        this.clientTokenPath = Paths.get(googleDriveOptions.getClientTokenPath());
        try {
            final String clientTokenAsJson = Files.exists(this.clientTokenPath) ? FileUtils.readFileToString(this.clientTokenPath.toFile(), charset) : null;
            credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()).setJsonFactory(new GsonFactory()).setClientSecrets(googleDriveOptions.getClientID(), googleDriveOptions.getClientSecret()).build();
            if (StringUtils.isEmpty(clientTokenAsJson)) {
                final String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URL).build();
                System.out.println("Please open the following URL in your browser, copy the authorization code and enter below.");
                System.out.println("\n" + url + "\n");
                final String code = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
                clientToken = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URL).execute();
                storeClientToken(jsonFactory);
                LOGGER.log(Level.INFO, "client token stored in '" + this.clientTokenPath + "'");
            } else {
                clientToken = jsonFactory.createJsonParser(clientTokenAsJson).parse(GoogleTokenResponse.class);
            }
            credential.setFromTokenResponse(clientToken);
        } catch (final IOException e) {
            throw new CloudsyncException("Can't init remote google drive connector", e);
        }
    }
}
Example 89
Project: CasserolesEnCours-master  File: CasserolesEnCoursActivity.java View source code
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
    //That ease dev of technical stuff BUT is not wanted on a mid/longer term
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    mTimeFilterSpinner = (Spinner) findViewById(R.id.timeFilterSpinner);
    mTimeFilterAdapter = ArrayAdapter.createFromResource(this, R.array.timeFilter_choices, android.R.layout.simple_spinner_item);
    mTimeFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mTimeFilterSpinner.setAdapter(mTimeFilterAdapter);
    mDistanceFilterSpinner = (Spinner) findViewById(R.id.distanceFilterSpinner);
    mDistanceFilterAdapter = ArrayAdapter.createFromResource(this, R.array.distanceFilter_choices, android.R.layout.simple_spinner_item);
    mDistanceFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mDistanceFilterSpinner.setAdapter(mDistanceFilterAdapter);
    mAloharAuthLayout = findViewById(R.id.auth_layout);
    mMainLayout = findViewById(R.id.main_layout);
    mProgress = findViewById(R.id.progress_spin);
    mAccountView = (TextView) findViewById(R.id.account);
    mMainHandler = new Handler();
    mStatusView = (TextView) findViewById(R.id.service_status);
    mServiceToggleButton = (ToggleButton) findViewById(R.id.toggle);
    mUIDView = (EditText) findViewById(R.id.uid);
    mNotificationManager = (NotificationManager) getSystemService(NOTIFIACTION_SERVICE_STRING);
    mAlohar = Alohar.init(getApplication());
    mPlaceManager = mAlohar.getPlaceManager();
    mMotionManager = mAlohar.getMotionManager();
    //mEventManager = EventsManager.getInstance();
    //register listener
    //mPlaceManager.registerPlaceEventListener(mEventManager);
    mMotionManager.registerMotionListener(this);
    //Alohar original, I'm testing the other one
    //mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    mAloharUid = mPrefs.getString(PREF_KEY, null);
    if (mAloharUid == null) {
        mAlohar.register(APP_ID, API_KEY, this);
    }
    mFusionTableEncID = mPrefs.getString(PREF_TABLE_ENCID, null);
    mRegisterRequestTableID = mPrefs.getString(PREF_REGREQUESTTABLE_ENCID, null);
    if (mRegisterRequestTableID == null) {
        ((Button) findViewById(R.id.refreshRegistration)).setEnabled(false);
    } else {
        ((Button) findViewById(R.id.refreshRegistration)).setEnabled(true);
        ((Button) findViewById(R.id.registerTable)).setEnabled(false);
    }
    mViewOnMasterID = mPrefs.getString(PREF_VIEWONMASTERTABLE_ENCID, null);
    if (mViewOnMasterID == null) {
        ((Button) findViewById(R.id.refreshRegistration)).setEnabled(true);
    } else {
        ((Button) findViewById(R.id.refreshRegistration)).setEnabled(false);
    }
    if (mAlohar.isServiceRunning()) {
        //findViewById(R.id.timeFilterSpinner).setClickable(true);
        mDistanceFilterSpinner.setEnabled(true);
    } else {
        //findViewById(R.id.timeFilterSpinner).setClickable(false);
        mDistanceFilterSpinner.setEnabled(false);
    }
    String tableStatus = mPrefs.getString(PREF_TABLE_STATUS, null);
    if (tableStatus == null) {
        tableStatus = getString(R.string.geolocationStatusRegRequired);
    //Setup interface
    //Done in XML file
    } else {
        //setup interface
        if (tableStatus.equals(getString(R.string.geolocationAnonymizePending))) {
            ((TextView) findViewById(R.id.geolocationStatus)).setTextColor(getResources().getColor(R.color.text_orange));
            ((TextView) findViewById(R.id.geolocationStatus)).setText(getString(R.string.geolocationAnonymizePending));
            ((Button) findViewById(R.id.registerAnonymize)).setVisibility(View.GONE);
            ((Button) findViewById(R.id.checkAnonymize)).setVisibility(View.VISIBLE);
        } else if (tableStatus.equals(getString(R.string.geolocationAnonymizeProcessed))) {
            ((TextView) findViewById(R.id.geolocationStatus)).setTextColor(getResources().getColor(R.color.text_green));
            ((TextView) findViewById(R.id.geolocationStatus)).setText(getString(R.string.geolocationAnonymizeProcessed));
            ((Button) findViewById(R.id.checkAnonymize)).setVisibility(View.GONE);
            ((Button) findViewById(R.id.registerAnonymize)).setVisibility(View.GONE);
            ((Button) findViewById(R.id.logWithGoogle)).setVisibility(View.GONE);
            ((Button) findViewById(R.id.toggleGeolocation)).setVisibility(View.VISIBLE);
            findViewById(R.id.geolocationServiceStatus).setVisibility(View.VISIBLE);
            findViewById(R.id.myDataCheckbox).setEnabled(true);
        } else if (tableStatus.equals(getString(R.string.geolocationStatusRegStart))) {
            findViewById(R.id.logWithGoogle).setVisibility(View.GONE);
            findViewById(R.id.registerAnonymize).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.geolocationStatus)).setTextColor(getResources().getColor(R.color.text_orange));
            ((TextView) findViewById(R.id.geolocationStatus)).setText(getString(R.string.geolocationStatusRegStart));
        }
    }
    ((TextView) findViewById(R.id.tableStatus)).setText(tableStatus);
    if (mAloharUid != null) {
        mUIDView.setText(String.valueOf(mAloharUid));
        onAuthenClick(mUIDView);
    } else {
        mAloharAuthLayout.setVisibility(View.VISIBLE);
    }
    mGOOGCredential = new GoogleCredential.Builder().setTransport(mNetHttpTransport).setJsonFactory(mJaksonJSONFactory//.build();
    ).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
    mGOOGCredential.setAccessToken(null);
    mGOOGCredential.setRefreshToken(mPrefs.getString(PREF_REFRESH_TOKEN, null));
    //Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
    Builder truc = GoogleClient.builder(mNetHttpTransport, mJaksonJSONFactory, new GenericUrl(SERVICE_URL));
    truc.setHttpRequestInitializer(mGOOGCredential);
    mGOOGClient = truc.build();
    mPollFrequencyText = (TextView) findViewById(R.id.pollFrequencyText);
    mPollFrequencyText.setText("N/A when stationary");
    //Something is wrong with the color, I'll see that cosmetic side later
    //mPollFrequencyText.setTextColor(R.color.text_violet);
    mLocationPollThreadExecutor.setKeepAliveTime(0, TimeUnit.SECONDS);
    RadioGroup pollFrequencyRadioGroup = (RadioGroup) findViewById(R.id.pollFrequencyRadioGroup);
    pollFrequencyRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            cancelActiveTasks();
            startTaskForId(checkedId, true);
        }
    });
    findViewById(R.id.frequency0).setEnabled(false);
    findViewById(R.id.frequency1).setEnabled(false);
    findViewById(R.id.frequency2).setEnabled(false);
    findViewById(R.id.frequency3).setEnabled(false);
}
Example 90
Project: drivemarks-master  File: CredentialManager.java View source code
/**
   * Builds an empty credential object.
   * @return An empty credential object.
   */
public Credential buildEmpty() {
    return new GoogleCredential.Builder().setClientSecrets(this.clientSecrets).setTransport(transport).setJsonFactory(jsonFactory).build();
}
Example 91
Project: s2ap-quickstart-java-master  File: WobCredentials.java View source code
/**
   * Helper function to generate the Google Credential
   *
   * @return
   * @throws GeneralSecurityException
   * @throws IOException
   */
private void generateGoogleCredential() {
    gCredential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId).setServiceAccountScopes(scopes).setServiceAccountPrivateKey(serviceAccountPrivateKey).build();
}
Example 92
Project: medsavant-master  File: GoogleAuthenticate.java View source code
private static GoogleCredential createCredentialWithRefreshToken(TokenResponse tokenResponse) {
    return new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setClientSecrets(clientSecrets).build().setFromTokenResponse(tokenResponse);
}
Example 93
Project: loli.io-master  File: GDriveAPI.java View source code
public static Credential tokenToCre(String accessToken, String refreshToken) {
    GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setAccessToken(accessToken).setRefreshToken(refreshToken);
    return credential;
}