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:au.com.tyo.services.sn.twitter.SNTwitter.java

License:Apache License

@Override
public void retrieveAccessToken() throws TwitterException {
    Twitter t = this.getTwitter();

    assert (requestToken != null);

    String token = callback.getQueryParameter("oauth_token");
    String verifier = callback.getQueryParameter("oauth_verifier");

    AccessToken accessToken = t.getOAuthAccessToken(this.requestToken, verifier);

    secretOAuth.getId().setToken(String.valueOf(accessToken.getUserId()));

    secretOAuth.getToken().setToken(accessToken.getToken());
    secretOAuth.getToken().setSecret(accessToken.getTokenSecret());

    secrets.save(secretOAuth.getId());/*from ww  w.  j  a v  a2 s  . c  om*/
    secrets.save(secretOAuth.getToken());
}

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

License:Apache License

@Override
public void retrieveAccessToken(Uri uri) throws TwitterException {
    Twitter t = this.getTwitter();

    assert (requestToken != null);

    String token = uri.getQueryParameter("oauth_token");
    String verifier = uri.getQueryParameter("oauth_verifier");

    AccessToken accessToken = t.getOAuthAccessToken(this.requestToken, verifier);

    secretOAuth.getId().setToken(String.valueOf(accessToken.getUserId()));

    secretOAuth.getToken().setToken(accessToken.getToken());
    secretOAuth.getToken().setSecret(accessToken.getTokenSecret());

    secrets.save(secretOAuth.getId());/*from   ww w  .  ja  v a2 s .c o m*/
    secrets.save(secretOAuth.getToken());
}

From source file:co.uk.socialticker.ticker.TickerActivity.java

License:Open Source License

private void onCreateTwitter() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);/*from w w  w.j av  a 2s . c  o  m*/

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(TickerActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
        // Internet Connection is not present
        alert.showAlertDialog(TickerActivity.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // All UI elements
    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
    btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
    txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
    lblUpdate = (TextView) findViewById(R.id.lblUpdate);

    llTwitter = (LinearLayout) findViewById(R.id.llTwitter);
    llCast = (LinearLayout) findViewById(R.id.llCast);

    /**
     * Twitter login button click event will call loginToTwitter() function
     * */
    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login twitter function
            loginToTwitter();
        }
    });

    /**
     * Button click event to Update Status, will call updateTwitterStatus()
     * function
     * */
    btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call update status function
            // Get the status from EditText
            String status = txtUpdate.getText().toString();

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    /**
     * Button click event for logout from twitter
     * */
    btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call logout twitter function
            logoutFromTwitter();
        }
    });

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */
    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                // Shared Preferences
                Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Hide login button
                btnLoginTwitter.setVisibility(View.GONE);

                // Show Update Twitter
                lblUpdate.setVisibility(View.VISIBLE);
                txtUpdate.setVisibility(View.VISIBLE);
                btnUpdateStatus.setVisibility(View.VISIBLE);
                btnLogoutTwitter.setVisibility(View.VISIBLE);

                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);

            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }
}

From source file:com.dwdesign.tweetings.util.Utils.java

License:Open Source License

