Example usage for twitter4j.auth AccessToken getScreenName

List of usage examples for twitter4j.auth AccessToken getScreenName

Introduction

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

Prototype


public String getScreenName() 

Source Link

Usage

From source file:com.gmail.altakey.joanne.service.TwitterAuthService.java

License:Apache License

public void setAccessToken(final AccessToken token) {
    final SharedPreferences prefs = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
    prefs.edit().putString(KEY_TOKEN, token.getToken()).putString(KEY_TOKEN_SECRET, token.getTokenSecret())
            .putString(KEY_SCREEN_NAME, token.getScreenName()).commit();
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

License:Apache License

protected Task<AccessToken> doGetAccessToken(final Twitter instance, Bundle bundle) {
    final Task<AccessToken>.TaskCompletionSource source = Task.create();

    new AsyncTask<Bundle, Void, Object>() {

        @Override//from w  ww.ja v a 2s  .  com
        protected Object doInBackground(Bundle... params) {
            try {
                Bundle result = params[0];

                RequestToken token = (RequestToken) result.getSerializable("request_token");
                String verifier = result.getString("oauth_verifier");

                AccessToken accessToken = instance.getOAuthAccessToken(token, verifier);
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getScreenName() = " + accessToken.getScreenName());
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getUserId() = " + accessToken.getUserId());
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getToken() = " + accessToken.getToken());
                Log.d(BuildConfig.DEBUG_TAG, "accessToken.getTokenSecret() = " + accessToken.getTokenSecret());

                return accessToken;
            } catch (TwitterException e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o instanceof AccessToken) {
                source.trySetResult((AccessToken) o);
            } else {
                source.trySetError((Exception) o);
            }

        }
    }.execute(bundle);
    return source.getTask();
}

From source file:com.mothsoft.alexis.web.TwitterBackingBean.java

License:Apache License

public String oauthCallback() {
    if (this.oauthToken != null && this.oauthVerifier != null && this.requestToken != null) {

        final AccessToken accessToken = this.twitterService.getAccessToken(this.requestToken,
                this.oauthVerifier);

        final User user = this.userService.getUser(CurrentUserUtil.getCurrentUserId());
        final SocialConnection socialConnection = new SocialConnection(user, accessToken.getScreenName(),
                accessToken.getToken(), accessToken.getTokenSecret(), SocialNetworkType.T);

        // FIXME - dupe logic and stuff
        this.userService.addOrUpdateSocialConnection(user, socialConnection);

        final TwitterSource twitterSource = new TwitterSource(socialConnection);
        twitterSource.setUserId(user.getId());
        this.sourceService.add(twitterSource);
    }/*w w  w  . j av a  2s.co  m*/

    return "/sources/list?faces-redirect=true";
}

From source file:com.twitstreet.servlet.CallBackServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    response.setHeader("Pragma", "no-cache"); //HTTP 1.0
    response.setDateHeader("Expires", 0); //prevents caching at the proxy server

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret());

    RequestToken requestToken = (RequestToken) request.getSession().getAttribute(REQUEST_TOKEN);
    String verifier = request.getParameter(OAUTH_VERIFIER);
    try {//from w  ww. ja  v  a  2s. c  o  m
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        long userId = accessToken.getUserId();
        String screenName = accessToken.getScreenName();
        String oauthToken = accessToken.getToken();
        String oauthTokenSecret = accessToken.getTokenSecret();
        User user = null;
        user = userMgr.getUserById(userId);
        //new user
        if (user == null) {
            twitter4j.User twUser = twitter.showUser(userId);
            user = new User();
            user.setId(userId);
            user.setUserName(screenName);
            user.setLastIp(request.getRemoteAddr());
            user.setOauthToken(oauthToken);
            user.setOauthTokenSecret(oauthTokenSecret);
            user.setCash(configMgr.getInitialMoney());
            user.setPictureUrl(twUser.getProfileImageURL().toExternalForm());

            user.setDescription(twUser.getDescription());
            user.setLongName(twUser.getName());
            user.setLocation(twUser.getLocation());
            user.setLanguage(twUser.getLang());
            user.setUrl(twUser.getURL() == null ? null : twUser.getURL().toExternalForm());

            userMgr.saveUser(user);
            String referenceId = (String) request.getSession().getAttribute(HomePageServlet.REFERENCE_ID);
            long referenceLong = -1;
            try {
                referenceLong = Long.parseLong(referenceId);
            } catch (NumberFormatException e) {
                logger.error("Parsing reference id failed: " + referenceId);
            }
            if (referenceLong > -1) {
                userMgr.invite(referenceLong, user.getId());
            }
            request.getSession().removeAttribute(HomePageServlet.REFERENCE_ID);

        } else {
            //existing user logging in again
            user = new User();
            user.setId(userId);
            user.setUserName(screenName);
            user.setLastIp(request.getRemoteHost());
            user.setOauthToken(oauthToken);
            user.setOauthTokenSecret(oauthTokenSecret);
            user.setAutoPlayer(false);
            userMgr.updateUser(user);
        }
        request.getSession().setAttribute(User.USER_ID, user.getId());
        Cookie cookies[] = createCookie(userId, oauthToken);
        writeCookies(response, cookies);
    } catch (TwitterException e) {
        throw new ServletException(e);
    }
    response.sendRedirect(request.getContextPath() + "/");
}

