List of usage examples for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport
public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException
From source file:org.argrr.extractor.gdrive.downloader.DriveApi.java
License:Open Source License
public static Drive getConnection() { if (DriveApi.drive != null) { return DriveApi.drive; }/*from w w w . j a v a 2 s . c o m*/ try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // authorization final Credential credential = authorize(); // set up the global Drive instance drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(Config.getVar("DRIVE_APP_NAME")) .setHttpRequestInitializer(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 } }).build(); } catch (GeneralSecurityException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } return drive; }
From source file:org.blom.martin.stream2gdrive.Stream2GDrive.java
License:Apache License
public static void main(String[] args) throws Exception { Options opt = new Options(); opt.addOption("?", "help", false, "Show usage."); opt.addOption("V", "version", false, "Print version information."); opt.addOption("v", "verbose", false, "Display progress status."); opt.addOption("p", "parent", true, "Operate inside this Google Drive folder instead of root."); opt.addOption("o", "output", true, "Override output/destination file name"); opt.addOption("m", "mime", true, "Override guessed MIME type."); opt.addOption("C", "chunk-size", true, "Set transfer chunk size, in MiB. Default is 10.0 MiB."); opt.addOption("r", "auto-retry", false, "Enable automatic retry with exponential backoff in case of error."); opt.addOption(null, "oob", false, "Provide OAuth authentication out-of-band."); try {//from w w w.ja v a 2 s .c o m CommandLine cmd = new GnuParser().parse(opt, args, false); args = cmd.getArgs(); if (cmd.hasOption("version")) { String version = "?"; String date = "?"; try { Properties props = new Properties(); props.load(resource("/build.properties")); version = props.getProperty("version", "?"); date = props.getProperty("date", "?"); } catch (Exception ignored) { } System.err.println(String.format("%s %s. Build %s (%s)", APP_NAME, APP_VERSION, version, date)); System.err.println(); } if (cmd.hasOption("help")) { throw new ParseException(null); } if (args.length < 1) { if (cmd.hasOption("version")) { return; } else { throw new ParseException("<cmd> missing"); } } String command = args[0]; JsonFactory jf = JacksonFactory.getDefaultInstance(); HttpTransport ht = GoogleNetHttpTransport.newTrustedTransport(); GoogleClientSecrets gcs = GoogleClientSecrets.load(jf, resource("/client_secrets.json")); Set<String> scopes = new HashSet<String>(); scopes.add(DriveScopes.DRIVE_FILE); scopes.add(DriveScopes.DRIVE_METADATA_READONLY); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(ht, jf, gcs, scopes) .setDataStoreFactory(new FileDataStoreFactory(appDataDir())).build(); VerificationCodeReceiver vcr = !cmd.hasOption("oob") ? new LocalServerReceiver() : new GooglePromptReceiver(); Credential creds = new AuthorizationCodeInstalledApp(flow, vcr).authorize("user"); List<HttpRequestInitializer> hrilist = new ArrayList<HttpRequestInitializer>(); hrilist.add(creds); if (cmd.hasOption("auto-retry")) { ExponentialBackOff.Builder backoffBuilder = new ExponentialBackOff.Builder() .setInitialIntervalMillis(6 * 1000) // 6 seconds initial retry period .setMaxElapsedTimeMillis(45 * 60 * 1000) // 45 minutes maximum total wait time .setMaxIntervalMillis(15 * 60 * 1000) // 15 minute maximum interval .setMultiplier(1.85).setRandomizationFactor(0.5); // Expected total waiting time before giving up = sum([6*1.85^i for i in range(10)]) // ~= 55 minutes // Note that Google API's HttpRequest allows for up to 10 retry. hrilist.add(new ExponentialBackOffHttpRequestInitializer(backoffBuilder)); } HttpRequestInitializerStacker hristack = new HttpRequestInitializerStacker(hrilist); Drive client = new Drive.Builder(ht, jf, hristack).setApplicationName(APP_NAME + "/" + APP_VERSION) .build(); boolean verbose = cmd.hasOption("verbose"); float chunkSize = Float.parseFloat(cmd.getOptionValue("chunk-size", "10.0")); String root = null; if (cmd.hasOption("parent")) { root = findWorkingDirectory(client, cmd.getOptionValue("parent")); } if (command.equals("get")) { String file; if (args.length < 2) { throw new ParseException("<file> missing"); } else if (args.length == 2) { file = args[1]; } else { throw new ParseException("Too many arguments"); } download(client, ht, root, file, cmd.getOptionValue("output", file), verbose, chunkSize); } else if (command.equals("put")) { String file; if (args.length < 2) { throw new ParseException("<file> missing"); } else if (args.length == 2) { file = args[1]; } else { throw new ParseException("Too many arguments"); } upload(client, file, root, cmd.getOptionValue("output", new File(file).getName()), cmd.getOptionValue("mime", new javax.activation.MimetypesFileTypeMap().getContentType(file)), verbose, chunkSize); } else if (command.equals("trash")) { String file; if (args.length < 2) { throw new ParseException("<file> missing"); } else if (args.length == 2) { file = args[1]; } else { throw new ParseException("Too many arguments"); } trash(client, root, file); } else if (command.equals("md5") || command.equals("list")) { if (args.length > 1) { throw new ParseException("Too many arguments"); } list(client, root, command.equals("md5")); } else { throw new ParseException("Invalid command: " + command); } } catch (ParseException ex) { PrintWriter pw = new PrintWriter(System.err); HelpFormatter hf = new HelpFormatter(); hf.printHelp(pw, 80, "stream2gdrive [OPTIONS] <cmd> [<options>]", " Commands: get <file>, list, md5, put <file>, trash <file>.", opt, 2, 8, "Use '-' as <file> for standard input."); if (ex.getMessage() != null && !ex.getMessage().isEmpty()) { pw.println(); hf.printWrapped(pw, 80, String.format("Error: %s.", ex.getMessage())); } pw.flush(); System.exit(EX_USAGE); } catch (NumberFormatException ex) { System.err.println("Invalid decimal number: " + ex.getMessage() + "."); System.exit(EX_USAGE); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage() + "."); System.exit(EX_IOERR); } }
From source file:org.codelibs.fess.score.GoogleAnalyticsScoreBooster.java
License:Apache License
private AnalyticsReporting initializeAnalyticsReporting() { try {//w ww . jav a 2s.com final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); final GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountEmail) .setServiceAccountPrivateKeyFromP12File(new File(keyFileLocation)) .setServiceAccountScopes(AnalyticsReportingScopes.all()).build(); return new AnalyticsReporting.Builder(httpTransport, jsonFactory, credential) .setApplicationName(applicationName).build(); } catch (final Exception e) { throw new FessSystemException("Failed to initialize GA.", e); } }
From source file:org.ctoolkit.restapi.client.adapter.GoogleApiProxyFactory.java
License:Open Source License
/** * Returns singleton instance of the HTTP transport. * * @return the reusable {@link HttpTransport} instance *//*w ww . j a va 2 s .c om*/ public final HttpTransport getHttpTransport() throws GeneralSecurityException, IOException { if (httpTransport == null) { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); } return httpTransport; }
From source file:org.dishevelled.variation.googlegenomics.GoogleGenomicsFactory.java
License:Open Source License
NetHttpTransport createNetHttpTransport() { try {/* w w w. j a v a2 s . c o m*/ return GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException e) { logger.error("unable to create HTTP transport", e); throw new RuntimeException("unable to create HTTP transport", e); } catch (IOException e) { logger.error("unable to create HTTP transport", e); throw new RuntimeException("unable to create HTTP transport", e); } }
From source file:org.dspace.google.GoogleAccount.java
License:BSD License
private GoogleAccount() { applicationName = new DSpace().getConfigurationService().getProperty("google-analytics.application.name"); tableId = new DSpace().getConfigurationService().getProperty("google-analytics.table.id"); emailAddress = new DSpace().getConfigurationService().getProperty("google-analytics.account.email"); certificateLocation = new DSpace().getConfigurationService() .getProperty("google-analytics.certificate.location"); jsonFactory = JacksonFactory.getDefaultInstance(); try {/* w w w.j a v a2 s. c om*/ httpTransport = GoogleNetHttpTransport.newTrustedTransport(); credential = authorize(); } catch (Exception e) { throw new RuntimeException("Error initialising Google Analytics client", e); } // Create an Analytics instance client = new Analytics.Builder(httpTransport, jsonFactory, credential).setApplicationName(applicationName) .build(); log.info("Google Analytics client successfully initialised"); }
From source file:org.elasticsearch.cloud.gce.GceComputeServiceImpl.java
License:Apache License
public synchronized Compute client() { if (refreshInterval != null && refreshInterval.millis() != 0) { if (client != null && (refreshInterval.millis() < 0 || (System.currentTimeMillis() - lastRefresh) < refreshInterval.millis())) { if (logger.isTraceEnabled()) logger.trace("using cache to retrieve client"); return client; }/*from w w w . j a v a 2 s.c om*/ lastRefresh = System.currentTimeMillis(); } try { HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); JSON_FACTORY = new JacksonFactory(); logger.info("starting GCE discovery service"); ComputeCredential credential = new ComputeCredential.Builder(HTTP_TRANSPORT, JSON_FACTORY) .setTokenServerEncodedUrl(TOKEN_SERVER_ENCODED_URL).build(); credential.refreshToken(); logger.debug("token [{}] will expire in [{}] s", credential.getAccessToken(), credential.getExpiresInSeconds()); refreshInterval = TimeValue.timeValueSeconds(credential.getExpiresInSeconds() - 1); // Once done, let's use this token this.client = new Compute.Builder(HTTP_TRANSPORT, JSON_FACTORY, null).setApplicationName(Fields.VERSION) .setHttpRequestInitializer(credential).build(); } catch (Exception e) { logger.warn("unable to start GCE discovery service: {} : {}", e.getClass().getName(), e.getMessage()); throw new DiscoveryException("unable to start GCE discovery service", e); } return this.client; }
From source file:org.elasticsearch.cloud.gce.GceInstancesServiceImpl.java
License:Apache License
protected synchronized HttpTransport getGceHttpTransport() throws GeneralSecurityException, IOException { if (gceHttpTransport == null) { if (validateCerts) { gceHttpTransport = GoogleNetHttpTransport.newTrustedTransport(); } else {/*from ww w . ja v a2 s .c om*/ // this is only used for testing - alternative we could use the defaul keystore but this requires special configs too.. gceHttpTransport = new NetHttpTransport.Builder().doNotValidateCertificate().build(); } } return gceHttpTransport; }
From source file:org.elasticsearch.cloud.gce.GceMetadataService.java
License:Apache License
protected synchronized HttpTransport getGceHttpTransport() throws GeneralSecurityException, IOException { if (gceHttpTransport == null) { gceHttpTransport = GoogleNetHttpTransport.newTrustedTransport(); }/*w w w . j a v a 2s. c o m*/ return gceHttpTransport; }
From source file:org.esn.esobase.data.GoogleDocsService.java
private static Credential authorize() throws Exception { // load client secrets FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File("/home/scraelos/")); NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream( "/home/scraelos/client_secret_218230677489-0f8al27el5nvfc6iguhrlop2c17oqf6r.apps.googleusercontent.com.1.json"))); // set up authorization code flow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, Collections.singleton("https://spreadsheets.google.com/feeds")) .setAccessType("offline").setDataStoreFactory(dataStoreFactory).build(); // authorize//www. j ava 2s . c o m return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }