Example usage for twitter4j.auth OAuthAuthorization setOAuthAccessToken

List of usage examples for twitter4j.auth OAuthAuthorization setOAuthAccessToken

Introduction

In this page you can find the example usage for twitter4j.auth OAuthAuthorization setOAuthAccessToken.

Prototype

@Override
    public void setOAuthAccessToken(AccessToken accessToken) 

Source Link

Usage

From source file:com.mastfrog.acteur.twitter.TwitterSign.java

@SuppressWarnings("unchecked")
RemoteUserInfo zgetUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential,
        AuthorizationResponse auth)//from ww  w.  j  ava  2s .  c  o m
        throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException {
    System.setProperty("twitter4j.http.useSSL", "false");

    Twitter twitter = TwitterFactory.getSingleton();
    try {
        // Idiotic - shutdown does not clear state
        twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    } catch (Exception e) {
        e.printStackTrace();
    }
    twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret));
    OAuthAuthorization a = new OAuthAuthorization(twitter.getConfiguration());
    a.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);

    URL url = URL.builder(Protocols.HTTPS)
            //        URL url = URL.builder(Protocols.HTTP) // XXX NOT UNENCRYPTED!  JUST FOR DEBUGING
            .setHost(Host.parse("api.twitter.com")).setPath("1.1/account/verify_credentials.json").create();

    String hdr = new SigBuilder().add(oauth_token, auth.accessToken).add(OAuthHeaders.oauth_nonce, oauth_nonce)
            .toHeader(Method.GET, url.getPathAndQuery(), auth); // XXX encode URL?

    String franken = a.xgenerateAuthorizationHeader(oauth_nonce, "GET", "/1.1/account/verify_credentials.json",
            new HttpParameter[0], new twitter4j.auth.AccessToken(auth.accessToken, auth.accessTokenSecret));

    OAuthAuthorization oa = new OAuthAuthorization(twitter.getConfiguration());
    oa.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    oa.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret));

    twitter4j.internal.http.HttpRequest r = new twitter4j.internal.http.HttpRequest(RequestMethod.GET,
            "https://api.twitter.com/twitter4j.internal.http.HttpRequest", new HttpParameter[0], oa,
            Collections.<String, String>emptyMap());

    ResponseLatch latch = new ResponseLatch();
    RH rh = new RH();
    client.get().setURL(url).addHeader(Headers.stringHeader("Authorization"), hdr)
            .addHeader(Headers.stringHeader("X-Twitter-Client-URL"),
                    "http://twitter4j.org/en/twitter4j-3.0.4-SNAPSHOT.xml")
            .addHeader(Headers.stringHeader("X-Twitter-Client"), "Twitter4J")
            .addHeader(Headers.stringHeader("Accept-Encoding"), "gzip")
            .addHeader(Headers.stringHeader("X-Twitter-Client-Version"), "3.0.4-SNAPSHOT")
            .addHeader(Headers.stringHeader("Accept"), "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
            //                .addHeader(Headers.stringHeader("Accept"), "*/*")
            //                .addHeader(Headers.stringHeader("Connection"), "keep-alive")
            .noDateHeader()
            //                .noConnectionHeader()
            //                .addHeader(Headers.stringHeader("Content-Type"), "application/x-www-form-urlencoded")
            //                .setBody("screen_name=kablosna", MediaType.PLAIN_TEXT_UTF_8)
            .on(StateType.Closed, latch).on(StateType.Timeout, latch).execute(rh);
    rh.await(1, TimeUnit.MINUTES);
    latch.latch.await(1, TimeUnit.MINUTES);

    String responseBody = rh.getResponse();

    RUI rui = new RUI();
    if (responseBody == null) {
        //            System.out.println("NULL RESPONSE BODY.");
        throw new IOException(rh.toString());
    }
    rui.putAll(new ObjectMapper().readValue(responseBody, Map.class));
    return rui;
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context,
        final AccountWithCredentials account) {
    if (context == null || account == null)
        return null;
    switch (account.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE);
        // Here I use old consumer key/secret because it's default
        // key for older
        // versions
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY_2);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        if (!isEmpty(account.api_url_format)) {
            final String versionSuffix = account.no_version_suffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(account.api_url_format, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(account.api_url_format, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(account.api_url_format, "upload", versionSuffix));
            if (!account.same_oauth_signing_url) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }//from   ww  w.ja  va 2  s . co  m
        }
        if (!isEmpty(account.consumer_key) && !isEmpty(account.consumer_secret)) {
            cb.setOAuthConsumerKey(account.consumer_key);
            cb.setOAuthConsumerSecret(account.consumer_secret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
        }
        final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
        auth.setOAuthAccessToken(new AccessToken(account.oauth_token, account.oauth_token_secret));
        return auth;
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = account.screen_name;
        final String username = account.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = account.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new BasicAuthorization(loginName, password);
    }
    default: {
        return null;
    }
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context, final long accountId) {

    final String where = Where.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL();
    final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI,
            Accounts.COLUMNS, where, null, null);
    if (c == null)
        return null;
    try {//from   w  w w  .j a va  2 s  . com
        if (!c.moveToFirst())
            return null;

        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
        case Accounts.AUTH_TYPE_OAUTH:
        case Accounts.AUTH_TYPE_XAUTH: {
            final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                    Context.MODE_PRIVATE);
            final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY_2);
            final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
            final ConfigurationBuilder cb = new ConfigurationBuilder();
            final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT));
            final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY)));
            final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET)));
            final boolean sameOAuthSigningUrl = c
                    .getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1;
            if (!isEmpty(apiUrlFormat)) {
                cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", "/1.1/"));
                cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
                cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", "/1.1/"));
                if (!sameOAuthSigningUrl) {
                    cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                    cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                    cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
                }
            }
            if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
                cb.setOAuthConsumerKey(consumerKey);
                cb.setOAuthConsumerSecret(consumerSecret);
            } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
                cb.setOAuthConsumerKey(prefConsumerKey);
                cb.setOAuthConsumerSecret(prefConsumerSecret);
            } else {
                cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
                cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
            }
            final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            auth.setOAuthAccessToken(new AccessToken(token, tokenSecret));
            return auth;
        }
        case Accounts.AUTH_TYPE_BASIC: {
            final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME));
            final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME));
            final String loginName = username != null ? username : screenName;
            final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD));
            if (isEmpty(loginName) || isEmpty(password))
                return null;
            return new BasicAuthorization(loginName, password);
        }
        default: {
            return null;
        }
        }
    } finally {
        c.close();
    }
}

