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

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

Introduction

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

Prototype

public static GoogleClientSecrets load(JsonFactory jsonFactory, Reader reader) throws IOException 

Source Link

Document

Loads the client_secrets.json file from the given reader.

Usage

From source file:io.github.lal872k.monotifier.GDrive.java

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException/*w  ww . j av  a 2  s  .  c om*/
 */
private static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GDrive.class.getResourceAsStream("client_secret.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

From source file:io.github.lal872k.monotifier.GMail.java

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException//from w  w w  .  j av a  2s .co  m
 */
private static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GMail.class.getResourceAsStream("client_secret.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

From source file:io.github.nathanross.listupload.GroupsMigrationBackend.java

License:Apache License

private static Credential authorize() throws Exception {

    Vector<String> scopes = new Vector<String>();
    scopes.add("https://www.googleapis.com/auth/apps.groups.migration");
    // load client secrets
    clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(new FileInputStream(new File(CLIENT_SECRETS_FNAME))));
    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/ "
                + "into oauth2-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);//from  www .j a  v a2  s  . c  o  m
    }
    // set up authorization code flow
    Builder builder = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets,
            scopes);
    GoogleAuthorizationCodeFlow flow = builder.setDataStoreFactory(dataStoreFactory).build();
    // authorize
    LocalServerReceiver lsreceiver = new LocalServerReceiver();
    AuthorizationCodeInstalledApp d = new AuthorizationCodeInstalledApp(flow, lsreceiver);
    Credential e = d.authorize(APPS_ADMIN_EMAIL);
    return e;
}

From source file:io.konig.maven.google.download.GoogleDownloadClient.java

License:Apache License

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException/*from  w  w  w .  ja v  a2s.c om*/
 */
private Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GoogleDownloadClient.class.getResourceAsStream("/GoogleDownloadClient/clientInfo.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("user");
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

From source file:io.mapping.api.billsplit.guice.BillSplitServletModule.java

License:Apache License

@Provides
@Singleton//from  w  w  w  .  j  a  v  a  2 s  . c  o m
GoogleClientSecrets provideGoogleClientSecrets() {
    GoogleClientSecrets googleClientSecrets = null;

    try {
        Reader reader = new InputStreamReader(this.getClass().getResourceAsStream(FILE_GOOGLE_OAUTH));
        googleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, reader);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return googleClientSecrets;
}

From source file:it.micheleorsi.drive.samples.dredit.CredentialMediator.java

License:Apache License

/**
 * Creates a new CredentialsManager for the given HTTP request.
 *
 * @param request Request in which session credentials are stored.
 * @param clientSecretsStream Stream of client_secrets.json.
 *///from   w w  w  .  ja va2 s  .c o m
public CredentialMediator(HttpServletRequest request, InputStream clientSecretsStream,
        Collection<String> scopes) {
    this.request = request;
    this.scopes = scopes;
    this.credentialStore = new AppEngineCredentialStore();
    try {
        secrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretsStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:javamailclient.GmailAPI.java

public static void initialize(String code) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Arrays.asList(SCOPE)).setAccessType("online").setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
    //System.out.println("Please open the following URL in your browser then type"+" the authorization code:\n" + url);

    // Read code entered by user.
    //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //String code = br.readLine();

    // Generate Credential using retrieved code.
    GoogleTokenResponse response = flow.newTokenRequest(code)
            .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    // Create a new authorized Gmail API client
    service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).build();

    Profile profile = service.users().getProfile(USER).execute();
    USER_EMAIL = profile.getEmailAddress();
    System.out.println(USER_EMAIL);
    /*ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute();
    List<Thread> threads = threadsResponse.getThreads();
            //w  w  w.  j  ava  2s .  c  o  m
    // Print ID of each Thread.
    for (Thread thread : threads) {
      System.out.println("Thread ID: " + thread.getId());
    }*/
}

From source file:me.emily.config.PlusConfig.java

License:Apache License

