Example usage for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport

List of usage examples for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport.

Prototype

public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException 

Source Link

Document

Returns a new instance of NetHttpTransport that uses GoogleUtils#getCertificateTrustStore() for the trusted certificates using com.google.api.client.http.javanet.NetHttpTransport.Builder#trustCertificates(KeyStore) .

Usage

From source file:org.ut.biolab.medsavant.app.google.original.GenomicsSample.java

License:Open Source License

public static void main(String[] args) {
    try {//from  w  w w. j  av a 2s  . c om
        createDotGoogleCloudDirectory();

        cmdLine = new CommandLine(args);

        // Show help
        assertOrDie(!cmdLine.showHelp(), "");

        // Make sure request_type is specified
        assertOrDie(cmdLine.remainingArgs.size() == 1, "Must specify a request_type\n");

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // Route to appropriate request method
        String requestType = cmdLine.remainingArgs.get(0);
        if (requestType.equals("help")) {
            cmdLine.printHelp("", System.err);
            return;
        } else if (requestType.equals("auth")) {
            deleteRefreshToken();
            authenticate();
            return;
        } else {
            Genomics genomics = buildService(authenticate());
            try {
                executeAndPrint(getRequest(cmdLine, genomics, requestType));
            } catch (IllegalArgumentException e) {
                cmdLine.printHelp(e.getMessage() + "\n", System.err);
                System.exit(0);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.wallride.service.BlogService.java

License:Apache License

@CacheEvict(value = WallRideCacheConfiguration.BLOG_CACHE, allEntries = true)
public GoogleAnalytics updateGoogleAnalytics(GoogleAnalyticsUpdateRequest request) {
    byte[] p12;//from ww  w.  j  ava2s  . com
    try {
        p12 = request.getServiceAccountP12File().getBytes();
    } catch (IOException e) {
        throw new ServiceException(e);
    }

    try {
        PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                new ByteArrayInputStream(p12), "notasecret", "privatekey", "notasecret");

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        // Build service account credential.
        Set<String> scopes = new HashSet<>();
        scopes.add(AnalyticsScopes.ANALYTICS_READONLY);

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(request.getServiceAccountId())
                .setServiceAccountScopes(scopes).setServiceAccountPrivateKey(privateKey).build();

        Analytics analytics = new Analytics.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("WallRide").build();

        GaData gaData = analytics.data().ga()
                .get(request.getProfileId(), "2005-01-01",
                        LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), "ga:pageviews")
                .setDimensions(String.format("ga:dimension%d", request.getCustomDimensionIndex()))
                .setMaxResults(1).execute();
        logger.debug("GaData: {}", gaData);
    } catch (GeneralSecurityException e) {
        throw new GoogleAnalyticsException(e);
    } catch (IOException e) {
        throw new GoogleAnalyticsException(e);
    }

    GoogleAnalytics googleAnalytics = new GoogleAnalytics();
    googleAnalytics.setTrackingId(request.getTrackingId());
    googleAnalytics.setProfileId(request.getProfileId());
    googleAnalytics.setCustomDimensionIndex(request.getCustomDimensionIndex());
    googleAnalytics.setServiceAccountId(request.getServiceAccountId());
    googleAnalytics.setServiceAccountP12FileName(request.getServiceAccountP12File().getOriginalFilename());
    googleAnalytics.setServiceAccountP12FileContent(p12);

    Blog blog = blogRepository.findOneForUpdateById(request.getBlogId());
    blog.setGoogleAnalytics(googleAnalytics);

    blog = blogRepository.saveAndFlush(blog);
    return blog.getGoogleAnalytics();
}

From source file:org.wallride.support.GoogleAnalyticsUtils.java

License:Apache License

public static Analytics buildClient(GoogleAnalytics googleAnalytics) {
    Analytics analytics;/*ww w .  ja v a 2s  .  co  m*/
    try {
        PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                new ByteArrayInputStream(googleAnalytics.getServiceAccountP12FileContent()), "notasecret",
                "privatekey", "notasecret");

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        Set<String> scopes = new HashSet<>();
        scopes.add(AnalyticsScopes.ANALYTICS_READONLY);

        final GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(googleAnalytics.getServiceAccountId())
                .setServiceAccountScopes(scopes).setServiceAccountPrivateKey(privateKey).build();

        HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest httpRequest) throws IOException {
                credential.initialize(httpRequest);
                httpRequest.setConnectTimeout(3 * 60000); // 3 minutes connect timeout
                httpRequest.setReadTimeout(3 * 60000); // 3 minutes read timeout
            }
        };
        analytics = new Analytics.Builder(httpTransport, jsonFactory, httpRequestInitializer)
                .setApplicationName("WallRide").build();
    } catch (Exception e) {
        logger.warn("Failed to synchronize with Google Analytics", e);
        throw new GoogleAnalyticsException(e);
    }

    return analytics;
}

From source file:orientan.OAuth.OAuth.java

