twitter4j.auth.AccessToken Java Examples

The following examples show how to use twitter4j.auth.AccessToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AccessTokenGenerator.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Interactive {@link AccessToken} generation.
 * 
 * @param args No args are required.
 * @throws Exception If the token cannot be generated.
 */
public static void main(final String... args) throws Exception
{
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken requestToken = twitter.getOAuthRequestToken();

    // Ask for the PIN
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    AccessToken accessToken = null;

    System.out.print("Open the following URL and grant access to your account: ");
    System.out.println(requestToken.getAuthorizationURL());
    System.out.print("Enter the PIN: ");

    accessToken = twitter.getOAuthAccessToken(requestToken, br.readLine());

    System.out.println("AccessToken Key: " + accessToken.getToken());
    System.out.println("AccessToken Secret: " + accessToken.getTokenSecret());

    twitter.shutdown();
}
 
Example #2
Source File: TwitterSession.java    From vocefiscal-android with Apache License 2.0 6 votes vote down vote up
/**
 * Stores the session data on disk.
 * 
 * @param context
 * @return
 */
public boolean save(Context context, AccessToken accessToken) 
{

    Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();

    this.token = accessToken.getToken();
    this.tokensecret = accessToken.getTokenSecret();
    editor.putString(TOKEN, token);
    editor.putString(TOKENSECRET, tokensecret);
    

    if (editor.commit()) 
    {
        singleton = this;
        return true;
    }
    return false;
}
 
Example #3
Source File: TwitterOAuthActivity.java    From firebase-login-demo-android with MIT License 6 votes vote down vote up
private void getTwitterOAuthTokenAndLogin(final RequestToken requestToken, final String oauthVerifier) {
    // once a user authorizes the application, get the auth token and return to the MainActivity
    new AsyncTask<Void, Void, AccessToken>() {
        @Override
        protected AccessToken doInBackground(Void... params) {
            AccessToken accessToken = null;
            try {
                accessToken = mTwitter.getOAuthAccessToken(requestToken, oauthVerifier);
            } catch (TwitterException te) {
                Log.e(TAG, te.toString());
            }
            return accessToken;
        }

        @Override
        protected void onPostExecute(AccessToken token) {
            Intent resultIntent = new Intent();
            resultIntent.putExtra("oauth_token", token.getToken());
            resultIntent.putExtra("oauth_token_secret", token.getTokenSecret());
            resultIntent.putExtra("user_id", token.getUserId() + "");
            setResult(MainActivity.RC_TWITTER_LOGIN, resultIntent);
            finish();
        }
    }.execute();
}
 
Example #4
Source File: MainController.java    From WTFDYUM with Apache License 2.0 6 votes vote down vote up
@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));
    }

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

    return new RedirectView("/user", true);
}
 
Example #5
Source File: Twitter4jSampleActivity.java    From android-opensource-library-56 with Apache License 2.0 6 votes vote down vote up
private void getOAuthAccessToken(final String pincode) {
    new Thread() {
        @Override
        public void run() {
            try {
                AccessToken token = mOauth.getOAuthAccessToken(pincode);
                Settings.getInstance(This()).setAccessToken(
                        token.getToken(), token.getTokenSecret());
                Settings.getInstance(This()).setInitialized(true);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startMain();
                    }
                });
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    }.start();
}
 
Example #6
Source File: TwitterActionService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static void start() {
    if (!Twitter.isEnabled) {
        return;
    }

    Twitter.client = createClient();

    AccessToken accessToken = getAccessToken();
    if (accessToken != null) {
        Twitter.client.setOAuthAccessToken(accessToken);
        logger.info("TwitterAction has been successfully authenticated > awaiting your Tweets!");
    } else {
        logger.info("Twitter authentication failed. Please use OSGi "
                + "console to restart the org.openhab.io.net-Bundle and re-initiate the authorization process!");
    }
}
 
Example #7
Source File: CollectionServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<User> getUserDataFromScreenName(String[] userNameList, String userName)	{		
	if (userNameList != null) {
		try {
			Twitter twitter = new TwitterFactory().getInstance();
			twitter.setOAuthConsumer(consumerKey, consumerSecret);
			AccessToken accessToken = new AccessToken(accessTokenStr, accessTokenSecretStr);
			twitter.setOAuthAccessToken(accessToken);

			ResponseList<User> list = twitter.lookupUsers(userNameList);
			logger.info("Successfully looked up in Twitter by screen name, size of list: " + list.size());
			return (list != null ? list : new ArrayList<User>());
		} catch (Exception e) {
			logger.error("Exception while getting user Data from screen Name for user: "+userName,e);
		}
	}
	return new ArrayList<User>();
}
 
Example #8
Source File: CollectionServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<User> getUserDataFromTwitterID(long[] userIdList, String userName)	{		
	if (userIdList != null) {
		try {
			Twitter twitter = new TwitterFactory().getInstance();
			twitter.setOAuthConsumer(consumerKey, consumerSecret);
			AccessToken accessToken = new AccessToken(accessTokenStr, accessTokenSecretStr);
			twitter.setOAuthAccessToken(accessToken);

			ResponseList<User> list = twitter.lookupUsers(userIdList);
			logger.info("Successfully looked up in Twitter by ID, size of list: " + list.size());
			return (list != null ? list : new ArrayList<User>());
		} catch (Exception e) {
			logger.error("Exception while getting user Data from TwitterId for user: "+userName,e);
		}
	}
	return new ArrayList<User>();
}
 
Example #9
Source File: TwitterServiceTest.java    From WTFDYUM with Apache License 2.0 6 votes vote down vote up
@Test
public void getFollowersTest() throws Exception {
    final Optional<Principal> principal = Optional.of(new Principal(123L, "toktok", "secsecret"));
    final IDs idsMock = mock(IDs.class);
    when(twitter.getFollowersIDs(444L, -1)).thenReturn(idsMock);

    final RateLimitStatus rateLimitStatusMock = mock(RateLimitStatus.class);
    when(idsMock.getRateLimitStatus()).thenReturn(rateLimitStatusMock);

    when(rateLimitStatusMock.getRemaining()).thenReturn(1);

    when(idsMock.getIDs()).thenReturn(new long[]{12L, 34L, 44L, 42L, 42L, 999L});

    final Set<Long> followers = sut.getFollowers(444L, principal);

    assertThat(followers).isNotNull();
    assertThat(followers.contains(12L));
    assertThat(followers.contains(34L));
    assertThat(followers.contains(44L));
    assertThat(followers.contains(42L));
    assertThat(followers.contains(999L));

    verify(twitter, times(1)).setOAuthAccessToken(new AccessToken("toktok", "secsecret"));
}
 
Example #10
Source File: PlayConfigurationView.java    From beatoraja with GNU General Public License v3.0 6 votes vote down vote up
@FXML
public void startPINAuth() {
	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setOAuthConsumerKey(player.getTwitterConsumerKey());
	cb.setOAuthConsumerSecret(player.getTwitterConsumerSecret());
	cb.setOAuthAccessToken(null);
	cb.setOAuthAccessTokenSecret(null);
	TwitterFactory twitterfactory = new TwitterFactory(cb.build());
	Twitter twitter = twitterfactory.getInstance();
	try {
		AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, txtTwitterPIN.getText());
		player.setTwitterAccessToken(accessToken.getToken());
		player.setTwitterAccessTokenSecret(accessToken.getTokenSecret());
		commit();
		update(config);
	} catch (TwitterException e) {
		e.printStackTrace();
	}
}
 
Example #11
Source File: OAuthActivity.java    From SmileEssence with MIT License 6 votes vote down vote up
@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();
            } else {
                setResult(RESULT_CANCELED);
                finish();
            }
        }
    }
}
 
Example #12
Source File: TweetLaunchpad.java    From The-NOC-List with Apache License 2.0 6 votes vote down vote up
public Twitter getTwitter() throws TwitterException, IOException 
{
   	ConfigurationBuilder cb = new ConfigurationBuilder();
   	
   	cb.setDebugEnabled(true)
   	  .setOAuthConsumerKey(CONSUMER_KEY)
   	  .setOAuthConsumerSecret(CONSUMER_KEY_SECRET);
   	
   	TwitterFactory tf = new TwitterFactory(cb.build());
   	Twitter twitter = tf.getInstance();
   	
   	twitter.setOAuthAccessToken(new AccessToken(ACCESS_TOKEN, 
   												ACCESS_TOKEN_SECRET));

   	return twitter;
}
 
Example #13
Source File: TweetSearcher.java    From The-NOC-List with Apache License 2.0 6 votes vote down vote up
public Twitter getTwitter() throws TwitterException, IOException 
{
   	ConfigurationBuilder cb = new ConfigurationBuilder();
   	
   	cb.setDebugEnabled(true)
   	  .setOAuthConsumerKey(CONSUMER_KEY)
   	  .setOAuthConsumerSecret(CONSUMER_SECRET)
   	  .setOAuthAccessToken(ACCESS_TOKEN)
   	  .setOAuthAccessTokenSecret(ACCESS_SECRET);
   	
   	TwitterFactory tf = new TwitterFactory(cb.build());
   	Twitter twitter = tf.getInstance();
   	
   	twitter.setOAuthAccessToken(new AccessToken(ACCESS_TOKEN, ACCESS_SECRET));

   	return twitter;
}
 