@Override
protected void configure() {

    TypeLiteral<Function<String, String>> literal = new TypeLiteral<Function<String, String>>() {
    };/*from ww w. j a v  a2  s  . com*/

    final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    final GsonFactory jsonFactory = new GsonFactory();
    final NetHttpTransport transport = new NetHttpTransport();
    bind(Gson.class).toInstance(gson);
    bind(JsonFactory.class).toInstance(jsonFactory);
    bind(HttpTransport.class).toInstance(transport);

    final Urlshortener shortener = new Urlshortener.Builder(transport, jsonFactory, null).build();

    bind(literal).annotatedWith(Names.named("shortner")).toInstance(new Function<String, String>() {

        @Override
        public String apply(String input) {
            try {
                return shortener.url().insert(new Url().setLongUrl(input)).execute().getId();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return input;
            }
        }

    });

    bind(GoogleClientSecrets.class).toProvider(new Provider<GoogleClientSecrets>() {

        @Override
        public GoogleClientSecrets get() {
            try {
                File secrets = new File(Context.get(Context.contextDirectory), "client-secrets.json");
                log.warn("Loading secrets from {}", secrets.getAbsolutePath());

                return GoogleClientSecrets.load(jsonFactory, new FileInputStream(secrets));

            } catch (Exception e) {
                Throwables.propagate(e);
                return null;
            }
        }

    });

    bind(CredentialStore.class).toInstance(new CredentialStore() {

        Cache<String, SerializableCredentials> cache = CacheBuilder.newBuilder()
                .expireAfterAccess(300, TimeUnit.SECONDS).build();

        File directory = new File(Context.get(Context.contextDirectory), "/creds");

        {
            directory.mkdir();
        }

        @Override
        public void store(String userId, Credential credential) throws IOException {
            SerializableCredentials permCreds = new SerializableCredentials(credential);
            cache.put(userId, permCreds);
            Files.write(gson.toJson(permCreds), credFile(userId), Charsets.UTF_8);
        }

        @Override
        public boolean load(String userId, Credential credential) throws IOException {
            SerializableCredentials cred = cache.getIfPresent(userId);
            if (cred != null) {
                cred.push(credential);
                return true;
            }

            cred = loadFromDisc(userId);
            if (cred != null) {
                cred.push(credential);
                cache.put(userId, cred);
                return true;
            }
            return false;
        }

        private SerializableCredentials loadFromDisc(String userId)
                throws JsonSyntaxException, JsonIOException, FileNotFoundException {

            File credfile = credFile(userId);
            if (credfile.exists()) {
                return gson.fromJson(new FileReader(credfile), SerializableCredentials.class);
            }

            return null;
        }

        @Override
        public void delete(String userId, Credential credential) throws IOException {
            cache.invalidate(userId);

            File credFile = credFile(userId);
            if (credFile.exists()) {
                credFile.delete();
            }

        }

        private File credFile(String userId) {
            return new File(directory, userId.replaceAll("(\\|/)", ".") + ".cred.json");
        }

    });

    bind(OAuth2Native.class).asEagerSingleton();

}

From source file:me.tango.devops.google.CredentialsManager.java

License:Apache License

/**
 * Authorizes the installed application to access user's protected data.
 *//*from   w  ww . j  a va  2 s.  c  o  m*/
public static Credential authorize() throws IOException {
    // Load client secrets.
    final byte[] bytes = Files.toByteArray(new File(clientSecretFile));
    final GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(new ByteArrayInputStream(bytes)));
    if (clientSecrets.getDetails().getClientId() == null
            || clientSecrets.getDetails().getClientSecret() == null) {
        throw new IllegalStateException("client_secrets not well formed.");
    }

    // Set up authorization code flow.
    // Ask for only the permissions you need. Asking for more permissions will
    // reduce the number of users who finish the process for giving you access
    // to their accounts. It will also increase the amount of effort you will
    // have to spend explaining to users what you are doing with their data.
    // Here we are listing all of the available scopes. You should remove scopes
    // that you are not actually using.
    final Set<String> scopes = new HashSet<String>();
    scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
    scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
    scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);

    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
            JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    // Authorize.
    final VerificationCodeReceiver receiver = AUTH_LOCAL_WEBSERVER ? new LocalServerReceiver()
            : new GooglePromptReceiver();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}

From source file:messenger.CalendarSample.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,
            new FileInputStream("client_secrets.json_futuresbot"));
    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);//from  ww w .j a v  a  2  s  . c  o  m
    }
    // set up file credential store
    FileCredentialStore credentialStore = new FileCredentialStore(new File("calendar.json_futuresbot"),
            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");
}