Java Code Examples for com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp

The following are top voted examples for showing how to use com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: youtube-chat-for-minecraft   File: Auth.java   View source code 10 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param scopes list of scopes needed to run youtube upload.
 * @param clientSecret the client secret from Google API console
 * @param credentialDatastore name of the credential datastore to cache OAuth tokens
 */
public static Credential authorize(
    Collection<String> scopes, String clientSecret, String credentialDatastore)
    throws IOException {
  // Load client secrets
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(JSON_FACTORY, new StringReader(clientSecret));

  // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
  FileDataStoreFactory fileDataStoreFactory =
      new FileDataStoreFactory(new File(getCredentialsDirectory()));
  DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
          .setCredentialDataStore(datastore)
          .build();

  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 2
Project: ProjectAltaria   File: GoogleClientServiceFactory.java   View source code 7 votes vote down vote up
public final Credential getCredential() {
    if (googleCredential == null) {
        try {
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                    secureHttpTransport,
                    JacksonFactory.getDefaultInstance(),
                    googleSecrets,
                    requiredScopes)

                    .setAccessType("offline")
                    .setDataStoreFactory(new MemoryDataStoreFactory())
                    .build();

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

        } catch (IOException e) {
            //Will not occur
            logger.fatal(e);
            throw new RuntimeException();
        }
    }
    return googleCredential;
}
 
Example 3
Project: gdx-gamesvcs   File: GApiGateway.java   View source code 7 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 */
public static void authorize(String userID, boolean driveAPI) throws IOException {
    // load client secrets

    // set up authorization code flow
    Collection<String> scopes = new ArrayList<String>();
    scopes.add(GamesScopes.GAMES);
    if (driveAPI)
        scopes.add(DriveScopes.DRIVE_APPDATA);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    // authorize
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) {
        // Override open browser not working well on Linux and maybe other
        // OS.
        protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws java.io.IOException {
            Gdx.net.openURI(authorizationUrl.build());
        }
    }.authorize(userID);

    games = new Games.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();
    if (driveAPI)
        drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();

}
 
Example 4
Project: joanne   File: Authorization.java   View source code 7 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static void authorize() throws IOException {
    // Load client secrets.
    InputStream in = Authorization.class.getClass().getResourceAsStream("/gallery/configs/client_id.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(NICK);
    
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    MAIN = credential;
}
 
Example 5
Project: Thesis-JHipster   File: SpreadsheetUtils.java   View source code 7 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws Exception 
 */
public static Credential authorize() throws Exception {
	// Load client secrets.
	InputStream in =
			SpreadsheetUtils.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;
}
 
Example 6
Project: desktop-gmail-client   File: Login.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
            Login.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;
}
 
Example 7
Project: REST-Web-Services   File: GoogleStorageServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws ResourceServerException Incorrect authorization
 */
public static Credential authorize() {
    // Load client secrets.
    final InputStream in =
            GoogleStorageServiceImpl.class.getResourceAsStream("/client_secret.json");
    Credential credential;
    try {
        final GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        final GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                        .setDataStoreFactory(DATA_STORE_FACTORY)
                        .setAccessType("offline")
                        .build();
        credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");
    } catch (final IOException e) {
        throw new ResourceServerException("Incorrect authorization", e);
    }
    return credential;
}
 
Example 8
Project: GooglePlusJavaImplementation   File: GooglePlusConsoleDisplay.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
  // load client secrets
 Reader in = new FileReader("Local directory path for client_secrets.json file");
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, in);
  if (clientSecrets.getDetails().getClientId().startsWith("Your ")
      || clientSecrets.getDetails().getClientSecret().startsWith("Your ")) {
    System.out.println(
        "Enter Client ID and Secret from https://code.google.com/apis/console/?api=plus "
        + "into client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets,
      Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory(
      dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 9
Project: EVE   File: CalendarAPI.java   View source code 6 votes vote down vote up
/***
 * Crates a Credential object authorized by the Google API.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException{
	InputStream in = CalendarAPI.class.getResourceAsStream("resources/client_secret.json");
   
	if(in == null) throw new IOException("Client information not found.");

	GoogleClientSecrets secrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(in));

	GoogleAuthorizationCodeFlow flow =
			new GoogleAuthorizationCodeFlow.Builder(
					http, jsonFactory, secrets, scopes)
					.setDataStoreFactory(dataFactory)
					.setAccessType("offline")
					.build();
	Credential cred = new AuthorizationCodeInstalledApp(
			flow, new LocalServerReceiver()).authorize("user");
	return cred;
}
 
Example 10
Project: Shield   File: Auth.java   View source code 6 votes vote down vote up
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

        Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
                || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                    "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                            + "into src/main/resources/client_secrets.json");
            System.exit(1);
        }

        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
                .build();

        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
    }
 
Example 11
Project: ismartonline   File: GoogleClassroomClient.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        GoogleClassroomClient.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("online")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}
 
Example 12
Project: ExcelToGoogleSpreadSheet   File: Authorization.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Configuration.JSON_FACTORY,
            new InputStreamReader(Main.class.getResourceAsStream("/client_secrets/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=drive "
                        + "into src/main/resources/client_secrets.json");
        System.exit(1);
    }

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            Configuration.httpTransport, Configuration.JSON_FACTORY, clientSecrets,DriveScopes.all()
            ).setDataStoreFactory(Configuration.dataStoreFactory)
            .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 13
Project: magister-google-sync   File: MagisterGoogleCalendarSyncer.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        MagisterGoogleCalendarSyncer.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;
}
 
Example 14
Project: ftc   File: Auth.java   View source code 6 votes vote down vote up
public static Credential authorize(Reader r, Class<?> preferencesNode) throws Exception {

		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, r);

		if (clientSecrets.getDetails().getClientId().startsWith("Enter")
				|| clientSecrets.getDetails().getClientSecret().startsWith("Enter "))
			throw new RuntimeException(
					"Enter Client ID and Secret from https://code.google.com/apis/console/?api=fusiontables "
							+ "into fusiontables-cmdline-sample/src/main/resources/client_secrets.json");

		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(getHttpTransport(), JSON_FACTORY,
				clientSecrets, Collections.singleton(FusiontablesScopes.FUSIONTABLES))
						.setDataStoreFactory(getPreferencesStore(preferencesNode)).build();

		return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
	}
 
Example 15
Project: ftc   File: FusionTablesSample.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
  String path = "/client_secrets.json";
  
  // load client secrets
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
      JSON_FACTORY, new InputStreamReader(
          FusionTablesSample.class.getResourceAsStream(path)));
         
  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=fusiontables "
        + "into fusiontables-cmdline-sample/src/main/resources/client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets,
      Collections.singleton(FusiontablesScopes.FUSIONTABLES)).setDataStoreFactory(
      dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 16
Project: timetable-builder   File: TimetableBuilder.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
private static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
            TimetableBuilder.class.getResourceAsStream("/client.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("online")
                    .build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 17
Project: drbookings   File: GoogleCalendarSync.java   View source code 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 */
private static Credential authorize() throws Exception {
    // load client secrets
    final GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(GoogleCalendarSync.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        if (logger.isErrorEnabled()) {
            logger.error("Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                    + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
        }
        return null;
    }
    // set up authorization code flow
    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
            .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
            .authorize("557837674207-61uehop5b0u5enflhc7ata9a75sf731e.apps.googleusercontent.com");
}
 
Example 18
Project: drbookings   File: RunnableImportGoogleCalendar.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
	// load client secrets
	final GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
			new InputStreamReader(RunnableImportGoogleCalendar.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);
	}
	// set up authorization code flow
	final 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");
}
 
Example 19
Project: pubsub   File: SheetsService.java   View source code 6 votes vote down vote up
private Sheets authorize() {
  try {
    InputStream in = new FileInputStream(new File(System.getenv("GOOGLE_OATH2_CREDENTIALS")));
    JsonFactory factory = new JacksonFactory();
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(factory, new InputStreamReader(in, Charset.defaultCharset()));
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    FileDataStoreFactory dataStoreFactory =
        new FileDataStoreFactory(new File(dataStoreDirectory));
    List<String> scopes = Collections.singletonList(SheetsScopes.SPREADSHEETS);
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(transport, factory, clientSecrets, scopes)
            .setAccessType("offline")
            .setDataStoreFactory(dataStoreFactory)
            .build();
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    return new Sheets.Builder(transport, factory, credential)
        .setApplicationName(APPLICATION_NAME)
        .build();
  } catch (Exception e) {
    return null;
  }
}
 
Example 20
Project: mesfavoris   File: GDriveConnectionManager.java   View source code 6 votes vote down vote up
private Credential authorize(final IProgressMonitor monitor) throws IOException {
	try {
		monitor.beginTask("Authorizes the application to access user's protected data on Google Drive", 100);
		// load client secrets
		// In this context, the client secret is obviously not treated as a
		// secret.
		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
				new InputStreamReader(GDriveConnectionManager.class.getResourceAsStream("client_secrets.json")));
		// set up authorization code flow
		FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(dataStoreDir);
		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
				clientSecrets, Collections.singleton(DriveScopes.DRIVE)).setDataStoreFactory(dataStoreFactory)
						.build();
		// authorize
		LocalServerReceiver localServerReceiver = new CancellableLocalServerReceiver(monitor);
		AuthorizationCodeInstalledApp authorizationCodeInstalledApp = authorizationCodeInstalledAppProvider
				.get(flow, localServerReceiver, monitor);
		return authorizationCodeInstalledApp.authorize("user");
	} finally {
		monitor.done();
	}
}
 