From source file:inujini_.hatate.service.OauthService.java

License:MIT License

/**
 * Oauth?./*from  w  w w .  j  av  a  2 s  .c  o  m*/
 * @param intent
 * @throws IllegalStateException intent?consumerKey?consumerKey???????????.
 */
private void startOauth(Intent intent) {
    // validate
    if (!intent.hasExtra(KEY_CONSUMER_KEY) || !intent.hasExtra(KEY_CONSUMER_SECRET)) {
        IllegalStateException e = new IllegalStateException(
                "In startOauth, intent's extra must have consumerKey and consumerSecret.");

        CallbackBroadcastReceiver.Data data = CallbackBroadcastReceiver.Data.create(e);
        sendBroadcast(CallbackBroadcastReceiver.createIntent(data));
        return;
    }

    Configuration conf = new ConfigurationBuilder().setOAuthConsumerKey(intent.getStringExtra(KEY_CONSUMER_KEY))
            .setOAuthConsumerSecret(intent.getStringExtra(KEY_CONSUMER_SECRET)).build();

    OAuthAuthorization oauth = new OAuthAuthorization(conf);
    oauth.setOAuthAccessToken(null);

    // ?URI?
    String uri;
    try {
        uri = oauth.getOAuthRequestToken(URI_CALLBACK).getAuthorizationURL();
    } catch (TwitterException e) {
        e.printStackTrace();
        CallbackBroadcastReceiver.Data data = CallbackBroadcastReceiver.Data.create(e);
        sendBroadcast(CallbackBroadcastReceiver.createIntent(data));
        return;
    }

    // OAuthAuthorization?
    try {
        serialize(oauth, "oauth.dat");
    } catch (IOException e) {
        e.printStackTrace();
        CallbackBroadcastReceiver.Data data = CallbackBroadcastReceiver.Data.create(e);
        sendBroadcast(CallbackBroadcastReceiver.createIntent(data));
        return;
    }

    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

From source file:mx.bigdata.t4j.TwitterStreamFactory.java

License:Apache License

/**
 * Returns a OAuth Authenticated instance.<br>
 * consumer key and consumer Secret must be provided by twitter4j.properties,
 * or system properties./*from w w  w .j a v  a2  s. c o m*/
 * Unlike {@link TwitterStream#setOAuthAccessToken(twitter4j.auth.AccessToken)}, 
 * this factory method potentially returns a cached instance.
 *
 * @param accessToken access token
 * @return an instance
 */
public TwitterStream getInstance(AccessToken accessToken, StreamListener listener) {
    String consumerKey = conf.getOAuthConsumerKey();
    String consumerSecret = conf.getOAuthConsumerSecret();
    if (null == consumerKey && null == consumerSecret) {
        throw new IllegalStateException("Consumer key and Consumer secret not supplied.");
    }
    OAuthAuthorization oauth = new OAuthAuthorization(conf);
    oauth.setOAuthAccessToken(accessToken);
    return getInstance(conf, oauth, listener);
}

From source file:mx.bigdata.t4j.TwitterStreamImpl.java

License:Apache License

private void init() {
    if (null == auth) {
        // try to populate OAuthAuthorization if available in the configuration
        String consumerKey = conf.getOAuthConsumerKey();
        String consumerSecret = conf.getOAuthConsumerSecret();
        // try to find oauth tokens in the configuration
        if (null != consumerKey && null != consumerSecret) {
            OAuthAuthorization oauth = new OAuthAuthorization(conf);
            String accessToken = conf.getOAuthAccessToken();
            String accessTokenSecret = conf.getOAuthAccessTokenSecret();
            if (null != accessToken && null != accessTokenSecret) {
                oauth.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
            }/*from w  w w. j  a  va 2s.co  m*/
            this.auth = oauth;
        } else {
            this.auth = NullAuthorization.getInstance();
        }
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context,
        final ParcelableCredentials account) {
    if (context == null || account == null)
        return null;
    switch (account.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE);
        // Here I use old consumer key/secret because it's default
        // key for older
        // versions
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        if (!isEmpty(account.api_url_format)) {
            final String versionSuffix = account.no_version_suffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(account.api_url_format, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(account.api_url_format, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(account.api_url_format, "upload", versionSuffix));
            cb.setOAuthAuthorizationURL(getApiUrl(account.api_url_format, null, null));
            if (!account.same_oauth_signing_url) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }//from ww w.ja  v  a 2s.c  om
        }
        if (!isEmpty(account.consumer_key) && !isEmpty(account.consumer_secret)) {
            cb.setOAuthConsumerKey(account.consumer_key);
            cb.setOAuthConsumerSecret(account.consumer_secret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        }
        final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
        auth.setOAuthAccessToken(new AccessToken(account.oauth_token, account.oauth_token_secret));
        return auth;
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = account.screen_name;
        final String username = account.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = account.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new BasicAuthorization(loginName, password);
    }
    default: {
        return null;
    }
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context, final long accountId) {

    final String where = Expression.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL();
    final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI,
            Accounts.COLUMNS, where, null, null);
    if (c == null)
        return null;
    try {/*from  w w  w  .  ja v a 2  s  .c  om*/
        if (!c.moveToFirst())
            return null;

        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
        case Accounts.AUTH_TYPE_OAUTH:
        case Accounts.AUTH_TYPE_XAUTH: {
            final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                    Context.MODE_PRIVATE);
            // Here I use old consumer key/secret because it's default
            // key for older
            // versions
            final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
            final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
            final ConfigurationBuilder cb = new ConfigurationBuilder();
            final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT));
            final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY)));
            final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET)));
            final boolean sameOAuthSigningUrl = c
                    .getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1;
            if (!isEmpty(apiUrlFormat)) {
                cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", "/1.1/"));
                cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
                cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", "/1.1/"));
                cb.setOAuthAuthorizationURL(getApiUrl(apiUrlFormat, null, null));
                if (!sameOAuthSigningUrl) {
                    cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                    cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                    cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
                }
            }
            if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
                cb.setOAuthConsumerKey(consumerKey);
                cb.setOAuthConsumerSecret(consumerSecret);
            } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
                cb.setOAuthConsumerKey(prefConsumerKey);
                cb.setOAuthConsumerSecret(prefConsumerSecret);
            } else {
                cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            }
            final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            auth.setOAuthAccessToken(new AccessToken(token, tokenSecret));
            return auth;
        }
        case Accounts.AUTH_TYPE_BASIC: {
            final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME));
            final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME));
            final String loginName = username != null ? username : screenName;
            final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD));
            if (isEmpty(loginName) || isEmpty(password))
                return null;
            return new BasicAuthorization(loginName, password);
        }
        default: {
            return null;
        }
        }
    } finally {
        c.close();
    }
}