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(String configTreePath) 

Source Link

Document

Creates a TwitterFactory with a specified config tree

Usage

From source file:com.learnncode.demotwitterimagepost.HelperMethods.java

License:Apache License

public static void postToTwitterWithInputStream(Context context, final Activity callingActivity,
        final InputStream inputStream, final String message, final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);/*from  w w w.j  a  va2  s .  c  o m*/
        return;
    }

    final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken(context));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    final Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {

        private double x;

        @Override
        public void run() {
            boolean success = true;
            try {
                x = Math.random();
                if (inputStream != null) {
                    final StatusUpdate status = new StatusUpdate(message);
                    status.setMedia("GIF image", inputStream);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (final Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.learnncode.demotwitterimagepost.LoginActivity.java

License:Apache License

private void askOAuth() {
    final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(twitterConsumerKey);
    configurationBuilder.setOAuthConsumerSecret(twitterConsumerSecret);
    final Configuration configuration = configurationBuilder.build();
    twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {
        @Override/* ww w .j  ava2 s .co m*/
        public void run() {
            try {
                requestToken = twitter.getOAuthRequestToken(AppConstantTwitter.TWITTER_CALLBACK_URL);
            } catch (final Exception e) {
                final String errorString = e.toString();
                LoginActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (busyDialog != null) {
                            busyDialog.dismis();
                        }
                        Toast.makeText(LoginActivity.this, errorString.toString(), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
                return;
            }

            LoginActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    twitterLoginWebView.loadUrl(requestToken.getAuthenticationURL());
                }
            });
        }
    }).start();
}

From source file:com.learnncode.twitter.Utilities.TwitterHelper.java

License:Apache License

public static Twitter getTwitterInstance(Context _Context) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(_Context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder//from   w  ww.  ja  v a2s  . c o m
            .setOAuthConsumerSecret(_Context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(AppSettings.getTwitterAccessToken((_Context)));
    configurationBuilder.setOAuthAccessTokenSecret(AppSettings.getTwitterAccessTokenSecret(_Context));
    Configuration configuration = configurationBuilder.build();
    return new TwitterFactory(configuration).getInstance();
}

From source file:com.learnncode.twitter.Utilities.TwitterHelper.java

License:Apache License

public static Twitter getTwitterInstanceWithoutAuthentication(Context _Context) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(_Context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder//from  w ww.  j a v a  2 s .  co m
            .setOAuthConsumerSecret(_Context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(_Context.getResources().getString(R.string.twitter_access_token));
    configurationBuilder
            .setOAuthAccessTokenSecret(_Context.getResources().getString(R.string.twitter_access_token_secret));
    Configuration configuration = configurationBuilder.build();
    return new TwitterFactory(configuration).getInstance();
}

From source file:com.left8.evs.utilities.dsretriever.TweetsRetriever.java

License:Open Source License

/**
 * Method to retrieve and store historical tweets by collecting them with 
 * their ID.//  w  w  w  .ja  v a2s . c  o  m
 * @param tweetIDs The IDs of the tweets that are going to be collected.
 * @param mongoDB A MongoHandler object.
 * @param config A configuration object.
 * @param event The ground truth event for which the tweets that are going 
 * to be collected, are referring to.
 */
public final void retrieveTweetsById(List<String> tweetIDs, MongoHandler mongoDB, Config config, String event) {

    ConfigurationBuilder cb = getAuthorization();
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();

    tweetIDs.stream().forEach((item) -> {
        try {
            //Get tweet and all its metadata and store it
            Status status = twitter.showStatus(Long.parseLong(item));
            mongoDB.insertSingleTweetIntoMongoDB(status, event);
        } catch (TwitterException e) {
            Utilities.printMessageln("Failed to retrieve tweet with ID: " + item);
            Logger.getLogger(TweetsRetriever.class.getName()).log(Level.SEVERE, null, e);
        }
    });
}

From source file:com.marpies.ane.twitter.data.TwitterAPI.java

License:Apache License

public static Twitter getInstance() {
    if (mTwitterFactory == null) {
        mTwitterFactory = new TwitterFactory(mConfiguration);
    }/*w ww  .  ja  v  a  2  s .c  o  m*/
    return mTwitterFactory.getInstance();
}

From source file:com.marpies.ane.twitter.data.TwitterAPI.java

License:Apache License

public static Twitter getInstance(AccessToken token) {
    if (mTwitterFactory == null) {
        mTwitterFactory = new TwitterFactory(mConfiguration);
    }/*from  w  w w . j  a  v  a2s .c o m*/
    return mTwitterFactory.getInstance(token);
}

From source file:com.michaelfitzmaurice.clocktwerk.apps.RandomReplyBot.java

License:Apache License

/**
 * @param args/*from  www  . j a  v a 2s . c  o m*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    if (args.length < 3) {
        String msg = "Error - you must supply full path to Persistence Directory, "
                + "full path to replies file, and full path to Twitter OAuth "
                + "file. Cannot do anything without these values - exiting.";
        System.err.println(msg);
        LOG.error(msg);
        System.exit(1);
    }

    LOG.info("Setting up Prevayler for persistence...");
    String persistenceDirectory = args[0];
    Prevayler prevayler = PrevaylerFactory.createPrevayler(new HashMap<String, Long>(), persistenceDirectory);
    LOG.info("Prevayler created");

    LOG.info("Reading reply set in from file...");
    File repliesFile = new File(args[1]);
    TweetDatabase tweetDatabase = new TweetDatabase(repliesFile, new RandomTweetIndex());
    LOG.info("Created randomised reply set");

    LOG.info("Setting up Twitter client...");
    Properties oAuthProps = new Properties();
    oAuthProps.load(new FileInputStream(new File(args[2])));
    Configuration twitterAuthConf = new ConfigurationBuilder()
            .setOAuthConsumerKey(oAuthProps.getProperty("oauth.consumerKey"))
            .setOAuthConsumerSecret(oAuthProps.getProperty("oauth.consumerSecret"))
            .setOAuthAccessToken(oAuthProps.getProperty("oauth.accessToken"))
            .setOAuthAccessTokenSecret(oAuthProps.getProperty("oauth.accessTokenSecret")).build();
    Twitter twitterClient = new TwitterFactory(twitterAuthConf).getInstance();
    if (twitterClient.getAuthorization().isEnabled() == false) {
        String msg = "Fatal - not authenticated to Twitter. "
                + "Check values in Twitter OAuth file before restarting.";
        LOG.error(msg);
        throw new IOException(msg);
    }
    LOG.info("Twitter client connected and authenticated");

    TweetResponder responder = new TweetResponder(prevayler, tweetDatabase, twitterClient);
    Collection<Status> mentionsToRespondTo = responder.getNewMentions();
    responder.respondToMentions(mentionsToRespondTo);
}

From source file:com.michaelstark.twitteroauth.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * Begins the OAuth authentication mechanism.
 *
 * @param request servlet request//  www  . j  av a  2  s. c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ConfigurationBuilder builder = new ConfigurationBuilder();

    builder.setOAuthConsumerKey("<consumer key goes here>")
            .setOAuthConsumerSecret("<consumer secret goes here>");

    Twitter twitter = new TwitterFactory(builder.build()).getInstance();

    HttpSession session = request.getSession(true);

    // Get the callback URL.
    String callbackUrl = String.format("http://%s:%d%s/oauth_callback", request.getServerName(),
            request.getServerPort(), request.getContextPath());

    try {
        // Get the request token.
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);

        // Store the request token for later use.
        session.setAttribute("requestToken", requestToken);

        // Save the Twitter client for later.
        session.setAttribute("twitterClient", twitter);

        // Redirect to Twitter authentication page.
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        logger.log(Level.SEVERE, "Could not login via Twitter: ", e);

        // Failure. Go back to home. Maybe add an error message.
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

License:Apache License

@Override
public void open(@NonNull final Callback callback) {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey)
            .setOAuthConsumerSecret(mConsumerSecret).build();

    final Twitter instance = new TwitterFactory(configuration).getInstance();
    if (mAccessToken != null) {
        instance.setOAuthAccessToken(mAccessToken);
    }// w w w .  jav a2 s.c  om

    doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() {
        @Override
        public Task<AccessToken> then(Task<User> task) throws Exception {
            if (task.isFaulted()) {
                SharedPreferences preferences = getActivity().getSharedPreferences("twitter",
                        Activity.MODE_PRIVATE);
                preferences.edit().clear().apply();

                mAccessToken = null;
                instance.setOAuthAccessToken(null);
                return doGetAuthenticationURL(instance)
                        .onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() {
                            @Override
                            public Task<Bundle> then(Task<RequestToken> task) throws Exception {
                                return doDialogAuthentication(task.getResult());
                            }
                        }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() {
                            @Override
                            public Task<AccessToken> then(Task<Bundle> task) throws Exception {
                                return doGetAccessToken(instance, task.getResult());
                            }
                        }).continueWith(new Continuation<AccessToken, AccessToken>() {
                            @Override
                            public AccessToken then(Task<AccessToken> task) throws Exception {
                                if (task.isFaulted()) {
                                    Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError());
                                    //                                Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show();
                                    callback.onCancelled();
                                } else if (task.isCompleted()) {
                                    AccessToken accessToken = task.getResult();
                                    String serialized = Base64.encodeToString(
                                            SerializationUtils.serialize(accessToken), Base64.DEFAULT);

                                    SharedPreferences preferences = getActivity()
                                            .getSharedPreferences("twitter", Activity.MODE_PRIVATE);
                                    preferences.edit().putString("access_token_str", serialized).apply();
                                    callback.onSessionOpened(accessToken);
                                    mAccessToken = accessToken;

                                    return accessToken;
                                }

                                return null;
                            }
                        });
            } else {
                callback.onSessionOpened(mAccessToken);
                return Task.forResult(mAccessToken);
            }
        }
    });
}