Example usage for twitter4j Twitter setOAuthConsumer

List of usage examples for twitter4j Twitter setOAuthConsumer

Introduction

In this page you can find the example usage for twitter4j Twitter setOAuthConsumer.

Prototype

void setOAuthConsumer(String consumerKey, String consumerSecret);

Source Link

Document

sets the OAuth consumer key and consumer secret

Usage

From source file:org.exoplatform.extensions.twitter.services.TwitterService.java

License:Open Source License

/**
 * /* ww  w .  ja va2s.c  o m*/
 * @param userId
 * @return 
 */
public Twitter getTwitter(String userId) {
    Twitter twitter = null;
    UserSocialNetworkPreferences prefs = this.getUserPreferences(userId);
    if (prefs != null) {
        String token = prefs.getToken();
        String tokenSecret = prefs.getTokenSecret();
        if (token != null && tokenSecret != null) {
            AccessToken accessToken = new AccessToken(token, tokenSecret);
            twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(consumerKey, secretKey);
            twitter.setOAuthAccessToken(accessToken);
        }
    }
    return twitter;
}

From source file:org.exoplatform.extensions.twitter.services.TwitterService.java

License:Open Source License

public RequestToken getAuthorizationUrl() {

    RequestToken requestToken = null;//from  w w w .j a  va2s .  c o  m
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, secretKey);
        requestToken = twitter.getOAuthRequestToken();

    } catch (TwitterException ex) {
        Logger.getLogger(TwitterService.class.getName()).log(Level.SEVERE, null, ex);
    }

    return requestToken;
}

From source file:org.exoplatform.extensions.twitter.services.TwitterService.java

License:Open Source License

public boolean validateTwitterAuthorization(String requestToken, String pin) {
    try {/*from ww w.  j  a  va 2s .c  o m*/
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, secretKey);
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterService.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}

From source file:org.fenixedu.bennu.social.domain.api.TwitterAPI.java

License:Open Source License

@Override
public String getAuthenticationUrlForUser(User user) {

    try {//w  ww .  j a v a 2  s  .  co m
        TwitterFactory tf = new TwitterFactory();
        Twitter twitter = tf.getInstance();
        twitter.setOAuthConsumer(getClientId(), getClientSecret());

        RequestToken oauthRequestToken = twitter.getOAuthRequestToken(getCallbackURL());

        String oauthToken = oauthRequestToken.getToken();
        String oauthTokenSecret = oauthRequestToken.getTokenSecret();
        String authorizationURL = oauthRequestToken.getAuthorizationURL();

        LOGGER.info("Received OauthToken. Token: " + oauthToken + ", TokenSecret: " + oauthTokenSecret
                + ", AuthenticationURL: " + authorizationURL);

        TwitterUser twitterUser = new TwitterService().getAuthenticatedUser(user);
        twitterUser.setOauthToken(oauthToken);
        twitterUser.setOauthTokenSecret(oauthTokenSecret);

        return authorizationURL;

    } catch (TwitterException e) {
        LOGGER.error("Received TwitterException:" + e.getErrorMessage());
        e.printStackTrace();
        return "";
    }
}

From source file:org.fenixedu.bennu.social.ui.controller.SocialCallbackController.java

License:Open Source License

