Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setRefreshToken

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setRefreshToken

Introduction

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

Prototype

@Override
    public GoogleCredential setRefreshToken(String refreshToken) 

Source Link

Usage

From source file:cloudnet.user.UserGoogleDrive.java

public void printFilesInFolder(String userType, String folderId, String token) {
    //        if(!files.isEmpty())
    //            parentFolderId = files.get(0).getParents().get(0).getId();
    GoogleCredential credential;
    files.removeAll(files);/*w  w w .jav  a2  s .c  o  m*/

    try {
        GoogleTokenResponse response;
        if (userType.equals(CloudNet.NEW_USER)) {
            response = flow.newTokenRequest(token).setRedirectUri(REDIRECT_URI).execute();

            addTokenToDatabase(response.getRefreshToken());
            User.setGoogleToken(String.valueOf(response.getRefreshToken()));

            credential = new GoogleCredential().setAccessToken(response.getAccessToken());
        } else {
            GoogleCredential.Builder b = new GoogleCredential.Builder();
            b.setJsonFactory(jsonFactory);
            b.setTransport(httpTransport);
            b.setClientSecrets(CLIENT_ID, CLIENT_SECRET);
            credential = b.build();
            credential.setRefreshToken(token);
            credential.refreshToken();
            credential.setAccessToken(credential.getAccessToken());
        }

        //Create a new authorized API client
        service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName("CloudNet")
                .build();
        filesRequest = service.files().list().setQ("trashed = false and '" + folderId + "' in parents");

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    do {
        try {
            FileList filesList = filesRequest.execute();

            for (File file : filesList.getItems()) {
                files.add(file);
                System.out.println(file.getTitle());
            }
            //parentFolderId = files.get(0).getParents().get(0).getId();

            filesRequest.setPageToken(filesList.getNextPageToken());
        } catch (IOException e) {
            System.out.println("An error occurred: " + e);
            filesRequest.setPageToken(null);
        }
    } while (filesRequest.getPageToken() != null && filesRequest.getPageToken().length() > 0);

    addMenu();
    CloudNet.noAccounts.setListItems(files, GOOGLE_CLOUD);
}

From source file:com.framework.common.GoogleSheets.java

public GoogleSheets(GoogleSheetConnectionDetails requiredSheet) {

    this.sheetName = requiredSheet.getSpreadSheetName();
    this.workSheetName = requiredSheet.getWorkSheetName();
    this.CLIENT_ID = requiredSheet.getClient_id();
    this.CLIENT_SECRET = requiredSheet.getClient_secret();
    this.refreshToken = requiredSheet.getRefreshToken();
    this.accessToken = requiredSheet.getAccessToken();

    List<String> scopes = Arrays.asList("https://www.googleapis.com/auth/drive");
    try {//from w ww.  j a v  a2s  .c o m

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build();

        credential.setRefreshToken(refreshToken);
        credential.setAccessToken(accessToken);

        SpreadsheetService service = new SpreadsheetService("Aplication-name");

        this.requiredservice = service;

        service.setOAuth2Credentials(credential);

        URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
        // Make a request to the API and get all spreadsheets.

        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);

        List<com.google.gdata.data.spreadsheet.SpreadsheetEntry> spreadsheets = feed.getEntries();

        boolean spreadsheetfound = false;
        int sheetCounter = 0;
        for (com.google.gdata.data.spreadsheet.SpreadsheetEntry spreadsheet : spreadsheets) {

            if (spreadsheets.isEmpty()) {
                System.out.println(" No spread sheets found.");
                throw new IllegalArgumentException();
            }

            //                System.out.println(spreadsheet.getTitle().getPlainText());
            if (spreadsheet.getTitle().getPlainText().equalsIgnoreCase(this.sheetName)) {
                //                    System.out.println("Found it");
                this.requiredSpreadsheet = spreadsheet;
                spreadsheetfound = true;
            }

        }

        if (!spreadsheetfound) {
            System.out.println("Spreadsheet not found, please check the name");
            throw new IllegalArgumentException("Spreadsheet not found, please check the name");
        }

        WorksheetFeed worksheetFeed = service.getFeed(requiredSpreadsheet.getWorksheetFeedUrl(),
                WorksheetFeed.class);

        List<WorksheetEntry> worksheets = worksheetFeed.getEntries();

        boolean worksheetfound = false;
        for (WorksheetEntry worksheet : worksheets) {
            //                System.out.println(worksheet.getTitle().getPlainText());
            if (worksheet.getTitle().getPlainText().equalsIgnoreCase(workSheetName)) {
                //                    System.out.println("Found It");
                this.requiredWorkSheet = worksheet;
                worksheetfound = true;
            }
            sheetCounter++;
        }
        if (!worksheetfound) {
            System.out.println("Worksheet was not found, please check the name");
            throw new IllegalArgumentException("Worksheet was not found, please check the name");
        }
        this.totalSheets = sheetCounter;

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.liferay.google.drive.repository.GoogleDriveRepository.java

License:Open Source License

protected GoogleDriveSession buildGoogleDriveSession() throws IOException, PortalException {

    long userId = PrincipalThreadLocal.getUserId();

    User user = UserLocalServiceUtil.getUser(userId);

    if (user.isDefaultUser()) {
        throw new PrincipalException("User is not authenticated");
    }//from   w w w  . jav  a  2 s.c o  m

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    String googleClientId = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-id");
    String googleClientSecret = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-secret");

    builder.setClientSecrets(googleClientId, googleClientSecret);

    JacksonFactory jsonFactory = new JacksonFactory();

    builder.setJsonFactory(jsonFactory);

    HttpTransport httpTransport = new NetHttpTransport();

    builder.setTransport(httpTransport);

    GoogleCredential googleCredential = builder.build();

    ExpandoBridge expandoBridge = user.getExpandoBridge();

    String googleAccessToken = GetterUtil.getString(expandoBridge.getAttribute("googleAccessToken", false));

    googleCredential.setAccessToken(googleAccessToken);

    String googleRefreshToken = GetterUtil.getString(expandoBridge.getAttribute("googleRefreshToken", false));

    googleCredential.setRefreshToken(googleRefreshToken);

    Drive.Builder driveBuilder = new Drive.Builder(httpTransport, jsonFactory, googleCredential);

    Drive drive = driveBuilder.build();

    Drive.About driveAbout = drive.about();

    Drive.About.Get driveAboutGet = driveAbout.get();

    About about = driveAboutGet.execute();

    return new GoogleDriveSession(drive, about.getRootFolderId());
}

From source file:com.prog.dist.oauth2.OauthCallBack.java

public void remplirSession(HttpServletRequest request, GoogleTokenResponse googleTokenResponse) {
    // Initializing the Tasks service
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    OAuthProperties oauthProperties = new OAuthProperties();

    GoogleCredential googleCredential = new GoogleCredential()
            .setAccessToken(googleTokenResponse.getAccessToken());
    googleCredential.setRefreshToken(googleTokenResponse.getRefreshToken());

    // set up global Oauth2 instance
    Oauth2 oauth2 = new Oauth2.Builder(transport, jsonFactory, googleCredential)
            .setApplicationName(APPLICATION_NAME).build();

    Userinfo userInfo = oauth2.userinfo();
    try {// ww w.j  ava  2s  .co  m
        String email = userInfo.get().execute().getEmail();
        String emailDomain = email.split("@")[1];
        if (!emailDomain.equals("edu.uca.ma")) {
            codeError = "1"; // email invalide
        } else {
            codeError = null;
            request.getSession().setAttribute("info", userInfo.get().execute().toPrettyString());
        }
    } catch (IOException ex) {
        Logger.getLogger(OauthCallBack.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.bremen.ugs.calendar.CalendarHelper.java

License:Open Source License

/**
 * Sets up the {@link Calendar} service. This method is called when a valid
 * code is given./*from  w w w . j av  a 2  s .c o m*/
 * 
 * @param code
 *            given code
 * @return {@link Calendar} service
 * @throws IOException
 *             thrown in case the calendar api throws it
 */
private Calendar setUp(final String code) throws IOException {
    final AppEngineCredentialStore credentialStore = new AppEngineCredentialStore();

    GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY,
            DeployConstants.CLIENT_ID, DeployConstants.CLIENT_SECRET, code, DeployConstants.REDIRECT_URL)
                    .execute();

    final GoogleCredential credential = CredentialHelper.loadCredential(this.userId);

    credential.setAccessToken(response.getAccessToken());
    credential.setRefreshToken(response.getRefreshToken());
    credential.setExpiresInSeconds(response.getExpiresInSeconds());

    credentialStore.store(userId, credential);

    Calendar calendar = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(DeployConstants.APP_NAME + "/" + DeployConstants.APP_VERSION).build();

    return calendar;
}

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  w w  w.j  a  va2  s. 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.wso2.carbon.dataservices.core.admin.DataServiceAdmin.java

License:Open Source License

/**
 * This will test the connection(retrieve CallFeed) of a Google spreadsheet
 * document. If connection can be made this method will return the status as
 * String, if not, failure String will be return.
 *
 * @param clientId from developer console
 * @param clientSecret from developer console
 * @param refreshToken generated refresh token
 * @param visibility Whether its private or public
 * @param documentURL Google spreadsheet URL
 * @return string State/*  w  w w.ja  v  a2s . c  o  m*/
 */
public String testGSpreadConnection(String clientId, String clientSecret, String refreshToken,
        String visibility, String documentURL) {
    if (DBUtils.isEmptyString(documentURL)) {
        String message = "Document URL is empty";
        log.debug(message);
        return message;
    }
    String key;
    SpreadsheetService service = new SpreadsheetService("GSpread Connection Service");
    try {
        key = GSpreadConfig.extractKey(documentURL);
    } catch (DataServiceFault e) {
        String message = "Invalid documentURL:" + documentURL;
        log.error(message, e);
        return message;
    }

    if (!visibility.equals("public")) {
        if (DBUtils.isEmptyString(clientId)) {
            String message = "clientId field is empty";
            log.error(message);
            return message;
        }
        if (DBUtils.isEmptyString(clientSecret)) {
            String message = "clientSecret field is empty";
            log.error(message);
            return message;
        }
        if (DBUtils.isEmptyString(refreshToken)) {
            String message = "refreshToken field is empty";
            log.error(message);
            return message;
        }
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder().setClientSecrets(clientId, clientSecret)
                .setTransport(httpTransport).setJsonFactory(jsonFactory).build();
        credential.setRefreshToken(refreshToken);
        try {
            credential.refreshToken();
        } catch (IOException e) {
            String message = "Google spreadsheet connection failed, Error refreshing the token ";
            log.debug(message);
            return message;
        }
        service.setOAuth2Credentials(credential);
    }

    String worksheetFeedURL = GSpreadConfig.BASE_WORKSHEET_URL + key + "/" + visibility + "/basic";
    try {
        URL url = new URL(worksheetFeedURL);
        try {
            service.getFeed(url, CellFeed.class);
            String message = "Google spreadsheet connection is successfull ";
            log.debug(message);
            return message;
        } catch (AuthenticationException e) {
            String message = "Invalid Credentials";
            log.error(message, e);
            return message;
        } catch (IOException e) {
            String message = "URL Not found:" + documentURL;
            log.error(message, e);
            return message;
        } catch (ServiceException e) {
            String message = "URL Not found:" + documentURL;
            log.error(message, e);
            return message;
        }
    } catch (MalformedURLException e) {
        String message = "Invalid documentURL:" + documentURL;
        log.error(message, e);
        return message;
    }

}

From source file:org.wso2.carbon.dataservices.sql.driver.util.GSpreadFeedProcessor.java

License:Open Source License

/**
 * helper method to refresh the access token and authenticate
 *
 * @throws Exception/*from   ww  w  .  j a va 2  s.  c om*/
 */
private void refreshAndAuthenticate() throws Exception {
    GoogleCredential credential = getBaseCredential();
    credential.setAccessToken(this.accessToken);
    credential.setRefreshToken(this.refreshToken);
    credential.refreshToken();
    this.accessToken = credential.getAccessToken();
    this.service.setOAuth2Credentials(credential);
}