public OAuth() {
    try {/*from w w w .j av a2  s  .  c  om*/
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        // authorization
        Credential credential = authorize();
        // set up global Oauth2 instance
        oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
        // run commands
        tokenInfo(credential.getAccessToken());
        userInfo();
        header("Obtaining User Profile Information");
        Userinfoplus userinfo = oauth2.userinfo().get().execute();
        System.out.println("*********************" + userinfo.getId());

        // success!
        return;
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:raspi_ui.backend.calendar.CalendarData.java

License:Apache License

public static void main(String[] args) {
    try {/*from  w  w  w  .  java 2  s. co  m*/
        // initialize the transport
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // initialize the data store factory
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        System.out.println("DatastoreDir: -------------------------------------------");
        System.out.println(DATA_STORE_DIR);

        // authorization
        Credential credential = authorize();

        // set up global CalendarData instance
        client = new com.google.api.services.calendar.Calendar.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        // run commands
        //showCalendars();

    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    //System.exit(1);
}

From source file:remotedrive.client.googledrive.GoogleDriveClient.java

License:Open Source License

/**
 * Authenticates to Google Drive account.
 * @param username The google account email address.
 * @param password Always empty for google drive authentication
 *///  ww  w.ja  va  2s.  c  om
public void authenticate(String username, char[] password) {
    // Arguments validation
    if (null == username || username.length() == 0) {
        throw new IllegalArgumentException("Username has to be provided");
    }

    try {
        // Initialize internal state
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        // Initialize the client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory,
                new InputStreamReader(GoogleDriveClient.class.getResourceAsStream("/client_secrets.json")));

        // Initialize authorization flow
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
                clientSecrets, Arrays.asList(DriveScopes.DRIVE))
                        .setDataStoreFactory(new FileDataStoreFactory(
                                new java.io.File(System.getProperty("user.home"), ".store/cloud_storage")))
                        .setApprovalPrompt("auto").setAccessType("offline").build();

        // Initialize the credentials for installed application
        credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(username);

        // Initialize the drive service
        driveService = new com.google.api.services.drive.Drive.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("CloudStorage").build();

        // Retrieve about resource in order to initialize disk information
        com.google.api.services.drive.Drive.About.Get get = driveService.about().get();
        About about = get.execute();

        // Add root in the FS index
        pathsToIdsIndex.put("", about.getRootFolderId());

        // Initialize disk information
        drive = new Drive(about.getQuotaBytesTotal(), about.getQuotaBytesUsed());
    } catch (Exception e) {
        throw new ClientAuthenticationException(String.format("Unable to authentication as %s", username), e);
    }
}

From source file:ru.caramel.juniperbot.module.social.service.impl.YouTubeServiceImpl.java

License:Open Source License

@PostConstruct
public void init() {
    try {//from w  w w.  j a v  a2 s .  c o m
        youTube = new YouTube.Builder(GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(), e -> {
                }).setApplicationName(YouTubeServiceImpl.class.getSimpleName()).build();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:ru.tiis.library.service.impl.GDriveService.java

License:Apache License

private static void init() {
    try {/*  www  . j a  v a2s  . c o m*/
        if (null == httpTransport) {
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        }
        if (null == dataStoreFactory) {
            dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        }
    } catch (GeneralSecurityException | IOException e) {
        log.error(e);
    }
}

From source file:ru.tmin10.fitTest.OAuth2Sample.java

License:Apache License

public static void main(String[] args) {
    try {/*from w  w  w. j  av  a 2 s  . co  m*/
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        // authorization
        Credential credential = authorize();
        // set up global Oauth2 instance
        oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
        // run commands
        tokenInfo(credential.getAccessToken());
        //userInfo();
        // success!

        Fitness f = new Fitness(httpTransport, JSON_FACTORY, credential);
        //      Fitness.Users.DataSources.List r = f.users().dataSources().list("me");
        //      ListDataSourcesResponse l = r.execute();
        //      List<DataSource> list = l.getDataSource();
        //      for (int i = 0; i < list.size(); i++)
        //      {
        //         System.out.println(list.get(i).getDataStreamId());
        //      }

        //      Get g = f.users().dataSources().datasets().get("me", "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps", getNow()+"-"+getDayStart());
        //      Dataset d = g.execute();    
        //      System.out.println(d.toPrettyString());

        AggregateRequest content = new AggregateRequest();
        content.setStartTimeMillis(getDayStartMillis());
        content.setEndTimeMillis(getNowMillis());
        ArrayList<AggregateBy> aggregatebyList = new ArrayList<AggregateBy>();
        AggregateBy agby = new AggregateBy();
        agby.setDataSourceId("derived:com.google.step_count.delta:com.google.android.gms:estimated_steps");
        aggregatebyList.add(agby);
        content.setAggregateBy(aggregatebyList);
        BucketByTime bucketByTime = new BucketByTime();
        bucketByTime.setDurationMillis((long) (1000 * 60 * 60));
        content.setBucketByTime(bucketByTime);
        Aggregate agg = f.users().dataset().aggregate("me", content);
        AggregateResponse resp = agg.execute();
        System.out.println(resp.toPrettyString());

        List<AggregateBucket> results = resp.getBucket();
        for (int i = 0; i < results.size(); i++) {
            List<Dataset> ds = results.get(i).getDataset();
            for (int j = 0; j < ds.size(); j++) {
                List<DataPoint> dp = ds.get(j).getPoint();
                for (int k = 0; k < dp.size(); k++) {
                    List<Value> v = dp.get(k).getValue();
                    for (int x = 0; x < v.size(); x++) {
                        System.out.println(v.get(x).getIntVal());

                    }
                }
            }
        }

        return;
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:sciuto.corey.alerter.drive.google.GoogleDriveWrapper.java

License:Apache License

/**
 * Creates the Google Drive client. Pass in the pointer to
 * clients_secret.json.//  ww w. j  av a2s  .  c o  m
 * 
 * @see https://developers.google.com/identity/protocols/OAuth2
 * 
 * @param secretsLocation
 * @return
 * @throws IOException
 * @throws GeneralSecurityException 
 */
public GoogleDriveWrapper(String secretsLocation) throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    File dataStoreDirectory = new File("dataStore/");
    dataStoreDirectory.mkdir();
    FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(dataStoreDirectory);
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(secretsLocation));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setDataStoreFactory(dataStoreFactory)
                    .build();

    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("CoreySciuto-Alerter/0.1").build();
    this.drive = drive;
}