From source file:inujini_.hatate.AccountListActivity.java

License:MIT License

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // add twitter account
    case R.id.menu_item_add:
        if (_receiver != null) {
            unregisterReceiver(_receiver);
            _receiver = null;/*from  w ww .  ja va 2s . c  om*/
        }

        val prog = new ProgressDialog(this);
        prog.setMessage("OAuth??????????????????");
        prog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        _receiver = new CallbackBroadcastReceiver() {
            @Override
            public void onSuccess(AccessToken token) {
                _receiver = null;
                if (prog != null && prog.isShowing())
                    prog.dismiss();

                if (AccountDao.isExist(token.getUserId(), getApplicationContext())) {
                    Toast.makeText(getApplicationContext(),
                            "??????????",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(getApplicationContext(),
                        "OAuth??????\n??????????????",
                        Toast.LENGTH_SHORT).show();
                val accountData = new TwitterAccount();
                accountData.setScreenName(token.getScreenName());
                accountData.setAccessToken(token.getToken());
                accountData.setAccessSecret(token.getTokenSecret());
                accountData.setUse(true);
                accountData.setUserId(token.getUserId());

                AccountDao.insertAsync(accountData, getApplicationContext());
                ((AccountAdapter) getListAdapter()).add(accountData);
            }

            @Override
            public void onError(Exception exception) {
                _receiver = null;
                if (prog != null && prog.isShowing())
                    prog.dismiss();

                Toast.makeText(getApplicationContext(), "Oauth??????", Toast.LENGTH_LONG)
                        .show();
            }
        };

        registerReceiver(_receiver, CallbackBroadcastReceiver.createIntentFilter());

        // Oauth?
        val res = getApplicationContext().getResources();
        startService(OauthService.createIntent(res.getString(R.string.consumer_key),
                res.getString(R.string.consumer_secret), getApplicationContext()));
        prog.show();

        return true;
    default:
        return false;
    }
}

From source file:inujini_.hatate.NotificationActivity.java

License:MIT License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.notification);

    findPreference("isTweet").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override/*from w  w w.  ja v a  2  s. c  o  m*/
        public boolean onPreferenceClick(Preference preference) {
            if (!AccountDao.isAuthorized(getApplicationContext())) {

                new AlertDialog.Builder(NotificationActivity.this).setTitle("?").setMessage(
                        "?????OAuth?????\n??????")
                        .setPositiveButton("??", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

                                val prog = new ProgressDialog(NotificationActivity.this);
                                prog.setMessage(
                                        "OAuth??????????????????");
                                prog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

                                if (_receiver != null) {
                                    unregisterReceiver(_receiver);
                                    _receiver = null;
                                }

                                _receiver = new CallbackBroadcastReceiver() {
                                    @Override
                                    public void onSuccess(AccessToken token) {
                                        if (prog != null && prog.isShowing())
                                            prog.dismiss();
                                        Toast.makeText(getApplicationContext(),
                                                "OAuth??????\n??????????????",
                                                Toast.LENGTH_SHORT).show();
                                        val accountData = new TwitterAccount();
                                        accountData.setScreenName(token.getScreenName());
                                        accountData.setAccessToken(token.getToken());
                                        accountData.setAccessSecret(token.getTokenSecret());
                                        accountData.setUse(true);
                                        accountData.setUserId(token.getUserId());

                                        AccountDao.insert(accountData, getApplicationContext());

                                        val p = (CheckBoxPreference) findPreference("isTweet");
                                        p.setChecked(true);
                                        _receiver = null;
                                    }

                                    @Override
                                    public void onError(Exception exception) {
                                        if (prog != null && prog.isShowing())
                                            prog.dismiss();
                                        Toast.makeText(getApplicationContext(),
                                                "Oauth??????", Toast.LENGTH_LONG).show();
                                        _receiver = null;
                                    }
                                };

                                registerReceiver(_receiver, CallbackBroadcastReceiver.createIntentFilter());

                                // Oauth?
                                val res = getApplicationContext().getResources();
                                startService(OauthService.createIntent(res.getString(R.string.consumer_key),
                                        res.getString(R.string.consumer_secret), getApplicationContext()));
                                prog.show();
                            }
                        }).setNegativeButton("", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();

                ((CheckBoxPreference) preference).setChecked(false);

                return true;
            }

            return false;
        }
    });

    val lightColorPref = (ListPreference) findPreference("lightColor");
    lightColorPref.setSummary(getString(R.string.summary_light, getApplicationContext().getLightColorName()));
    lightColorPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            preference.setSummary(getString(R.string.summary_light,
                    getApplicationContext().getLightColorName(newValue.toString())));
            return true;
        }
    });

    val snoozeTimePref = (ValidatableEditTextPreference) findPreference("snoozeTime");
    snoozeTimePref.setSummary(getString(R.string.summary_snooze, getApplicationContext().getSnoozeTime()));
    snoozeTimePref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
    snoozeTimePref.setValidation("0????????",
            new TextValidator() {
                @Override
                public boolean validation(String s) {
                    if (s.equals(""))
                        return false;

                    val i = Integer.parseInt(s);
                    return i > 0;
                }
            });
    snoozeTimePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            preference.setSummary(getString(R.string.summary_snooze, Integer.parseInt(newValue.toString())));
            return true;
        }
    });

    val vibrationPatternPref = (EventableListPreference) findPreference("vibrationPattern");
    vibrationPatternPref.setSummary(
            getString(R.string.summary_vibration, getApplicationContext().getVibrationPatternName()));
    vibrationPatternPref.setOnChosenListener(new OnChosenListener() {
        @Override
        public void onChosen(int index, String entry, String entryValue) {
            val vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(entryValue.split(",").linq().select(new Func1<String, Long>() {
                @Override
                public Long call(String x) {
                    return Long.parseLong(x);
                }
            }).toLongArray(), -1);
        }
    });
    vibrationPatternPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            preference.setSummary(getString(R.string.summary_vibration,
                    getApplicationContext().getVibrationPatternName(newValue.toString())));
            return true;
        }
    });

    val yoPref = findPreference("yo");

    // ?Yo??????????
    if (!RepeatYoService.isSentYo(getApplicationContext())) {
        yoPref.setEnabled(false);
    }

    yoPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (hasYo()) {
                return false;
            }

            val i = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.yo_invate_uri)));
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
            return true;
        }
    });

    yoPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue == null || "".equals(newValue))
                return false;

            preference.setEnabled(false);
            Util.setRepeatYo(getApplicationContext());
            return true;
        }
    });
}

