Example usage for twitter4j.auth AccessToken getUserId

List of usage examples for twitter4j.auth AccessToken getUserId

Introduction

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

Prototype


public long getUserId() 

Source Link

Usage

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 . j a v a  2s  .  c om
        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:de.jetwick.ui.MySession.java

License:Apache License

public Cookie afterLogin(AccessToken token, ElasticUserSearch uSearch, WebResponse response)
        throws TwitterException {
    if (email == null)
        throw new IllegalArgumentException("Email not available. Please login again.");

    twitterSearch.initTwitter4JInstance(token.getToken(), token.getTokenSecret(), true);
    twitterSearchInitialized = true;//  www  .  j a v  a  2s .  c  om
    //            logger.info("TOKEN:" + token);
    Cookie cookie = new Cookie(TwitterSearch.COOKIE, token.getToken());
    // LATER: use https: cookie.setSecure(true);
    cookie.setComment("Supply autologin for " + Helper.JETSLIDE_URL);
    // four weeks
    cookie.setMaxAge(4 * 7 * 24 * 60 * 60);
    // set path because the cookie should be sent for / and /slide* and /login*
    cookie.setPath("/");
    response.addCookie(cookie);

    // get current infos
    User twitterUser = twitterSearch.getTwitterUser();

    // get current saved searches and update with current twitter infos
    JUser tmpUser = uSearch.findById(token.getUserId());
    if (tmpUser == null) {
        tmpUser = uSearch.findByScreenName(twitterUser.getScreenName());
        if (tmpUser == null)
            tmpUser = new JUser(twitterUser.getScreenName());
    }

    tmpUser.updateFieldsBy(twitterUser);
    // now set email entered on form one page before twitter redirect
    tmpUser.setEmail(email);
    tmpUser.setTwitterToken(token.getToken());
    tmpUser.setTwitterTokenSecret(token.getTokenSecret());
    tmpUser.setLastVisit(new Date());

    // save user into user index
    uSearch.save(tmpUser, false);

    // save user into session
    setUser(tmpUser);

    logger.info("[stats] user login:" + twitterUser.getScreenName() + " " + tmpUser.getScreenName());
    return cookie;
}

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

License:Open Source License

public static ContentValues makeAccountContentValuesOAuth(final Configuration conf,
        final AccessToken accessToken, final User user, final int authType, final int color,
        final String apiUrlFormat, final boolean sameOAuthSigningUrl, final boolean noVersionSuffix) {
    if (user == null || user.getId() <= 0 || accessToken == null || user.getId() != accessToken.getUserId())
        return null;
    final ContentValues values = new ContentValues();
    values.put(Accounts.OAUTH_TOKEN, accessToken.getToken());
    values.put(Accounts.OAUTH_TOKEN_SECRET, accessToken.getTokenSecret());
    values.put(Accounts.CONSUMER_KEY, conf.getOAuthConsumerKey());
    values.put(Accounts.CONSUMER_SECRET, conf.getOAuthConsumerSecret());
    values.put(Accounts.AUTH_TYPE, authType);
    values.put(Accounts.ACCOUNT_ID, user.getId());
    values.put(Accounts.SCREEN_NAME, user.getScreenName());
    values.put(Accounts.NAME, user.getName());
    values.put(Accounts.PROFILE_IMAGE_URL, ParseUtils.parseString(user.getProfileImageUrlHttps()));
    values.put(Accounts.PROFILE_BANNER_URL, ParseUtils.parseString(user.getProfileBannerImageUrl()));
    values.put(Accounts.COLOR, color);//from w  w  w. j  a va2  s.c  o  m
    values.put(Accounts.IS_ACTIVATED, 1);
    values.put(Accounts.API_URL_FORMAT, apiUrlFormat);
    values.put(Accounts.SAME_OAUTH_SIGNING_URL, sameOAuthSigningUrl);
    values.put(Accounts.NO_VERSION_SUFFIX, noVersionSuffix);
    return values;
}

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 w  w  .  jav a  2  s.c  o m*/
        }

        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  www  . ja v  a 2 s .co 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   ww w .j a  v a  2 s .  c o  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:jp.xxxxxxxx.l3fish.twnyaan.repository.AccessTokenRepository.java

License:Open Source License

/**
 * AccessTokenXML???????????//from  w  w w .  jav  a  2s . c o  m
 *
 * @param accessToken AccessToken
 * @return ??????{@code true}, ???{@code false}
 */
public boolean save(AccessToken accessToken) {
    AccessTokenBean bean = new AccessTokenBean(accessToken.getUserId(), accessToken.getToken(),
            accessToken.getTokenSecret());
    return BeanFileIOUtil.writeBean(FILE_NAME, bean);
}

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 {//from ww  w. j  a  v a  2 s.c  o  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.jeremybrooks.suprsetr.twitter.TwitterHelper.java

License:Open Source License

/**
 * Authenticates the user.//from   w w w.  jav a2s.c  o m
 * <p/>
 * <p>This method will use the OAuth method of authentication. The user's
 * browser will be opened, and they will be prompted for the PIN. The
 * authentication token data will then be saved in the database.</p>
 *
 * @throws Exception if there are any errors.
 */
public static void authenticate() throws Exception {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("net.jeremybrooks.suprsetr.misc");
    twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(Main.getPrivateProperty("TWITTER_CONSUMER_KEY"),
            Main.getPrivateProperty("TWITTER_CONSUMER_SECRET"));
    try {
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken;
        String url = requestToken.getAuthenticationURL();
        java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));

        String pin = JOptionPane.showInputDialog(null,
                resourceBundle.getString("TwitterHelper.dialog.pin.message"),
                resourceBundle.getString("TwitterHelper.dialog.pin.title"), JOptionPane.INFORMATION_MESSAGE);
        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        // Save the access token
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_USERID, Long.toString(accessToken.getUserId()));
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_USERNAME,
                twitter.verifyCredentials().getName());
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_TOKEN, accessToken.getToken());
        LookupDAO.setKeyAndValue(SSConstants.LOOKUP_KEY_TWITTER_TOKEN_SECRET, accessToken.getTokenSecret());
    } catch (Exception e) {
        twitter = null;
        throw 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  ava 2 s  .co  m
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
    }
    }
}