@RequestMapping(value = "/twitter/callback", method = RequestMethod.GET)
public String twitter(Model model, RedirectAttributes redirectAttrs,
        @RequestParam(value = "oauth_token", required = false) String oauthToken,
        @RequestParam(value = "oauth_verifier", required = false) String oauthVerifier,
        @RequestParam(value = "denied", required = false) String denied) {

    LOGGER.info("received invocation at twitter callback endpoint w/ params: oauth_token=" + oauthToken
            + ", oauth_verifier=" + oauthVerifier + ", denied=" + denied);

    TwitterAPI twitterAPI = twitterService.getInstance();

    if (!twitterAPI.isConfigured()) {
        LOGGER.error("Received invocation at Twitter callback endpoint, but service not yet configured");
        redirectAttrs.addFlashAttribute("errors", Arrays.asList("api.not.configured.twitter"));
    } else {/*w w  w. j a  va2  s .  c  o  m*/

        if (denied != null) {
            String errorMessage = "Received error from Twitter server: " + denied;
            LOGGER.info(errorMessage);
            redirectAttrs.addFlashAttribute("errorMessage", errorMessage);
        } else {
            try {
                User user = Authenticate.getUser();
                TwitterUser twitterUser = twitterService.getAuthenticatedUser(user);

                Twitter instance = new TwitterFactory().getInstance();
                instance.setOAuthConsumer(twitterAPI.getClientId(), twitterAPI.getClientSecret());
                RequestToken requestToken = new RequestToken(twitterUser.getOauthToken(),
                        twitterUser.getOauthTokenSecret());
                AccessToken oAuthAccessToken = instance.getOAuthAccessToken(requestToken, oauthVerifier);

                twitterService.parseResponse(twitterUser, oAuthAccessToken);
            } catch (TwitterException | AccessTokenNotProvidedException e) {
                e.printStackTrace();
                redirectAttrs.addFlashAttribute("errors", Arrays.asList(e.getClass().getSimpleName()));
            }
        }
    }

    return "redirect:/bennu-social-admin";
}

From source file:org.getlantern.firetweet.fragment.support.AccountsDashboardFragment.java

License:Open Source License

@Override
public void onListItemClick(final ListView l, final View v, final int position, final long id) {
    final ListAdapter adapter = mAdapter.getAdapter(position);
    final Object item = mAdapter.getItem(position);
    if (adapter instanceof AccountOptionsAdapter) {
        final ParcelableAccount account = mAccountsAdapter.getSelectedAccount();
        if (account == null || !(item instanceof OptionItem))
            return;
        final OptionItem option = (OptionItem) item;
        switch (option.id) {
        case MENU_SEARCH: {
            final Intent intent = new Intent(getActivity(), QuickSearchBarActivity.class);
            intent.putExtra(EXTRA_ACCOUNT_ID, account.account_id);
            startActivity(intent);//from w w w  .  j  a  v  a2s .  c om
            closeAccountsDrawer();
            break;
        }
        case MENU_COMPOSE: {
            final Intent composeIntent = new Intent(INTENT_ACTION_COMPOSE);
            composeIntent.setClass(getActivity(), ComposeActivity.class);
            composeIntent.putExtra(EXTRA_ACCOUNT_IDS, new long[] { account.account_id });
            startActivity(composeIntent);
            break;
        }
        case MENU_FAVORITES: {
            openUserFavorites(getActivity(), account.account_id, account.account_id, account.screen_name);
            break;
        }
        case MENU_LISTS: {
            openUserLists(getActivity(), account.account_id, account.account_id, account.screen_name);
            break;
        }
        case MENU_EDIT: {
            final Bundle bundle = new Bundle();
            bundle.putLong(EXTRA_ACCOUNT_ID, account.account_id);
            final Intent intent = new Intent(INTENT_ACTION_EDIT_USER_PROFILE);
            intent.setClass(getActivity(), UserProfileEditorActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
            break;
        }
        }
    } else if (adapter instanceof AppMenuAdapter) {
        if (!(item instanceof OptionItem))
            return;
        final OptionItem option = (OptionItem) item;
        switch (option.id) {
        case MENU_ACCOUNTS: {
            final Intent intent = new Intent(getActivity(), AccountsManagerActivity.class);
            startActivity(intent);
            break;
        }
        case MENU_DRAFTS: {
            final Intent intent = new Intent(INTENT_ACTION_DRAFTS);
            intent.setClass(getActivity(), DraftsActivity.class);
            startActivity(intent);
            break;
        }
        case MENU_SIGNOUT: {
            // destroy Twitter instance and delete oauth access token
            final Twitter mTwitter = new TwitterFactory().getInstance();
            mTwitter.setOAuthConsumer(Accounts.CONSUMER_KEY, Accounts.CONSUMER_SECRET);
            mTwitter.setOAuthAccessToken(null);
            mTwitter.shutdown();

            // remove existing account
            mAccountsAdapter.setAccounts(null);
            Utils.removeAccounts(getActivity().getApplicationContext());

            // close existing activity
            closeActivity();

            // display sign in activity
            final Intent signInIntent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
            signInIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(signInIntent);
            break;
        }
        case MENU_SETTINGS: {
            final Intent intent = new Intent(getActivity(), SettingsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, REQUEST_SETTINGS);
            break;
        }
        }
        closeAccountsDrawer();
    }
}

From source file:org.jetbrains.webdemo.servlet.TwitterServlet.java

License:Apache License

private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from  ww w .  j a v a  2  s  .c o m*/
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(apiKey, apiSecret);
        request.getSession().setAttribute("twitter", twitter);
        String callbackURL = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + "/twitter/tweet";
        request.getSession().setAttribute("tweetText", request.getParameter("tweet-text"));
        request.getSession().setAttribute("kotlin-level", request.getParameter("kotlin-level"));
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void requestAccessToken(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();// w  ww.  j a  v a2s . c  om

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg;
    String lCallbackURL = aToken.getString("callbackURL");
    try {
        if (!mCheckAuth(lResponse)) {
            mLog.error(lResponse.getString("msg"));
        } else {
            // get a new Twitter object for the user
            TwitterFactory lTwitterFactory = new TwitterFactory();
            Twitter lTwitter = lTwitterFactory.getInstance();
            lTwitter.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret());

            // pass callback URL to Twitter API if given
            RequestToken lReqToken = (lCallbackURL != null ? lTwitter.getOAuthRequestToken(lCallbackURL)
                    : lTwitter.getOAuthRequestToken());

            String lAuthenticationURL = lReqToken.getAuthenticationURL();
            String lAuthorizationURL = lReqToken.getAuthorizationURL();

            lResponse.setString("authenticationURL", lAuthenticationURL);
            lResponse.setString("authorizationURL", lAuthorizationURL);
            lMsg = "authenticationURL: " + lAuthenticationURL + ", authorizationURL: " + lAuthorizationURL;
            lResponse.setString("msg", lMsg);
            if (mLog.isInfoEnabled()) {
                mLog.info(lMsg);
            }

            aConnector.setVar(OAUTH_REQUEST_TOKEN, lReqToken);
            aConnector.setVar(TWITTER_VAR, lTwitter);
        }
    } catch (Exception lEx) {
        lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.keycloak.social.twitter.TwitterIdentityProvider.java

License:Open Source License

@Override
public Response performLogin(AuthenticationRequest request) {
    try {//from w ww. j a  va2s.com
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(getConfig().getClientId(), getConfig().getClientSecret());

        URI uri = new URI(request.getRedirectUri() + "?state=" + request.getState());

        RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString());
        ClientSessionModel clientSession = request.getClientSession();

        clientSession.setNote("twitter_token", requestToken.getToken());
        clientSession.setNote("twitter_tokenSecret", requestToken.getTokenSecret());

        URI authenticationUrl = URI.create(requestToken.getAuthenticationURL());

        return Response.temporaryRedirect(authenticationUrl).build();
    } catch (Exception e) {
        throw new IdentityBrokerException("Could send authentication request to twitter.", e);
    }
}

From source file:org.keycloak.social.twitter.TwitterProvider.java

License:Open Source License

@Override
public AuthRequest getAuthUrl(SocialProviderConfig config, String state) throws SocialProviderException {
    try {/*from w  w  w. j  a v  a2 s. c o m*/
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(config.getKey(), config.getSecret());

        URI uri = new URI(config.getCallbackUrl() + "?state=" + state);

        RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString());
        return AuthRequest.create(requestToken.getAuthenticationURL())
                .setAttribute("token", requestToken.getToken())
                .setAttribute("tokenSecret", requestToken.getTokenSecret()).build();
    } catch (Exception e) {
        throw new SocialProviderException(e);
    }
}