Example usage for twitter4j.auth OAuthAuthorization OAuthAuthorization

List of usage examples for twitter4j.auth OAuthAuthorization OAuthAuthorization

Introduction

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

Prototype

public OAuthAuthorization(Configuration conf) 

Source Link

Usage

From source file:au.com.tyo.services.sn.twitter.SNTwitter.java

License:Apache License

public void createInstance() {
    synchronized (this) {
        try {// w  w  w  .j a v  a2 s  . c  om
            if (hasSecret()) {
                AccessToken accessToken = new AccessToken(secretOAuth.getToken().getToken(),
                        secretOAuth.getToken().getSecret());

                Configuration conf = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey)
                        .setOAuthConsumerSecret(consumerKeySecret).setOAuthAccessToken(accessToken.getToken())
                        .setOAuthAccessTokenSecret(accessToken.getTokenSecret()).build();

                OAuthAuthorization auth = new OAuthAuthorization(conf);
                twitter = new TwitterFactory().getInstance(auth);
                authenticated = true;
            }
        } catch (Exception ex) {
            authenticated = false;
            twitter = null;
        }

        try {
            /*
             * it is better to use the id, because people would change their name
             */
            long sourceId = Integer.valueOf(secretOAuth.getId().getToken());
            user = twitter.showUser(sourceId);
            //              user = twitter.showUser(userInfo.getName());

            secretOAuth.getId().setToken(String.valueOf(user.getId()));
            secrets.save(secretOAuth.getId());

            userInfo.setName(user.getScreenName());
            alias.setName(user.getName());

            saveUserInfo();
            saveAlias();
            userProfileImageUrl = getUserAvatarUrl();
        } catch (Exception ex) {
        }
    }
}

From source file:br.shura.team.mpsbot.runtime.ConnectedBot.java

License:Open Source License

public void connect() {
    ApiKeys keys = getBot().getApiKeys();

    if (!isConnected()) {
        Configuration configuration = new ConfigurationBuilder().setOAuthAccessToken(keys.getAccessToken())
                .setOAuthAccessTokenSecret(keys.getAccessTokenSecret())
                .setOAuthConsumerKey(keys.getConsumerKey()).setOAuthConsumerSecret(keys.getConsumerSecret())
                .build();//from   w w w  . ja  va  2 s  . c  o  m
        OAuthAuthorization auth = new OAuthAuthorization(configuration);
        TwitterStreamFactory streamFactory = new TwitterStreamFactory(configuration);
        ImageUploadFactory uploadFactory = new ImageUploadFactory(configuration);

        this.streamer = streamFactory.getInstance(auth);
        this.uploader = uploadFactory.getInstance(auth);
    }
}

From source file:com.ak.android.akplaza.common.sns.twitter.TwitterController.java

License:Open Source License

public static void write(String content, Activity at) {
    //      Log.d(TAG, "content : " + content);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String fileName = "example.jpg";
    InputStream is = null;/*w  w  w  . j a  va2 s  .  com*/

    try {
        if (new File(path + File.separator + fileName).exists())
            is = new FileInputStream(path + File.separator + fileName);
        else
            is = null;

        ConfigurationBuilder cb = new ConfigurationBuilder();
        String oAuthAccessToken = acToken.getToken();
        String oAuthAccessTokenSecret = tacs;
        String oAuthConsumerKey = C.TWITTER_CONSUMER_KEY;
        String oAuthConsumerSecret = C.TWITTER_CONSUMER_SECRET;
        cb.setOAuthAccessToken(oAuthAccessToken);
        cb.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
        cb.setOAuthConsumerKey(oAuthConsumerKey);
        cb.setOAuthConsumerSecret(oAuthConsumerSecret);
        Configuration config = cb.build();
        OAuthAuthorization auth = new OAuthAuthorization(config);

        TwitterFactory tFactory = new TwitterFactory(config);
        Twitter twitter = tFactory.getInstance();
        //         ImageUploadFactory iFactory = new ImageUploadFactory(getConfiguration(C.TWITPIC_API_KEY));
        //         ImageUpload upload = iFactory.getInstance(MediaProvider.TWITPIC, auth);

        if (is != null) {
            //        String strResult = upload.upload("example.jpg", is, mEtContent.getText().toString());
            //        twitter.updateStatus(mEtContent.getText().toString() + " " + strResult);
        } else
            twitter.updateStatus(content);
        new AlertDialog.Builder(at).setMessage(" ? ? ?.")
                .setPositiveButton("?", null).show();
    } catch (Exception e) {
        e.printStackTrace();
        new AlertDialog.Builder(at).setMessage("? ?  ")
                .setPositiveButton("?", null).show();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
        }
    }

}

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

