List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets load
public static GoogleClientSecrets load(JsonFactory jsonFactory, Reader reader) throws IOException
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 {// w ww .j ava2 s . co 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.dataconservancy.dcs.access.server.GoogleAuthHelper.java
License:Apache License
private void loadClientSecrets() throws IOException { clientSecrets = GoogleClientSecrets.load(new JacksonFactory(), getClass().getResourceAsStream("../../../../../client_secret.json")); }
From source file:org.dishevelled.variation.googlegenomics.GoogleGenomicsFactory.java
License:Open Source License
GoogleClientSecrets createGoogleClientSecrets(final JsonFactory jsonFactory, final String resourceName) { try {//from ww w . j a v a 2s .c om return GoogleClientSecrets.load(jsonFactory, new InputStreamReader(getClass().getResourceAsStream(resourceName))); } catch (IOException e) { logger.error("unable to load client secrets", e); throw new RuntimeException("unable to load client secrets", e); } }
From source file:org.drivemarks.web.BaseServlet.java
License:Apache License
/** * Reads client_secrets.json and creates a GoogleClientSecrets object. * @return A GoogleClientsSecrets object. *//* w w w.j a v a2 s. c om*/ private GoogleClientSecrets getClientSecrets() { if (googleClientSecrets == null) { InputStream stream = getServletContext().getResourceAsStream(CLIENT_SECRETS_FILE_PATH); try { googleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, stream); } catch (IOException e) { throw new RuntimeException("No client_secrets.json found"); } } return googleClientSecrets; }
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//from w ww . j a v a 2s . com return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:org.esn.esobase.data.GoogleDocsService.java
private static Credential authorize2() 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_949902383727-vijtpirvq0i6q4lnsua6bn44v9441dpa.apps.googleusercontent.com.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/*from w ww .j a v a 2 s .c o m*/ return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:org.excalibur.driver.google.compute.GoogleCompute.java
License:Open Source License
private Credential authorize() throws IOException, GeneralSecurityException { PrivateKey securityKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), ClassUtils.getDefaultClassLoader() .getResourceAsStream(credentials_.getLoginCredentials().getCredential()), "notasecret", "privatekey", "notasecret"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new FileReader(new File(SystemUtils2.getApplicationDataPath(), credentials_.getLoginCredentials().getIdentity()))); GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId((String) clientSecrets.getWeb().get("client_email")) .setServiceAccountScopes(//from w w w . j a v a 2s.c o m Arrays.asList(ComputeScopes.COMPUTE, ComputeScopes.DEVSTORAGE_FULL_CONTROL)) .setServiceAccountPrivateKey(securityKey).build(); return credential; }
From source file:org.forgerock.openicf.connectors.googleapps.Main.java
License:Open Source License
static Map<String, Object> getConfigurationMap(File clientJson) throws IOException, URISyntaxException { System.setProperty("https.protocols", "TLSv1.2"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new FileReader(clientJson)); Credential credential = new AuthorizationCodeInstalledApp( new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setAccessType("offline").setApprovalPrompt("force") .setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build(), new AbstractPromptReceiver() { @Override//from w w w . j av a2 s . co m public String getRedirectUri() throws IOException { return GoogleOAuthConstants.OOB_REDIRECT_URI; } }).authorize("user"); Map<String, Object> configMap = new LinkedHashMap<String, Object>(3); configMap.put("clientId", clientSecrets.getDetails().getClientId()); configMap.put("clientSecret", clientSecrets.getDetails().getClientSecret()); configMap.put("refreshToken", credential.getRefreshToken()); return configMap; }
From source file:org.gcaldaemon.core.GCalUtilitiesV3.java
License:Apache License
private static Credential authorize() throws Exception { // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader( ClassLoader.getSystemClassLoader().getResourceAsStream("client_secrets.json"))); if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar " + "into calendar-cmdline-sample/src/main/resources/client_secrets.json"); System.exit(1);/*w w w . j a v a2s .c o m*/ } // set up authorization code flow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory) .build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:org.iminer.components.publication.pdf.GoogleClient.java
License:Apache License
/** Authorizes the installed application to access user's protected data. */ private static Credential authorize() throws Exception { // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, GoogleClient.class.getResourceAsStream("/client_secrets.json")); if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar " + "into calendar-cmdline-sample/src/main/resources/client_secrets.json"); System.exit(1);// w ww . j a v a 2 s. co m } // set up file credential store FileCredentialStore credentialStore = new FileCredentialStore(new File( "E:\\My Projects\\Google\\api-sample\\google-api-java-client-samples\\calendar-cmdline-sample", ".credentials/calendar.json"), JSON_FACTORY); // set up authorization code flow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).setCredentialStore(credentialStore) .build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }