List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleClientSecrets setInstalled
public GoogleClientSecrets setInstalled(Details installed)
From source file:br.usp.poli.lta.cereda.macro.util.GoogleDriveController.java
License:Open Source License
/** * Construtor.//from w w w . ja v a 2 s. co m */ private GoogleDriveController() { // originalmente, o servio invlido service = null; // tenta obter a configurao do Google Drive a partir de um arquivo de // propriedades localizado no diretrio de usurio File config = new File( System.getProperty("user.home").concat(File.separator).concat("me-driveconfig.properties")); // se a configurao no existe, lanar exceo if (!config.exists()) { exception = new TextRetrievalException( "No encontrei o arquivo de configurao do Google Drive ('me-driveconfig.properties') no diretrio do usurio."); } else { // a configurao existe, carrega o mapa de chaves e valores e // faz a autenticao no Google Drive Properties properties = new Properties(); try { // obtm o arquivo de propriedades e verifica se as chaves so // vlidas properties.load(new FileReader(config)); if (properties.containsKey("id") && properties.containsKey("secret")) { // cria as chaves de acesso de acordo com as informaes // contidas no arquivo de propriedades GoogleClientSecrets secrets = new GoogleClientSecrets(); GoogleClientSecrets.Details details = new GoogleClientSecrets.Details(); details.setClientId(properties.getProperty("id")); details.setClientSecret(properties.getProperty("secret")); secrets.setInstalled(details); // cria um novo transporte HTTP e a factory do JSON para // parsing da API do Google Drive HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory factory = JacksonFactory.getDefaultInstance(); // define o diretrio do usurio como o local para // armazenamento das credenciais de autenticao do // Google Drive FileDataStoreFactory store = new FileDataStoreFactory( new File(System.getProperty("user.home"))); // cria um fluxo de autorizao do Google a partir de todas // as informaes coletadas anteriormente GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, factory, secrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setDataStoreFactory(store) .build(); // cria uma nova credencial a partir da autorizao Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) .authorize("user"); // cria efetivamente um novo servio do Google Drive // utilizando as informaes coletadas anteriormente service = new Drive.Builder(transport, factory, credential) .setApplicationName("macro-expander/1.0").build(); } else { // as chaves so invlidas, configura uma nova exceo exception = new TextRetrievalException( "O arquivo de configurao do Google Drive ('me-driveconfig.properties') no possui as chaves 'id' e 'secret'."); } } catch (IOException ex) { // erro de leitura do arquivo de configurao exception = new TextRetrievalException( "No consegui ler o arquivo de configurao do Google Drive ('me-driveconfig.properties') no diretrio do usurio."); } catch (GeneralSecurityException ex) { // erro de conexo exception = new TextRetrievalException("No foi possvel estabelecer uma conexo segura."); } } }
From source file:com.aalmeida.lightning.external.auth.GoogleAuthorizationImpl.java
License:Apache License
/** * Authorize./* ww w .j a v a2 s.c o m*/ * * @param pUrl * the url * @return the credential * @throws Exception * the exception */ private static Credential authorize(String pUrl) throws Exception { URL url = new URL(pUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, in); String clientId = clientSecrets.getDetails().getClientId(); String clientSecret = clientSecrets.getDetails().getClientSecret(); if ((clientId == null) || (clientId.isEmpty()) || (clientSecret == null) || (clientSecret.isEmpty())) { throw new Exception("Empty Google credencials"); } GoogleClientSecrets.Details details = new GoogleClientSecrets.Details(); details.setClientId(clientId); details.setClientSecret(clientSecret); clientSecrets.setInstalled(details); List<String> permissions = new ArrayList<String>(); permissions.add("https://www.googleapis.com/auth/calendar"); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, permissions).setAccessType("offline").setApprovalPrompt("force") .setDataStoreFactory(dataStoreFactory).build(); return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:com.google.cloud.hadoop.util.CredentialFactory.java
License:Open Source License
/** * Initialized OAuth2 credential for the "installed application" flow; where the credential * typically represents an actual end user (instead of a service account), and is stored * as a refresh token in a local FileCredentialStore. * @param clientId OAuth2 client ID identifying the 'installed app' * @param clientSecret OAuth2 client secret * @param filePath full path to a ".json" file for storing the credential * @param scopes list of well-formed scopes desired in the credential * @return credential with desired scopes, possibly obtained from loading {@code filePath}. * @throws IOException on IO error/*from ww w . ja v a 2 s .c om*/ */ public Credential getCredentialFromFileCredentialStoreForInstalledApp(String clientId, String clientSecret, String filePath, List<String> scopes) throws IOException, GeneralSecurityException { LOG.debug("getCredentialFromFileCredentialStoreForInstalledApp({}, {}, {}, {})", clientId, clientSecret, filePath, scopes); Preconditions.checkArgument(!Strings.isNullOrEmpty(clientId), "clientId must not be null or empty"); Preconditions.checkArgument(!Strings.isNullOrEmpty(clientSecret), "clientSecret must not be null or empty"); Preconditions.checkArgument(!Strings.isNullOrEmpty(filePath), "filePath must not be null or empty"); Preconditions.checkArgument(scopes != null, "scopes must not be null or empty"); // Initialize client secrets. GoogleClientSecrets.Details details = new GoogleClientSecrets.Details(); details.setClientId(clientId); details.setClientSecret(clientSecret); GoogleClientSecrets clientSecrets = new GoogleClientSecrets(); clientSecrets.setInstalled(details); // Set up file credential store. FileCredentialStore credentialStore = new FileCredentialStore(new File(filePath), JSON_FACTORY); // Set up authorization code flow. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(getHttpTransport(), JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore) .setRequestInitializer(new CredentialHttpRetryInitializer()).build(); // Authorize access. return new AuthorizationCodeInstalledApp(flow, new GooglePromptReceiver()).authorize("user"); }
From source file:com.NSSWare.MultiSync.GoogleDriveSyncer.java
public static GoogleAuthorizationCodeFlow getFlow(List<String> scopes) throws IOException { if (flow == null) { GoogleClientSecrets.Details installed = new GoogleClientSecrets.Details(); installed.setAuthUri(AUTH_URI); installed.setClientId(CLIENT_ID); installed.setClientSecret(CLIENT_SECRET); installed.setRedirectUris(REDIRECT_URIS); installed.setTokenUri(TOKEN_URI); GoogleClientSecrets clientSecret = new GoogleClientSecrets(); clientSecret.setInstalled(installed); flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecret, scopes) .setAccessType("offline").setApprovalPrompt("force").build(); }/*from w w w . j a v a 2s . c o m*/ return flow; }
From source file:org.grails.plugin.google.drive.GoogleDrive.java
License:Apache License
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();//from w w w. ja v a2s . co m return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:tv.bioscope.taskqueue.TaskQueueWorker.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 = new GoogleClientSecrets(); GoogleClientSecrets.Details installed = new GoogleClientSecrets.Details(); installed.setClientId(CLIENT_ID);/*ww w . j a va 2 s . c om*/ installed.setClientSecret(CLIENT_SECRET); clientSecrets.setInstalled(installed); 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=taskqueue into " + "taskqueue-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(TaskqueueScopes.TASKQUEUE)) .setDataStoreFactory(dataStoreFactory).build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }