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.insomne.blackbush.BlackBushContextListener.java
License:Apache License
@Override public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); try {//ww w . j ava 2 s. c om context.setAttribute("TRANSPORT", new NetHttpTransport()); context.setAttribute("GSON", new Gson()); JacksonFactory JSON_FACTORY = new JacksonFactory(); context.setAttribute("JSON_FACTORY", JSON_FACTORY); Reader reader = new InputStreamReader(context.getResourceAsStream("/client_secret.json")); context.setAttribute("clientSecrets", GoogleClientSecrets.load(JSON_FACTORY, reader)); } catch (IOException e) { throw new Error("No client_secrets.json found", e); } }
From source file:org.opencastproject.publication.youtube.auth.OAuth2CredentialFactoryImpl.java
License:Educational Community License
@Override public GoogleCredential getGoogleCredential(final DataStore<StoredCredential> datastore, final ClientCredentials authContext) throws IOException { final GoogleCredential gCred; final LocalServerReceiver localReceiver = new LocalServerReceiver(); final String accessToken; final String refreshToken; try {/*from www. j a v a 2s . com*/ // Reads the client id and client secret from a file name passed in authContext final GoogleClientSecrets gClientSecrets = GoogleClientSecrets.load(new JacksonFactory(), new FileReader(authContext.getClientSecrets())); // Obtain tokens from credential in data store, or obtains a new one from // Google if one doesn't exist final StoredCredential sCred = datastore.get(authContext.getClientId()); if (sCred != null) { accessToken = sCred.getAccessToken(); refreshToken = sCred.getRefreshToken(); logger.debug(MessageFormat.format("Found credential for client {0} in data store {1}", authContext.getClientId(), datastore.getId())); } else { // This flow supports installed applications final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( new NetHttpTransport(), new JacksonFactory(), gClientSecrets, authContext.getScopes()) .setCredentialDataStore(datastore).setApprovalPrompt("auto") .setAccessType("offline").build(); final Credential cred = new AuthorizationCodeInstalledApp(flow, localReceiver) .authorize(authContext.getClientId()); accessToken = cred.getAccessToken(); refreshToken = cred.getRefreshToken(); logger.debug(MessageFormat.format("Created new credential for client {0} in data store {1}", authContext.getClientId(), datastore.getId())); } gCred = new GoogleCredential.Builder().setClientSecrets(gClientSecrets) .setJsonFactory(new JacksonFactory()).setTransport(new NetHttpTransport()).build(); gCred.setAccessToken(accessToken); gCred.setRefreshToken(refreshToken); logger.debug(MessageFormat.format("Found credential {0} using {1}", gCred.getRefreshToken(), authContext.toString())); } finally { localReceiver.stop(); } return gCred; }
From source file:org.pentaho.googledrive.vfs.GoogleDriveFileObject.java
License:Apache License
private Credential authorize() throws IOException { InputStream in = new FileInputStream( resolveCredentialsPath() + "/" + resourceBundle.getString("client.secrets")); 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 CustomAuthorizationCodeInstalledApp(flow, new CustomLocalServerReceiver()) .authorize("user"); return credential; }
From source file:org.ut.biolab.medsavant.app.google.original.GenomicsSample.java
License:Open Source License
private static GoogleClientSecrets loadClientSecrets() { try {/*from www . ja v a 2 s. co m*/ InputStream inputStream = getClientSecrets(); return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(inputStream)); } catch (Exception e) { System.err.println("Could not load client_secrets.json"); } return null; }
From source file:org.yccheok.jstock.google.drive.Utils.java
/** Authorizes the installed application to access user's protected data. * @return //from www. j a v a 2 s .c o m * @throws java.lang.Exception */ public static Credential authorize() throws Exception { // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY, new InputStreamReader(Utils.class.getResourceAsStream("/resources/drive_client_secrets.json"))); // 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. Set<String> scopes = new HashSet<String>(); scopes.add("email"); scopes.add("profile"); scopes.add(DriveScopes.DRIVE_APPDATA); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build(); // authorize return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:org.yccheok.jstock.google.Utils.java
public static Pair<Pair<Credential, String>, Boolean> authorizeCalendar() throws Exception { Set<String> scopes = new HashSet<String>(); scopes.add("email"); scopes.add("profile"); scopes.add(CalendarScopes.CALENDAR); // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY, new InputStreamReader( Utils.class.getResourceAsStream("/assets/authentication/calendar/client_secrets.json"))); return authorize(clientSecrets, scopes, getCalendarDataDirectory()); }
From source file:org.yccheok.jstock.google.Utils.java
public static Pair<Pair<Credential, String>, Boolean> authorizeDrive() throws Exception { // 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. Set<String> scopes = new HashSet<String>(); scopes.add("email"); scopes.add("profile"); scopes.add(DriveScopes.DRIVE_APPDATA); // Legacy. Shall be removed after a while... scopes.add(DriveScopes.DRIVE);//from w w w . j a v a2s .c o m // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY, new InputStreamReader( Utils.class.getResourceAsStream("/assets/authentication/drive/client_secrets.json"))); return authorize(clientSecrets, scopes, getDriveDataDirectory()); }
From source file:org.yccheok.jstock.google.Utils.java
public static Pair<Credential, String> authorizeCalendarOffline() throws Exception { Set<String> scopes = new HashSet<String>(); scopes.add("email"); scopes.add("profile"); scopes.add(CalendarScopes.CALENDAR); // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY, new InputStreamReader( Utils.class.getResourceAsStream("/assets/authentication/calendar/client_secrets.json"))); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(new FileDataStoreFactory(getCalendarDataDirectory())) .build();//from w ww. j ava 2 s.co m Credential credential = flow.loadCredential("user"); if (credential != null && credential.getRefreshToken() != null) { boolean success = false; if (credential.getExpiresInSeconds() <= 60) { if (credential.refreshToken()) { success = true; } } else { success = true; } if (success) { FileDataStoreFactory fileDataStoreFactory = (FileDataStoreFactory) flow.getCredentialDataStore() .getDataStoreFactory(); String email = Utils.loadEmail(fileDataStoreFactory.getDataDirectory()); if (email == null) { Userinfoplus userinfoplus = org.yccheok.jstock.google.Utils.getUserInfo(credential); email = userinfoplus.getEmail(); } return new Pair<Credential, String>(credential, email); } } return null; }
From source file:orientan.OAuth.OAuth.java
/** Authorizes the installed application to access user's protected data. */ private static Credential authorize() throws Exception { // load client secrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(OAuth.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 oauth2-cmdline-sample/src/main/resources/client_secrets.json"); System.exit(1);//from ww w .j a va2 s . c o m } // set up authorization code flow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(dataStoreFactory).build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
From source file:pkg398gmail.GmailApiQuickstart.java
public static void main(String[] args) 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("offline").setApprovalPrompt("force").build(); String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build(); System.out.println(/*from w w w . j a va 2s .co m*/ "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(); System.out.println("refresh " + response.getRefreshToken()); /* online use GoogleCredential credential = new GoogleCredential() .setFromTokenResponse(response); */ // offline use. //http://stackoverflow.com/questions/15064636/googlecredential-wont-build-without-googlecredential-builder GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(jsonFactory).setClientSecrets(clientSecrets).build().setFromTokenResponse(response); // Create a new authorized Gmail API client Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME) .build(); // Retrieve a page of Threads; max of 100 by default. ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute(); List<com.google.api.services.gmail.model.Thread> threads = threadsResponse.getThreads(); // Print ID of each Thread. for (com.google.api.services.gmail.model.Thread thread : threads) { System.out.println("Thread ID: " + thread.getId()); } // send message try { sendMessage(service, "me", createEmail("wra216@lehigh.edu", "me", "test", "test")); } catch (MessagingException ex) { Logger.getLogger(GmailApiQuickstart.class.getName()).log(Level.SEVERE, null, ex); } }