Example #14
Source File: TwitterUnit.java    From Tweetin with Apache License 2.0 6 votes vote down vote up
public static Twitter getTwitterFromSharedPreferences(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(
            context.getString(R.string.sp_tweetin),
            Context.MODE_PRIVATE
    );

    String consumerKey = context.getString(R.string.app_consumer_key);
    String consumerSecret = context.getString(R.string.app_consumer_secret);
    String accessToken = sharedPreferences.getString(
            context.getString(R.string.sp_access_token),
            null
    );
    String accessTokenSecret = sharedPreferences.getString(
            context.getString(R.string.sp_access_token_secret),
            null
    );

    Twitter twitter = (new TwitterFactory()).getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitter.setOAuthAccessToken(token);

    return twitter;
}
 
Example #15
Source File: TwitterUserValidator.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Optional<User> getUserFromAccessToken(String accessToken) throws UserValidationException {
  String token = accessToken.substring(0, accessToken.indexOf("_"));
  String tokenSecret = accessToken.substring(accessToken.indexOf("_") + 1, accessToken.length());

  if (users.get(token) != null) {
    return Optional.of(users.get(token));
  } else {
    twitter.setOAuthAccessToken(new AccessToken(token, tokenSecret));
    twitter4j.User userTwitter;

    try {
      userTwitter = twitter.showUser(Long.valueOf(twitter.getId()));
    } catch (TwitterException e) {
      return Optional.empty();
    }

    User user = User.create(userTwitter.getName(), userTwitter.getId() + "",
      userTwitter.getId() + "");

    users.put(token, user);
    return Optional.of(user);
  }
}
 
Example #16
Source File: TwitterPrefsPane.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Helper to get the user access token from the request token and supplied access code
 * @param accessCode
 * @return
 */
private AccessToken getOAuthAccessToken(String accessCode) {
	
	Map<String,String> config = externalIntegrationLogic.getTwitterOAuthConsumerDetails();

	Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
    
    try {
		return twitter.getOAuthAccessToken(requestToken, accessCode);
	} catch (TwitterException e) {
		log.error(e.getMessage(), e);
	}
	return null;
}
 
Example #17
Source File: AccessTokenTask.java    From SmileEssence with MIT License 5 votes vote down vote up
@Override
protected AccessToken doInBackground(Void... params) {
    try {
        return twitter.getOAuthAccessToken(requestToken, pinCode);
    } catch (TwitterException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #18
Source File: TwitterServiceTest.java    From WTFDYUM with Apache License 2.0 5 votes vote down vote up
@Test
public void getFollowersMultiplePageTest() throws Exception {
    final Optional<Principal> principal = Optional.of(new Principal(123L, "toktok", "secsecret"));
    final IDs firstPageMock = mock(IDs.class);
    final IDs secondPageMock = mock(IDs.class);

    final RateLimitStatus firstPageRateLimitMock = mock(RateLimitStatus.class);
    when(firstPageRateLimitMock.getRemaining()).thenReturn(1);
    when(firstPageMock.getRateLimitStatus()).thenReturn(firstPageRateLimitMock);
    when(firstPageMock.hasNext()).thenReturn(true);
    when(firstPageMock.getIDs()).thenReturn(new long[]{12L, 34L, 44L, 42L, 42L, 999L});
    when(firstPageMock.getNextCursor()).thenReturn(42L);

    final RateLimitStatus secondPageRateLimitMock = mock(RateLimitStatus.class);
    when(secondPageRateLimitMock.getRemaining()).thenReturn(0);
    when(secondPageMock.getRateLimitStatus()).thenReturn(secondPageRateLimitMock);
    when(secondPageMock.hasNext()).thenReturn(false);
    when(secondPageMock.getIDs()).thenReturn(new long[]{1001L, 1002L, 1003L});

    when(twitter.getFollowersIDs(444L, -1)).thenReturn(firstPageMock);
    when(twitter.getFollowersIDs(444L, 42)).thenReturn(secondPageMock);

    final Set<Long> followers = sut.getFollowers(444L, principal);

    assertThat(followers).isNotNull();
    assertThat(followers).containsOnly(12L, 34L, 44L, 42L, 999L, 1001L, 1002L, 1003L);

    verify(twitter, times(1)).setOAuthAccessToken(new AccessToken("toktok", "secsecret"));
}
 
Example #19
Source File: ProfileExternalIntegrationLogicImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public String getTwitterName(ExternalIntegrationInfo info) {
	
	if(info == null){
		return null;
	}
	
	//get values
	String token = info.getTwitterToken();
	String secret = info.getTwitterSecret();
	
	if(StringUtils.isNotBlank(token) && StringUtils.isNotBlank(secret)) {

		//global config
		Map<String,String> config = getTwitterOAuthConsumerDetails();

		//token for user
		AccessToken accessToken = new AccessToken(token, secret);
		
		//setup
		TwitterFactory factory = new TwitterFactory();
		Twitter twitter = factory.getInstance();
		twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
		twitter.setOAuthAccessToken(accessToken);
		
		//check
		try {
			return twitter.verifyCredentials().getScreenName();
		} catch (TwitterException e) {
			log.error("Error retrieving Twitter credentials: " + e.getClass() + ": " + e.getMessage());
		}
	}
	return null;
}
 
Example #20
Source File: Twitt4droid.java    From twitt4droid with Apache License 2.0 5 votes vote down vote up
/**
 * Saves authentication information from the given AccessToken in {@code SharedPreferences}.
 * 
 * @param context the application context.
 * @param token an AccessToken.
 */
public static void saveAuthenticationInfo(Context context, AccessToken token) {
    Resources.getPreferences(context)
        .edit()
        .putString(context.getString(R.string.twitt4droid_oauth_token_key), token.getToken())
        .putString(context.getString(R.string.twitt4droid_oauth_secret_key), token.getTokenSecret())
        .putBoolean(context.getString(R.string.twitt4droid_user_is_logged_in_key), true)
        .commit();
}
 
Example #21
Source File: TwitterOauthWizard.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
protected Result<AccessToken> doInBackground (final Void... params) {
	try {
		final RequestToken token = this.host.unstashRequestToken();
		return new Result<AccessToken>(this.host.getTwitter(this.requestCode).getOAuthAccessToken(token, this.oauthVerifier));
	}
	catch (final Exception e) { // NOSONAR report all errors to user.
		return new Result<AccessToken>(e);
	}
}
 
Example #22
Source File: TwitterOauthWizard.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute (final Result<AccessToken> result) {
	this.dialog.dismiss();
	if (result.isSuccess()) {
		this.host.onGotTwitterAccessToken(result.getData(), this.completeCallback);
	}
	else {
		getLog().e("Failed to complete OAuth.", result.getE());
		DialogHelper.alert(this.host.getContext(), result.getE());
	}
}
 
Example #23
Source File: TwitterOauthWizard.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
protected void onGotTwitterAccessToken (final AccessToken accessToken, final TwitterOauthComplete completeCallback) {
	try {
		LOG.i("Account authorised %s.", accessToken.getScreenName());
		final Account account = new Account(completeCallback.getAccountId(), accessToken.getScreenName(), AccountProvider.TWITTER,
				getTwitterConfiguration().getOAuthConsumerKey(), getTwitterConfiguration().getOAuthConsumerSecret(),
				accessToken.getToken(), accessToken.getTokenSecret());
		completeCallback.onAccount(account, accessToken.getScreenName());
	}
	catch (final Exception e) { // NOSONAR want to show any errors to the user.
		LOG.e("Failed to write new Twitter account.", e);
		DialogHelper.alert(getContext(), e);
	}
}
 
Example #24
Source File: TwitterLogin.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Path("/callback")
@GET
public Response callback(@QueryParam("oauth_token") String token, @QueryParam("oauth_verifier") String verifier) {

  AccessToken accessToken;
  try {
    accessToken = twitter.getOAuthAccessToken(tokenSecrets.get(token), verifier);

    return Response.ok(accessToken.getToken() + "_" + accessToken.getTokenSecret()).build();
  } catch (Exception e) {
    return Response.status(400).entity("Access Token not found").build();
  }

}
 
Example #25
Source File: OAuthSession.java    From SmileEssence with MIT License 5 votes vote down vote up
public AccessToken getAccessToken(String pinCode) {
    Twitter twitter = new TwitterFactory(TwitterApi.getConf(consumer.key, consumer.secret)).getInstance();
    AccessTokenTask task = new AccessTokenTask(twitter, requestToken, pinCode);
    task.execute();
    try {
        return task.get();
    } catch (Exception e) {
        e.printStackTrace();
        Logger.error(e.toString());
        return null;
    }
}
 
Example #26
Source File: CallbackServlet.java    From TwitterBoost-Tools with MIT License 5 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get twitter object from session
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
//Get twitter request token object from session
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
String verifier = request.getParameter("oauth_verifier");
try {
	// Get twitter access token object by verifying request token 
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
    request.getSession().removeAttribute("requestToken");
    
    // Get user object from database with twitter user id
    UserPojo user = TwitterDAO.selectTwitterUser(accessToken.getUserId());
    if(user == null) {
       // if user is null, create new user with given twitter details 
       user = new UserPojo();
       user.setTwitter_user_id(accessToken.getUserId());
       user.setTwitter_screen_name(accessToken.getScreenName());
       user.setAccess_token(accessToken.getToken());
       user.setAccess_token_secret(accessToken.getTokenSecret());
       TwitterDAO.insertRow(user);
       user = TwitterDAO.selectTwitterUser(accessToken.getUserId());
    } else {
       // if user already there in database, update access token
       user.setAccess_token(accessToken.getToken());
       user.setAccess_token_secret(accessToken.getTokenSecret());
       TwitterDAO.updateAccessToken(user);
    }
    request.setAttribute("user", user);
} catch (TwitterException | DBException e) {
    throw new ServletException(e);
} 
request.getRequestDispatcher("/index2.html").forward(request, response);
  }
 
Example #27
Source File: TweetManager.java    From bridgefy-android-samples with MIT License 5 votes vote down vote up
TweetManager(String username, TweetListener tweetListener) {
    this.username = username;
    this.tweetListener = tweetListener;

    // configure the Twitter client
    String token  = "YOUR TOKEN HERE";
    String secret = "YOUR SECRET HERE";
    String consumerKey = "CONSUMER KEY";
    String consumerSecret = "CONSUMER SECRET";

    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(token,secret));
}
 
Example #28
Source File: Twitter.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private void saveAccessToken(AccessToken accessToken) {
  final SharedPreferences.Editor sharedPrefsEditor = sharedPreferences.edit();
  if (accessToken == null) {
    sharedPrefsEditor.remove(ACCESS_TOKEN_TAG);
    sharedPrefsEditor.remove(ACCESS_SECRET_TAG);
  } else {
    sharedPrefsEditor.putString(ACCESS_TOKEN_TAG, accessToken.getToken());
    sharedPrefsEditor.putString(ACCESS_SECRET_TAG,
        accessToken.getTokenSecret());
  }
  sharedPrefsEditor.commit();
}
 
Example #29
Source File: MainControllerTest.java    From WTFDYUM with Apache License 2.0 5 votes vote down vote up
@Test
public void signinCallbackTest() throws Exception {
    final RequestToken returnedRequestToken = new RequestToken("my_super_token", "");

    when(twitterService.signin(anyString())).thenReturn(returnedRequestToken);
    when(principalService.get(1203L)).thenReturn(null);

    final HttpSession session = mockMvc
            .perform(get("/signin"))
            .andExpect(status().is3xxRedirection())
            .andExpect(redirectedUrlPattern("http*://**/**my_super_token"))
            .andReturn()
            .getRequest()
            .getSession();

    assertThat(session).isNotNull();
    assertThat(session.getAttribute(MainController.SESSION_REQUEST_TOKEN)).isNotNull();
    assertThat(session.getAttribute(MainController.SESSION_REQUEST_TOKEN)).isEqualTo(returnedRequestToken);

    final AccessToken returnedAccessToken = new AccessToken("TOken", "secret");
    ReflectionTestUtils.setField(returnedAccessToken, "userId", 1203L);

    when(twitterService.completeSignin(returnedRequestToken, "42")).thenReturn(returnedAccessToken);

    mockMvc
    .perform(get("/signin/callback?oauth_verifier=42").session((MockHttpSession) session))
    .andExpect(status().is3xxRedirection())
    .andExpect(redirectedUrl("/user"));

    final Principal builtUser = new Principal(1203L, "TOken", "secret");

    verify(userService, times(1)).addEvent(1203L, new Event(EventType.REGISTRATION, null));
    verify(principalService, times(1)).saveUpdate(builtUser);
    verify(authenticationService, times(1)).authenticate(builtUser);
}
 
Example #30
Source File: Twitter.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private AccessToken retrieveAccessToken() {
  String token = sharedPreferences.getString(ACCESS_TOKEN_TAG, "");
  String secret = sharedPreferences.getString(ACCESS_SECRET_TAG, "");
  if (token.length() == 0 || secret.length() == 0) {
    return null;
  }
  return new AccessToken(token, secret);
}