Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory() 

Source Link

Document

Creates a TwitterFactory with the root configuration.

Usage

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 av  a2  s . co  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 {//  w  ww. j  a  v a 2 s . 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 {/*from   w w w .  ja  va  2  s.c o 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 {/*from  w w  w.j a v a2  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);//ww  w .  j av  a 2s.c  o m
            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.hfoss.posit.android.functionplugin.twitter.TwitFindsActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "onCreate");
    super.onCreate(savedInstanceState);

    // Ensure user is logged in.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    PREF_ACCESS_TOKEN = prefs.getString("prefaccesstoken", "");
    PREF_ACCESS_TOKEN_SECRET = prefs.getString("prefaccesstokensecret", "");
    if (PREF_ACCESS_TOKEN == "" || PREF_ACCESS_TOKEN_SECRET == "") {
        //TODO: Allow user to login here as well. Challenge, redirecting back to the find. 
        Toast.makeText(this, "Please Login to Twitter in the Preferences", Toast.LENGTH_LONG).show();
        finish();//from ww  w .ja va2s  .co m
    } else {
        // Load the twitter4j helper
        mTwitter = new TwitterFactory().getInstance();

        // Tell twitter4j that we want to use it with our app
        mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

        // Retrieve find string.
        // Retrieve DbEntries of Find from intent
        ContentValues cv = getIntent().getParcelableExtra("DbEntries");
        mEntries = new ArrayList<Entry<String, Object>>(cv.valueSet());

        // Access point for find plug-ins to insert their own tweet find string.
        // Find plug-in would need to store the tweet find string as a field instead of generating it dynamically.
        for (Entry<String, Object> entry : mEntries) {
            if (entry.getKey().matches("tweetFindString")) {
                tweetString = entry.getValue().toString();
            }
        }
        // If the find object does not have an custom find string, create one. 
        if (tweetString == null || tweetString == "") {
            StringBuilder builder = new StringBuilder();
            for (Entry<String, Object> entry : mEntries) {
                builder.append(entry.getKey());
                builder.append("= ");
                builder.append(entry.getValue().toString());
                builder.append(" ");
            }
            tweetString = builder.toString();
        }

        AccessToken at = new AccessToken(PREF_ACCESS_TOKEN, PREF_ACCESS_TOKEN_SECRET);
        mTwitter.setOAuthAccessToken(at);
        tweetMessage();
        finish();
    }
}

From source file:org.hornetq.integration.twitter.impl.IncomingTweetsHandler.java

License:Apache License

public void start() throws Exception {
    Binding b = postOffice.getBinding(new SimpleString(queueName));
    if (b == null) {
        throw new Exception(connectorName + ": queue " + queueName + " not found");
    }//  w  w  w .  j  a va  2 s.  co  m

    paging = new Paging();
    TwitterFactory tf = new TwitterFactory();
    this.twitter = tf.getOAuthAuthorizedInstance(this.consumerKey, this.consumerSecret,
            new AccessToken(this.accessToken, this.accessTokenSecret));
    this.twitter.verifyCredentials();

    // getting latest ID
    this.paging.setCount(TwitterConstants.FIRST_ATTEMPT_PAGE_SIZE);

    // If I used annotations here, it won't compile under JDK 1.7
    ResponseList res = this.twitter.getHomeTimeline(paging);
    this.paging.setSinceId(((Status) res.get(0)).getId());
    HornetQTwitterLogger.LOGGER
            .debug(connectorName + " initialise(): got latest ID: " + this.paging.getSinceId());

    // TODO make page size configurable
    this.paging.setCount(TwitterConstants.DEFAULT_PAGE_SIZE);

    scheduledFuture = this.scheduledPool.scheduleWithFixedDelay(new TweetsRunnable(), intervalSeconds,
            intervalSeconds, TimeUnit.SECONDS);
    isStarted = true;
}

From source file:org.hornetq.integration.twitter.impl.OutgoingTweetsHandler.java

License:Apache License

/**
 * TODO streaming API support//  w w w  .  j a v a2s.  co m
 * TODO rate limit support
 */
public synchronized void start() throws Exception {
    if (this.isStarted) {
        return;
    }

    if (this.connectorName == null || this.connectorName.trim().equals("")) {
        throw new Exception("invalid connector name: " + this.connectorName);
    }

    if (this.queueName == null || this.queueName.trim().equals("")) {
        throw new Exception("invalid queue name: " + queueName);
    }

    SimpleString name = new SimpleString(this.queueName);
    Binding b = this.postOffice.getBinding(name);
    if (b == null) {
        throw new Exception(connectorName + ": queue " + queueName + " not found");
    }
    this.queue = (Queue) b.getBindable();

    TwitterFactory tf = new TwitterFactory();
    this.twitter = tf.getOAuthAuthorizedInstance(this.consumerKey, this.consumerSecret,
            new AccessToken(this.accessToken, this.accessTokenSecret));
    this.twitter.verifyCredentials();

    // TODO make filter-string configurable
    // this.filter = FilterImpl.createFilter(filterString);
    this.filter = null;

    this.queue.addConsumer(this);

    this.queue.deliverAsync();
    this.isStarted = true;
    HornetQTwitterLogger.LOGGER.debug(connectorName + ": started");
}

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

License:Apache License

private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//from  w w  w . j a v a  2  s . co  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.junjun.twitter.GetUserTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]//from ww w.  ja v  a 2 s  .c  om
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        List<Status> statuses;
        String user;
        Paging paging = new Paging(1);
        paging.setCount(100);
        if (args.length == 1) {
            user = args[0];
            /* statuses = twitter.getUserTimeline(Long.parseLong(user),paging);*/
            statuses = twitter.getUserTimeline(Long.parseLong(user));
        } else {
            user = twitter.verifyCredentials().getScreenName();
            statuses = twitter.getUserTimeline();
        }
        System.out.println("Showing @" + user + "'s user timeline.");
        int i = 0;

        for (Status status : statuses) {
            System.out.println(i++ + "@" + status.getUser().getName() + " - " + status + "  ");
        }

        System.out.println();
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}