From source file:jp.wda.azeda.core.logics.impl.TwitterServiceImpl.java

License:Apache License

/** {@inheritDoc} */
@Override/*from   www. jav  a 2 s.  co  m*/
public void registerAccessToken(String requestID, String oauthVerifier) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken requestToken = requestTokens.get(requestID);
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier);

    StoredAccessToken dbToken = new StoredAccessToken();
    dbToken.setUserID(accessToken.getUserId());
    dbToken.setAccount(accessToken.getScreenName());
    dbToken.setAccessToken(accessToken.getToken());
    dbToken.setAccessTokenSecret(accessToken.getTokenSecret());
    dbToken.setUpdatedAt(new java.sql.Timestamp(System.currentTimeMillis()));

    try {
        accessTokensDao.update(dbToken);
    } catch (NotSingleRowUpdatedRuntimeException ex) {
        accessTokensDao.insert(dbToken);
    }

    crawlerFactory.startCrawl(dbToken.getUserID());
}

From source file:net.codestory.http.filters.twitter.TwitterAuthenticator.java

License:Apache License

@Override
public User authenticate(String oauthToken, String oauthVerifier) {
    Twitter twitter = twitterFactory.getInstance();
    try {// w ww  .ja v a  2 s  .co  m
        AccessToken accessToken = twitter.getOAuthAccessToken(oauthRequestByToken.remove(oauthToken),
                oauthVerifier);

        twitter4j.User user = twitter.users().showUser(accessToken.getUserId());

        return new User(accessToken.getUserId(), accessToken.getScreenName(), accessToken.getToken(),
                accessToken.getTokenSecret(), user.getBiggerProfileImageURL());
    } catch (TwitterException e) {
        throw new AuthenticationException(e);
    }
}

From source file:net.lacolaco.smileessence.activity.OAuthActivity.java

License:Open Source License

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button_oauth_auth: {
        AccessToken accessToken = oauthSession.getAccessToken(pinEditText.getText().toString());
        if (accessToken != null) {
            Intent intent = new Intent();
            intent.putExtra(OAuthSession.KEY_TOKEN, accessToken.getToken());
            intent.putExtra(OAuthSession.KEY_TOKEN_SECRET, accessToken.getTokenSecret());
            intent.putExtra(OAuthSession.KEY_USER_ID, accessToken.getUserId());
            intent.putExtra(OAuthSession.KEY_SCREEN_NAME, accessToken.getScreenName());
            setResult(RESULT_OK, intent);
            finish();/*from w  w  w.j  a v  a  2  s.co  m*/
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
    }
    }
}

From source file:net.nokok.twitduke.core.account.AccountManagerImpl.java

License:Open Source License

@Override
public void addAccount(AccessToken accessToken) {
    boolean isPrimary = !hasValidAccount();
    File dir = DirectoryHelper.createAccountDirectory(accessToken.getScreenName());
    if (isPrimary) {
        try {/*from   w  w w  . j av  a2s  .c o  m*/
            new File(dir, "primary").createNewFile();
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }
    Writer<AccessToken> writer = new AccessTokenIOSelector(new ScreenName(accessToken.getScreenName()))
            .getWriter();
    writer.write(accessToken);
}