public static ContentValues makeAccountContentValues(final int color, final AccessToken access_token,
        final User user, final String rest_base_url, final String oauth_base_url,
        final String signing_rest_base_url, final String signing_oauth_base_url, final String search_base_url,
        final String upload_base_url, final String basic_password, final int auth_type) {
    if (user == null || user.getId() <= 0)
        return null;
    final ContentValues values = new ContentValues();
    switch (auth_type) {
    case Accounts.AUTH_TYPE_TWIP_O_MODE: {
        break;/*from   w  w w .j a va  2  s . co m*/
    }
    case Accounts.AUTH_TYPE_BASIC: {
        if (basic_password == null)
            return null;
        values.put(Accounts.BASIC_AUTH_PASSWORD, basic_password);
        break;
    }
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        if (access_token == null)
            return null;
        if (user.getId() != access_token.getUserId())
            return null;
        values.put(Accounts.OAUTH_TOKEN, access_token.getToken());
        values.put(Accounts.TOKEN_SECRET, access_token.getTokenSecret());
        break;
    }
    }
    values.put(Accounts.AUTH_TYPE, auth_type);
    values.put(Accounts.USER_ID, user.getId());
    values.put(Accounts.USERNAME, user.getScreenName());
    values.put(Accounts.PROFILE_IMAGE_URL, user.getProfileImageURL().toString());
    values.put(Accounts.USER_COLOR, color);
    values.put(Accounts.IS_ACTIVATED, 1);
    values.put(Accounts.REST_BASE_URL, rest_base_url);
    values.put(Accounts.SIGNING_REST_BASE_URL, signing_rest_base_url);
    values.put(Accounts.SEARCH_BASE_URL, search_base_url);
    values.put(Accounts.UPLOAD_BASE_URL, upload_base_url);
    values.put(Accounts.OAUTH_BASE_URL, oauth_base_url);
    values.put(Accounts.SIGNING_OAUTH_BASE_URL, signing_oauth_base_url);
    return values;
}

From source file:com.jeanchampemont.wtfdyum.web.MainController.java

License:Apache License

@RequestMapping(value = "/signin/callback", method = RequestMethod.GET)
public RedirectView signinCallback(@RequestParam("oauth_verifier") final String verifier,
        final HttpServletRequest request) throws WTFDYUMException {
    final RequestToken requestToken = (RequestToken) request.getSession().getAttribute(SESSION_REQUEST_TOKEN);
    request.getSession().removeAttribute(SESSION_REQUEST_TOKEN);

    final AccessToken accessToken = twitterService.completeSignin(requestToken, verifier);

    if (principalService.get(accessToken.getUserId()) == null) {
        userService.addEvent(accessToken.getUserId(), new Event(EventType.REGISTRATION, null));
    }/*from w  w w  .  jav a  2s.  c  om*/

    final Principal user = new Principal(accessToken.getUserId(), accessToken.getToken(),
            accessToken.getTokenSecret());
    principalService.saveUpdate(user);
    authenticationService.authenticate(user);

    return new RedirectView("/user", true);
}

From source file:com.learnncode.twitter.TwitterLoginActivity.java

License:Apache License

private void saveAccessTokenAndFinish(final Uri uri) {
    new Thread(new Runnable() {
        @Override/*from  ww w . jav a 2 s  .  co m*/
        public void run() {
            String verifier = uri.getQueryParameter(AppConstants.IEXTRA_OAUTH_VERIFIER);
            try {
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
                AppSettings.setTwitterAccessTokenAndSecret(TwitterLoginActivity.this, accessToken.getToken(),
                        accessToken.getTokenSecret());
                TwitterLoginActivity.this.setResult(TWITTER_LOGIN_RESULT_CODE_SUCCESS);
                AppSettings.setTwitterUserId(getApplicationContext(), accessToken.getUserId());
            } catch (Exception e) {
                TwitterLoginActivity.this.setResult(TWITTER_LOGIN_RESULT_CODE_FAILURE);
            }
            TwitterLoginActivity.this.finish();
        }
    }).start();
}

From source file:com.marpies.ane.twitter.functions.GetLoggedInUserFunction.java

License:Apache License