Example 21
Project: blog-java2   File: SmtpManager.java   View source code 6 votes vote down vote up
private static Gmail getGmailService(String basedir, String appName) throws Exception {

        // 機密情報ファイルのパス
        File DATA_STORE_DIR = new java.io.File(basedir, "gmail-secrets");
        File SECRET_JSON = new java.io.File(DATA_STORE_DIR, "client_secret.json");

        // 準備
        FileDataStoreFactory DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

        // 送信のみ
        List<String> SCOPES = Arrays.asList(GmailScopes.GMAIL_SEND);

        // Credential取得
        try (InputStream in = FileUtils.openInputStream(SECRET_JSON)) {
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
            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");

            // Gmailインスタンス生成
            return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(appName).build();
        }
    }
 
Example 22
Project: giv-planner   File: GmailAPI.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
private static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        GmailAPI.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;
}
 
Example 23
Project: giv-planner   File: GoogleCalendar.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        GoogleCalendar.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;
}
 
Example 24
Project: giv-planner   File: AppsScriptApi.java   View source code 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        AppsScriptApi.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;
}
 
Example 25
Project: google-sites-liberation   File: Main.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. 
* @throws Exception */
 private static Credential authorize() throws Exception {
   // load client secrets
   clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
       new InputStreamReader(Main.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/ "
         + "into google-sites-liberation/src/main/resources/client_secrets.json");
     System.exit(1);
   }
   // set up authorization code flow
   GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(
       dataStoreFactory).setAccessType("offline").build();
   
   //Loading receiver on 8080 port (you can change this if already in use) 
   LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setPort( 8080 ).build(); 
   
   // authorize
   return new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user");
 }
 
Example 26
Project: google-sites-liberation   File: Main.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. 
* @throws Exception */
 private static Credential authorize() throws Exception {
   // load client secrets
   clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
       new InputStreamReader(Main.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/ "
         + "into google-sites-liberation/src/main/resources/client_secrets.json");
     System.exit(1);
   }
   // set up authorization code flow
   GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(
       dataStoreFactory).setAccessType("offline").build();
   
   //Loading receiver on 8080 port (you can change this if already in use) 
   LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setPort( 8080 ).build(); 
   
   // authorize
   return new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user");
 }
 
Example 27
Project: FeedMeYoutube   File: Auth.java   View source code 6 votes vote down vote up
/**
 * Perform the authorisation for the youtube account
 *
 * @param scopes              {@linkplain List} of scopes to perform
 *                            authorization
 * @param credentailDataStore name of the credential datastore
 *
 * @return {@linkplain Credential} object which is used for Requests
 *
 * @throws IOException an error occurs during the authorisation.
 *
 * @since 1.0
 */
public static Credential authorize(List<String> scopes,
        String credentailDataStore)
        throws IOException {
    final Reader reader = new InputStreamReader(Auth.class.
            getResourceAsStream("/youtube.json"));
    final GoogleClientSecrets secrets = GoogleClientSecrets.load(
            JSON_FACTORY, reader);
    final FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(
            Paths.get(System
                    .getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY).
            toFile());
    final DataStore<StoredCredential> dataStore = dataStoreFactory.
            getDataStore(credentailDataStore);
    final GoogleAuthorizationCodeFlow flow
            = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
                    JSON_FACTORY,
                    secrets, scopes).setCredentialDataStore(dataStore).
            build();
    final LocalServerReceiver receiver = new LocalServerReceiver.Builder().
            setPort(8080).build();

    return new AuthorizationCodeInstalledApp(flow, receiver).authorize(
            config.userId());
}
 
Example 28
Project: RavenBot   File: YTAuth.java   View source code 6 votes vote down vote up
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
	Reader clientSecretReader = new InputStreamReader(YTAuth.class.getResourceAsStream("/client_secrets.json"));
	GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

	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=youtube into src/main/resources/client_secres.json");
		System.exit(1);
	}

	FileDataStoreFactory fileDataStoreFactory= new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
	DataStore<StoredCredential> dataStore = fileDataStoreFactory.getDataStore(credentialDatastore);

	GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(dataStore).build();
	LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

	return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
 
Example 29
Project: slack-java-client   File: Auth.java   View source code 6 votes vote down vote up
public static Credential authorize() throws Exception {
  InputStream in = Auth.class.getResourceAsStream("/slack_client_secret.json");
  ClientSecrets secrets = objectMapper.readValue(in, ClientSecrets.class);

  // set up authorization code flow
  AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
          .authorizationHeaderAccessMethod(),
          HTTP_TRANSPORT,
          JSON_FACTORY,
          new GenericUrl(TOKEN_SERVER_URL),
          new ClientParametersAuthentication(
                  secrets.getClient_id(), secrets.getClient_secret()),
          secrets.getClient_id(),
          AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE))
          .setDataStoreFactory(DATA_STORE_FACTORY).build();
  LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(
          secrets.getDomain()).setPort(secrets.getPort()).build();
  System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
  Credential credential = flow.loadCredential("user");
  if (credential != null) {
    return credential;
  } else {
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
  }
}
 
Example 30
Project: leanbean   File: AndroidPublisherHelper.java   View source code 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static Credential authorizeWithInstalledApplication() throws IOException {
    log.info("Authorizing using installed application");

    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY,
            new InputStreamReader(
                    AndroidPublisherHelper.class
                            .getResourceAsStream(RESOURCES_CLIENT_SECRETS_JSON)));
    // Ensure file has been filled out.
    checkClientSecretsFile(clientSecrets);

    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
            .Builder(HTTP_TRANSPORT,
            JSON_FACTORY, clientSecrets,
            Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER))
            .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize(INST_APP_USER_ID);
}
 
Example 31
Project: googleads-adxseller-examples   File: AdExchangeSellerSample.java   View source code 6 votes vote down vote up
/** 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 InputStreamReader(AdExchangeSellerSample.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=adexchangeseller into "
        + "adexchangeseller-cmdline-sample/src/main/resources/client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
          httpTransport,
          JSON_FACTORY,
          clientSecrets,
          Collections.singleton(AdExchangeSellerScopes.ADEXCHANGE_SELLER_READONLY)
      ).setDataStoreFactory(dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 32
Project: googleads-adxseller-examples   File: AdExchangeSellerSample.java   View source code 6 votes vote down vote up
/** 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 InputStreamReader(AdExchangeSellerSample.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=adexchangeseller into "
        + "adexchangeseller-cmdline-sample/src/main/resources/client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
          httpTransport,
          JSON_FACTORY,
          clientSecrets,
          Collections.singleton(AdExchangeSellerScopes.ADEXCHANGE_SELLER_READONLY)
      ).setDataStoreFactory(dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 33
Project: grails-google-drive   File: GoogleDrive.java   View source code 6 votes vote down vote up
static Credential authorize(String clientId, String clientSecret, String credentialsPath, String credentialStore,
                            HttpTransport httpTransport, JsonFactory jsonFactory) throws IOException {
    GoogleClientSecrets.Details installedDetails = new GoogleClientSecrets.Details();
    installedDetails.setClientId(clientId);
    installedDetails.setClientSecret(clientSecret);

    GoogleClientSecrets clientSecrets = new GoogleClientSecrets();
    clientSecrets.setInstalled(installedDetails);

    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new java.io.File(credentialsPath));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialStore);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Collections.singleton(DriveScopes.DRIVE_FILE))
            .setCredentialDataStore(datastore)
            .build();

    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 34
Project: AGIA   File: GoogleDriveServiceImpl.java   View source code 6 votes vote down vote up
protected Credential authorize() throws GoogleException, GeneralSecurityException, IOException {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretsResource.getInputStream());
    if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        LOGGER.error("Enter Client ID and Secret from https://code.google.com/apis/console/?api=drive " + "into "
                + clientSecretsResource.getFile().getAbsolutePath());
        throw new GoogleException("ClientSecrets not configured");
    }
    // set up file credential store
    FileCredentialStore credentialStore = new FileCredentialStore(userCredentialStoreResource.getFile(), JSON_FACTORY);
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets,
            Collections.singleton(DriveScopes.DRIVE_FILE)).setCredentialStore(credentialStore).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, verificationCodeReceiver).authorize(user);
}
 
Example 35
Project: calendar-sync   File: Utils.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
public static Credential authorize(List<String> scopes) throws Exception {
  // Load client secrets.
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
      new InputStreamReader(SyncTokenSample.class.getResourceAsStream("/client_secrets.json")));
  if (clientSecrets.getDetails().getClientId().startsWith("Enter")
      || clientSecrets.getDetails().getClientSecret().startsWith("Enter")) {
    System.out.println(
        "Overwrite the src/main/resources/client_secrets.json file with the client secrets file "
        + "you downloaded from your Google Developers Console project.");
    System.exit(1);
  }

  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
      JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
  // Authorize.
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 36
Project: googleads-adsense-examples   File: AdSenseSample.java   View source code 6 votes vote down vote up
/** 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 InputStreamReader(AdSenseSample.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=adsense into "
        + "adsense-cmdline-sample/src/main/resources/client_secrets.json");
    System.exit(1);
  }
  // set up authorization code flow
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets,
      Collections.singleton(AdSenseScopes.ADSENSE_READONLY)).setDataStoreFactory(
      dataStoreFactory).build();
  // authorize
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 37
Project: playstorepublisher   File: AndroidPublisherHelper.java   View source code 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static Credential authorizeWithInstalledApplication() throws IOException {
    log.info("Authorizing using installed application");

    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY,
            new InputStreamReader(
                    AndroidPublisherHelper.class
                            .getResourceAsStream(RESOURCES_CLIENT_SECRETS_JSON)));
    // Ensure file has been filled out.
    checkClientSecretsFile(clientSecrets);

    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
            .Builder(HTTP_TRANSPORT,
                    JSON_FACTORY, clientSecrets,
                    Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize(INST_APP_USER_ID);
}
 
Example 38
Project: android-play-publisher-api   File: AndroidPublisherHelper.java   View source code 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static Credential authorizeWithInstalledApplication() throws IOException {
    log.info("Authorizing using installed application");

    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY,
            new InputStreamReader(
                    AndroidPublisherHelper.class
                            .getResourceAsStream(RESOURCES_CLIENT_SECRETS_JSON)));
    // Ensure file has been filled out.
    checkClientSecretsFile(clientSecrets);

    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
            .Builder(HTTP_TRANSPORT,
                    JSON_FACTORY, clientSecrets,
                    Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize(INST_APP_USER_ID);
}
 
Example 39
Project: google-drive-ftp-adapter   File: GoogleDrive.java   View source code 6 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private Credential authorize() throws Exception {
	// load client secrets
	GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
			new InputStreamReader(GFile.class.getResourceAsStream("/client_secrets.json")));
	if (clientSecrets.getDetails().getClientId().startsWith("Enter")
			|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
		System.out.println("Overwrite the src/main/resources/client_secrets.json file with the client secrets file "
				+ "you downloaded from the Quickstart tool or manually enter your Client ID and Secret "
				+ "from https://code.google.com/apis/console/?api=drive#project:275751503302 "
				+ "into src/main/resources/client_secrets.json");
		System.exit(1);
	}
	// set up authorization code flow
	Set<String> scopes = new HashSet<String>();
	scopes.add(DriveScopes.DRIVE);
	scopes.add(DriveScopes.DRIVE_METADATA);

	GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, scopes)
			.setDataStoreFactory(dataStoreFactory).build();
	// authorize
	return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
 
Example 40
Project: amelia   File: AuthorizeGoogleUser.java   View source code 5 votes vote down vote up
private static Credential authorize(String user) throws Exception {
  clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
      new InputStreamReader(AuthorizeGoogleUser.class.getResourceAsStream("/amelia-server/client_id.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/ "
        + "into oauth2-cmdline-sample/src/main/resources/client_secrets.json");
  }

  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(
      dataStoreFactory).build();
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(user);
}