@SuppressWarnings("unchecked")
RemoteUserInfo zgetUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential,
        AuthorizationResponse auth)/*from www.ja v a2  s.  c om*/
        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);
            }//w  w  w . jav  a2 s .  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_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 ww w  .jav a2  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);
            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:hashimotonet.UpdateStatus.java

License:Apache License

/**
 * Twitter?/*from  w  w  w  . j  av a2  s  . c o  m*/
 * @throws TwitterException 
 */
private void connectTwitter() throws TwitterException {
    // Twitetr4j??
    Configuration conf = ConfigurationContext.getInstance();
    // OauthF?IuWFNg??
    OAuthAuthorization Oauth = new OAuthAuthorization(conf);
    // OauthF?IuWFNgconsumerKeyconsumerSecret?
    Oauth.setOAuthConsumer(Globals.KEY, Globals.SECRET);

    //       // NGXgg?[N??
    RequestToken sRequestToken = null;
    try {
        sRequestToken = Oauth.getOAuthRequestToken();
    } catch (TwitterException e) {
        throw new TwitterException(e.toString());
    }
    String url = sRequestToken.getAuthorizationURL();
    System.out.println("Url = " + url);
}

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

License:MIT License

/**
 * Oauth?.//from w  ww  .  j a  v a2s.  com
 * @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:io.spring.batch.spark.Main.java

License:Apache License

public static void main(String[] args) {
    // URL of the Spark cluster
    String sparkUrl = "local[2]";

    SparkConf conf = new SparkConf();

    conf.setMaster(sparkUrl);/*  w ww.ja v  a  2 s. c  o m*/
    conf.setAppName("Twitter");
    conf.validateSettings();

    JavaStreamingContext ssc = new JavaStreamingContext(sparkUrl, "Twitter", new Duration(1000));

    Configuration configuration = new ConfigurationBuilder()
            .setOAuthConsumerKey(System.getProperty("twitter4j.oauth.consumerKey"))
            .setOAuthConsumerSecret(System.getProperty("twitter4j.oauth.consumerSecret"))
            .setOAuthAccessToken(System.getProperty("twitter4j.oauth.accessKey"))
            .setOAuthAccessTokenSecret(System.getProperty("twitter4j.oauth.accessSecret")).setDebugEnabled(true)
            .build();

    JavaDStream<Status> tweets = TwitterUtils.createStream(ssc, new OAuthAuthorization(configuration));

    tweets.map(new Function<Status, String>() {
        public String call(Status status) {
            return status.getText();
        }
    }).dstream().saveAsTextFiles("hdfs://localhost:8020/spark/twitter/", "txt");

    ssc.start();

    // Just run stream for 20 seconds
    ssc.awaitTermination(20000);
}

From source file:jp.typosone.android.azarashi.OAuthActivity.java

License:Apache License

/**
 * Twitter OAuth ?????????//from   w  w  w.jav  a 2s  .c o m
 * <p/>
 * OAuth ????? RequestToken ??
 * ????AccessToken ??????URL???????
 *
 * @see Activity#onCreate
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Configuration conf = ConfigurationContext.getInstance();
    mOAuth = new OAuthAuthorization(conf);
    RequestTokenLoaderCallbacks mRequestCallbacks = new RequestTokenLoaderCallbacks();
    mAccessCallbacks = new AccessTokenLoaderCallbacks();

    getLoaderManager().initLoader(LID_REQ, null, mRequestCallbacks);
}