@Override
public FREObject call(FREContext context, FREObject[] args) {
    super.call(context, args);

    mCallbackID = FREObjectUtils.getInt(args[0]);

    User user = TwitterAPI.getLoggedInUser();

    /* Return cached object */
    if (user != null) {
        try {//w  w  w .j a v a 2  s  . c o  m
            dispatchUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_ERROR,
                    StringUtils.getEventErrorJSON(mCallbackID, e.getMessage()));
        }
    }
    /* Request user info */
    else if (TwitterAPI.hasAccessTokens()) {
        AccessToken accessToken = TwitterAPI.getAccessToken();
        AsyncTwitter twitter = TwitterAPI.getAsyncInstance(accessToken);
        twitter.addListener(this);
        twitter.showUser(accessToken.getUserId());
    }
    /* User not logged in, error */
    else {
        AIR.dispatchEvent(AIRTwitterEvent.USER_QUERY_ERROR,
                StringUtils.getEventErrorJSON(mCallbackID, "User is not logged in."));
    }

    return null;
}

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  .  java2s . c o m
        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.speed.traquer.app.TraqComplaintTaxi.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_traq_complaint_taxi);
    easyTracker = EasyTracker.getInstance(TraqComplaintTaxi.this);
    //onCreateView(savedInstanceState);
    //InitialSetupUI();

    //Added UIHelper
    uiHelper = new UiLifecycleHelper(this, null);
    uiHelper.onCreate(savedInstanceState);

    inputTaxi = (EditText) findViewById(R.id.taxi_id);
    taxiDriver = (EditText) findViewById(R.id.taxi_driver);
    taxiLic = (EditText) findViewById(R.id.taxi_license);
    geoLat = (TextView) findViewById(R.id.geoLat);
    geoLong = (TextView) findViewById(R.id.geoLong);
    editDate = (EditText) findViewById(R.id.editDate);
    editTime = (EditText) findViewById(R.id.editTime);
    editCurrTime = (EditText) findViewById(R.id.editCurrTime);
    complainSend = (Button) findViewById(R.id.complain_send);

    ProgressBar barProgress = (ProgressBar) findViewById(R.id.progressLoading);
    ProgressBar barProgressFrom = (ProgressBar) findViewById(R.id.progressLoadingFrom);
    ProgressBar barProgressTo = (ProgressBar) findViewById(R.id.progressLoadingTo);

    actv_comp_taxi = (AutoCompleteTextView) findViewById(R.id.search_taxi_comp);
    SuggestionAdapter sa = new SuggestionAdapter(this, actv_comp_taxi.getText().toString(), taxiUrl,
            "compcode");
    sa.setLoadingIndicator(barProgress);
    actv_comp_taxi.setAdapter(sa);/*from   ww w. j ava2  s .c  om*/

    actv_from = (AutoCompleteTextView) findViewById(R.id.search_from);
    SuggestionAdapter saFrom = new SuggestionAdapter(this, actv_from.getText().toString(), locUrl, "location");
    saFrom.setLoadingIndicator(barProgressFrom);
    actv_from.setAdapter(saFrom);

    actv_to = (AutoCompleteTextView) findViewById(R.id.search_to);
    SuggestionAdapter saTo = new SuggestionAdapter(this, actv_to.getText().toString(), locUrl, "location");
    saTo.setLoadingIndicator(barProgressTo);
    actv_to.setAdapter(saTo);

    /*if(isNetworkConnected()) {
    new getTaxiComp().execute(new ApiConnector());
    }*/

    //Setting Fonts
    String fontPath = "fonts/segoeuil.ttf";
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    complainSend.setTypeface(tf);
    inputTaxi.setTypeface(tf);
    editDate.setTypeface(tf);
    editTime.setTypeface(tf);
    actv_comp_taxi.setTypeface(tf);
    actv_to.setTypeface(tf);
    actv_from.setTypeface(tf);
    taxiDriver.setTypeface(tf);
    taxiLic.setTypeface(tf);

    TextView txtComp = (TextView) findViewById(R.id.taxi_comp);
    txtComp.setTypeface(tf);

    TextView txtTaxiDriver = (TextView) findViewById(R.id.txt_taxi_driver);
    txtTaxiDriver.setTypeface(tf);

    TextView txtTaxiLic = (TextView) findViewById(R.id.txt_taxi_license);
    txtTaxiLic.setTypeface(tf);

    TextView txtNumber = (TextView) findViewById(R.id.taxi_number);
    txtNumber.setTypeface(tf);

    TextView txtTo = (TextView) findViewById(R.id.to);
    txtTo.setTypeface(tf);

    TextView txtDate = (TextView) findViewById(R.id.date);
    txtDate.setTypeface(tf);

    TextView txtTime = (TextView) findViewById(R.id.time);
    txtTime.setTypeface(tf);

    gLongitude = this.getIntent().getExtras().getDouble("Longitude");
    gLatitude = this.getIntent().getExtras().getDouble("Latitude");
    speedTaxiExceed = this.getIntent().getExtras().getDouble("SpeedTaxiExceed");

    isTwitterSelected = false;
    isFacebookSelected = false;
    isDefaultSelected = false;
    isSmsSelected = false;

    geoLat.setText(Double.toString(gLatitude));
    geoLong.setText(Double.toString(gLongitude));

    rateBtnBus = (ImageButton) findViewById(R.id.btn_rate_bus);

    rateBtnBus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (actv_comp_taxi.length() != 0) {
                final AlertDialog.Builder alertBox = new AlertDialog.Builder(TraqComplaintTaxi.this);
                alertBox.setIcon(R.drawable.info_icon);
                alertBox.setCancelable(false);
                alertBox.setTitle("Do you want to cancel complaint?");
                alertBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        // finish used for destroyed activity
                        easyTracker.send(MapBuilder
                                .createEvent("Complaint", "Cancel Complaint (Yes)", "Complaint event", null)
                                .build());
                        finish();
                    }
                });

                alertBox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        easyTracker.send(MapBuilder
                                .createEvent("Complaint", "Cancel Complaint (No)", "Complaint event", null)
                                .build());
                        dialog.cancel();
                    }
                });

                alertBox.show();
            } else {
                Intent intent = new Intent(getApplicationContext(), TraqComplaint.class);
                intent.putExtra("Latitude", gLatitude);
                intent.putExtra("Longitude", gLongitude);
                intent.putExtra("SpeedBusExceed", speedTaxiExceed);
                startActivity(intent);
            }
        }
    });

    complainSend.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            String taxi_id = inputTaxi.getText().toString().toUpperCase();
            String taxi_comp = actv_comp_taxi.getText().toString();

            /*if(taxi_comp.length() == 0){
            Toast.makeText(TraqComplaintTaxi.this, "Taxi Company is required!", Toast.LENGTH_SHORT).show();
            }else */
            if (taxi_comp.length() < 2) {
                Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Company.", Toast.LENGTH_SHORT).show();
            } else if (taxi_id.length() == 0) {
                Toast.makeText(TraqComplaintTaxi.this, "Taxi Plate Number is required!", Toast.LENGTH_SHORT)
                        .show();
            } else if (taxi_id.length() < 7) {
                Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Number.", Toast.LENGTH_SHORT).show();
            } else {
                easyTracker.send(
                        MapBuilder.createEvent("Complaint", "Dialog Prompt", "Complaint event", null).build());
                PromptCustomDialog();
            }
        }
    });
    setCurrentDateOnView();
    getCurrentTime();

    //Shi Chuan's Code

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(TraqComplaintTaxi.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
        // Internet Connection is not present
        alert.showAlertDialog(TraqComplaintTaxi.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */

    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                // Shared Preferences
                SharedPreferences.Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);

                String username = user.getName();
                String description = user.getDescription();

                // Displaying in xml ui
                //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description));
            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }

    //LocationManager lm = (LocationManager)  this.getSystemService(Context.LOCATION_SERVICE);
    //LocationListener ll = new passengerLocationListener();
    //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

}

From source file:com.speed.traquer.app.TraqComplaintTaxi.java

private void checkTwitterID() {

    /* Get Access Token after login*/
    try {/*from  w  ww. j av a 2  s.  c om*/
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

        // Access Token
        String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
        // Access Token Secret
        String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

        AccessToken accessToken = new AccessToken(access_token, access_token_secret);
        Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

        // Getting user details from twitter
        // For now i am getting his name only
        twitterID = accessToken.getUserId();
        User user = twitter.showUser(twitterID);

        userName = user.getName();

        //Toast.makeText(TraqComplaintTaxi.this, Long.toString(twitterID) + userName, Toast.LENGTH_SHORT).show();
        // Displaying in xml ui
        //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description));

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    } catch (Exception e) {
        // Error in updating status
        Log.d("error!", e.getMessage());
    }
}