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

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

Introduction

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

Prototype

public GoogleCredential() 

Source Link

Document

Constructor with the ability to access protected resources, but not refresh tokens.

Usage

From source file:com.google.ytdl.UploadService.java

License:Apache License

@Override
protected void onHandleIntent(Intent intent) {
    mFileUri = intent.getData();// w  w  w  .  j  a v a 2  s .c o m
    mToken = intent.getStringExtra("token");
    mFileSize = intent.getLongExtra("length", 0);
    GoogleCredential credential = new GoogleCredential();
    credential.setAccessToken(mToken);

    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    YouTube youtube = new YouTube.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(Constants.APP_NAME).build();

    InputStream fileInputStream = null;
    try {
        mFileSize = getContentResolver().openFileDescriptor(mFileUri, "r").getStatSize();
        fileInputStream = getContentResolver().openInputStream(mFileUri);
    } catch (FileNotFoundException e) {
        Log.e(getApplicationContext().toString(), e.getMessage());
    }
    ResumableUpload.upload(youtube, fileInputStream, mFileSize, getApplicationContext());
}

From source file:com.klepra.jdbcpractice.GoogleApiClient.java

public static void main(String[] args) {

    GoogleCredential credential = new GoogleCredential().setAccessToken("");
    System.out.println(credential.getServiceAccountId());

}

From source file:com.letscode.rsync.Main.java

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    if (args.length <= 0) {
        System.out.println("Please input your upload file path : ");
        filePath = br.readLine();/*ww  w  .j a  v  a  2 s. c  o m*/
        if ("".equals(filePath)) {
            System.exit(0);
        }
    } else {
        filePath = args[0];
    }

    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            CLIENT_ID, CLIENT_SECRET, Arrays.asList(new String[] { "https://www.googleapis.com/auth/drive" }))
                    .setAccessType("online").setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build();
    System.out.println("****Please open the following URL in your browser then type the authorization code");
    System.out.println("[COPY] " + url);
    System.out.print("[PASTE] Authen code : ");
    String code = br.readLine();

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    drive = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME)
            .build();

    uploadFolder(false, filePath);
}

From source file:com.mycompany.gmailtest.view.MessageView.java

public static void getConnection(String code) throws IOException {
    // Generate Credential using retrieved code.
    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(callbackUrl).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();
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.GoogleProfileReader.java

License:Apache License

private Storage createGoogleStorage(boolean useApplicationDefaultCreds) {
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    String applicationName = "Spinnaker/Halyard";
    HttpRequestInitializer requestInitializer;

    try {//from ww w .  j  a va 2  s.  c  o  m
        GoogleCredential credential = useApplicationDefaultCreds ? GoogleCredential.getApplicationDefault()
                : new GoogleCredential();
        if (credential.createScopedRequired()) {
            credential = credential.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
        }
        requestInitializer = GoogleCredentials.setHttpTimeout(credential);

        log.info("Loaded application default credential for reading BOMs & profiles.");
    } catch (Exception e) {
        requestInitializer = GoogleCredentials.retryRequestInitializer();
        log.debug(
                "No application default credential could be loaded for reading BOMs & profiles. Continuing unauthenticated: {}",
                e.getMessage());
    }

    return new Storage.Builder(GoogleCredentials.buildHttpTransport(), jsonFactory, requestInitializer)
            .setApplicationName(applicationName).build();
}

From source file:com.otway.picasasync.webclient.GoogleOAuth.java

License:Apache License

public Credential getRefreshedCredentials(String refreshCode) throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    log.info("Getting access token for refresh token..");

    try {/*  w  w  w.j av  a  2  s  . c  o  m*/
        GoogleTokenResponse response = new GoogleRefreshTokenRequest(httpTransport, jsonFactory, refreshCode,
                clientId, clientSecret).execute();

        return new GoogleCredential().setAccessToken(response.getAccessToken());

    } catch (UnknownHostException ex) {
        log.error("Unknown host. No web access?");
        throw ex;
    } catch (IOException e) {
        log.error("Exception getting refreshed auth: ", e);
    }
    return null;
}

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 {//from  w  w  w  .java 2s  .c o 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:com.twasyl.slideshowfx.hosting.connector.drive.DriveHostingConnector.java

License:Apache License

@Override
public boolean authenticate() {

    final HttpTransport httpTransport = new NetHttpTransport();
    final JsonFactory jsonFactory = new JacksonFactory();

    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            GlobalConfiguration.getProperty(this.CONSUMER_KEY),
            GlobalConfiguration.getProperty(this.CONSUMER_SECRET), Arrays.asList(DriveScopes.DRIVE))
                    .setAccessType("online").setApprovalPrompt("auto").build();

    final WebView browser = new WebView();
    final Scene scene = new Scene(browser);
    final Stage stage = new Stage();

    browser.setPrefSize(500, 500);//from   ww  w . j  a v  a  2  s  .c  om
    browser.getEngine().getLoadWorker().stateProperty().addListener((stateValue, oldState, newState) -> {
        if (newState == Worker.State.SUCCEEDED) {

            final HTMLInputElement codeElement = (HTMLInputElement) browser.getEngine().getDocument()
                    .getElementById("code");
            if (codeElement != null) {
                final String authorizationCode = codeElement.getValue();

                try {
                    final GoogleTokenResponse response = flow.newTokenRequest(authorizationCode.toString())
                            .setRedirectUri(GlobalConfiguration.getProperty(this.REDIRECT_URI)).execute();

                    this.credential = new GoogleCredential().setFromTokenResponse(response);
                    this.accessToken = this.credential.getAccessToken();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to get access token", e);
                    this.accessToken = null;
                } finally {
                    GlobalConfiguration.setProperty(this.ACCESS_TOKEN, this.accessToken);
                    stage.close();
                }

            }
        }
    });
    browser.getEngine().load(flow.newAuthorizationUrl()
            .setRedirectUri(GlobalConfiguration.getProperty(this.REDIRECT_URI)).build());

    stage.setScene(scene);
    stage.setTitle("Authorize SlideshowFX in Google Drive");
    stage.showAndWait();

    return this.isAuthenticated();
}

From source file:com.twasyl.slideshowfx.hosting.connector.drive.DriveHostingConnector.java

License:Apache License

@Override
public boolean checkAccessToken() {
    boolean valid = false;

    if (this.credential == null) {
        this.credential = new GoogleCredential();
        this.credential.setAccessToken(this.accessToken);
    }/*w ww .ja  v  a  2  s .c  o  m*/

    Drive service = new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), this.credential)
            .setApplicationName("SlideshowFX").build();

    try {
        service.about().get().execute();
        valid = true;
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Can not determine if access token is valid", e);
    }

    return valid;
}

From source file:edu.morgan.server.GoogleDrive.java

public GoogleDrive(String code) throws IOException {
    this.httpTransport = new NetHttpTransport();
    this.jsonFactory = new JacksonFactory();

    this.flow = new GoogleAuthorizationCodeFlow.Builder(this.httpTransport, this.jsonFactory, CLIENT_ID,
            CLIENT_SECRET,//from   ww  w  . j  a v  a  2 s  .c o m
            Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA, DriveScopes.DRIVE_APPS_READONLY,
                    DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_METADATA_READONLY)).setAccessType("offline")
                            .setApprovalPrompt("force").build();

    GoogleTokenResponse response = this.flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    String accessToken = response.getAccessToken();
    credential = new GoogleCredential().setAccessToken(accessToken);
    this.setService(new Drive.Builder(this.httpTransport, this.jsonFactory, this.credential)
            .setApplicationName("Admissions GoogleDrive Manager").build());
}