Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

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

License:Apache License

@Override
public void tweets(final StatusUpdate latestStatus, @NonNull final ResponseCallback callback) {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey)
            .setOAuthConsumerSecret(mConsumerSecret).build();

    final Twitter instance = new TwitterFactory(configuration).getInstance();
    if (mAccessToken != null) {
        instance.setOAuthAccessToken(mAccessToken);
    }/*from w  w w.  j  av  a 2  s  . c  o  m*/

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

                mAccessToken = null;
                instance.setOAuthAccessToken(null);
                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(task.getError());
                            source.trySetError(task.getError());
                        } 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();
                            instance.setOAuthAccessToken(accessToken);

                            mAccessToken = accessToken;
                            source.trySetResult(mAccessToken);
                            return accessToken;
                        }

                        return null;
                    }
                });
                return source.getTask();
            } else {
                return Task.forResult(mAccessToken);
            }
            //            }
            //        }).onSuccessTask(new Continuation<AccessToken, Task<Map<String, RateLimitStatus>>>() {
            //            @Override
            //            public Task<Map<String, RateLimitStatus>> then(Task<AccessToken> task) throws Exception {
            //                return doCheckStatus(instance);
        }
    }).onSuccessTask(new Continuation<AccessToken, Task<Status>>() {
        @Override
        public Task<Status> then(Task<AccessToken> task) throws Exception {
            //                Map<String, RateLimitStatus> result = task.getResult();

            return doTweet(instance, latestStatus);
        }
    }).continueWith(new Continuation<Status, Object>() {
        @Override
        public Object then(Task<Status> task) throws Exception {
            if (task.isFaulted()) {
                Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError());
                String message = task.getError().getMessage();
                if (!TextUtils.isEmpty(message)) {
                    //                        Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                }
                callback.onCancelled(task.getError());
            } else if (task.isCompleted()) {
                callback.onCompleted(task.getResult());
            }

            return null;
        }
    });
}

From source file:com.mycompany.dovetune.SignIn.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w.j  a va  2 s.  co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Djgh7AmnNzxmv7fXzqlsdj8RB")
            .setOAuthConsumerSecret("Mnj40YllwKBBZvOkndnrmxl1TaNvcnS0x40PFhhDnMHysgzHum");

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

    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        System.out.println("TwitterLoginServlet:callbackURL:" + callbackURL);

        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/Callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        System.out.println("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:com.mycompany.mech2015task.App.java

public static void main(String[] args) throws Exception {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(CONSUMER_KEY);
    builder.setOAuthConsumerSecret(CONSUMER_SECRET);
    builder.setOAuthAccessToken(ACCESS_TOKEN);
    builder.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);

    // ??Twitter4J??API???betastream.twitter.com???????
    builder.setUserStreamBaseURL("https://userstream.twitter.com/2/");

    // Configuration?
    Configuration configuration = builder.build();

    /*        Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
        .setOAuthConsumerSecret(CONSUMER_SECRET)
        .setOAuthAccessToken(ACCESS_TOKEN)
        .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET)
        .build();//from   w  w w  .j  av a2 s . c o  m
    */
    TwitterStream twStream = new TwitterStreamFactory(configuration).getInstance();
    //TwitterStream twStream = new TwitterStreamFactory().getInstance();
    twStream.addListener(new MyStatusListener());
    twStream.user();
    //twStream.sample();
}

From source file:com.mycompany.omnomtweets.Search.java

public static void main(String[] args) throws TwitterException {
    System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.NullLoggerFactory");
    if (args.length >= 1) {
        candidate = Candidate.valueOf(args[0]);
        System.out.println("Getting tweets on " + candidate.name);
    } else {/*from w  w  w . j ava 2 s.c o  m*/
        //System.out.println("You didn't give me a candidate, so you get TRUMP");
    }
    //System.out.println("Starting at: " + sdf.format(new Date()));
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(candidate.consumerKey)
            .setOAuthConsumerSecret(candidate.consumerSecret).setOAuthAccessToken(candidate.accessToken)
            .setOAuthAccessTokenSecret(candidate.accessTokenSecret);

    final ArrayList<Status> statuses = new ArrayList<>();

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            statuses.add(status);
            writeToStdErr(status);
            //Removed because writing to STD OUT instead.
            //System.out.println("statuses: " + statuses.size());
            if (statuses.size() >= 100) {
                /*System.out.println("Writing " + statuses.size() + " to file " + 
                            "at: " + sdf.format(new Date()));*/
                writeTweetsToFile(statuses, candidate.name + "StreamTweets.txt");
                statuses.clear();
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            //System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            //System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        public void onScrubGeo(long userId, long upToStatusId) {
            //System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        public void onException(Exception ex) {
            //ex.printStackTrace();
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };

    FilterQuery fq = new FilterQuery();
    String keywords[] = candidate.aliases;

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
}

From source file:com.mycompany.twitterapp.TwitterApp.java

public void buildConfig() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("")
            .setOAuthAccessTokenSecret("");
    TwitterFactory tf = new TwitterFactory(cb.build());

    twitter = tf.getInstance();//from   ww w .j av  a  2  s .c  o m
}

From source file:com.mycompany.twitterproductanalysistool.TwitterAPI.java

public TwitterAPI() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("ogluOfaFe00xjVQ5WfynhkWQY")
            .setOAuthConsumerSecret("l4yL7iz6J1zEBaY4ownHu9VnIu2zSLuELVyzxykgoSEF3vzSup")
            .setOAuthAccessToken("1101064884-uMgjzYHHo82fRZdwWbvjNWs8ZKqoZj0xsKB4jnO")
            .setOAuthAccessTokenSecret("WyCAT00L4FK0lOQiXhshNXpS5bHVFoVsaoYGlJYVylWYm");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();// ww w  . j a  v  a  2s.  c o  m
}

From source file:com.mycompany.twittersearch.SignIn.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww .j  ava 2 s.  c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("");

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

    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        System.out.println("TwitterLoginServlet:callbackURL:" + callbackURL);

        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/Callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        System.out.println("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }

}

From source file:com.mysportsshare.mysportscast.utils.HelperMethods.java

License:Apache License

public static void postToTwitter(Context context, final Activity callingActivity, final String message,
        final TwitterCallback postResponse) {
    SharedPreferences mSharedPref = context.getSharedPreferences("Android_Twitter_Preferences",
            Context.MODE_PRIVATE);
    if (mSharedPref.getString(Constants.KEY_TWITTER_ACCESS_TOKEN, null) == null) {
        postResponse.onFinsihed(false);/*from w  w w. j av  a 2s . com*/
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(HomeActivity.CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(HomeActivity.CONSUMER_SECRET);
    configurationBuilder.setOAuthAccessToken(HomeActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(HomeActivity.getAccessTokenSecret(context));
    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();
                twitter.updateStatus(message);
            } catch (TwitterException 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.mysportsshare.mysportscast.utils.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final Activity callingActivity,
        final String imageUrl, final String message, final TwitterCallback postResponse) {
    SharedPreferences mSharedPref = context.getSharedPreferences("Android_Twitter_Preferences",
            Context.MODE_PRIVATE);
    if (mSharedPref.getString(Constants.KEY_TWITTER_ACCESS_TOKEN, null) == null) {
        postResponse.onFinsihed(false);//from w  w w .j  ava 2  s  .co  m
        return;
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(HomeActivity.CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(HomeActivity.CONSUMER_SECRET);
    configurationBuilder.setOAuthAccessToken(HomeActivity.getAccessToken((context)));
    configurationBuilder.setOAuthAccessTokenSecret(HomeActivity.getAccessTokenSecret(context));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    final File file = new File(imageUrl);

    new Thread(new Runnable() {

        @Override
        public void run() {
            boolean success = true;
            try {
                if (file.exists()) {
                    StatusUpdate status = new StatusUpdate(message);
                    status.setMedia(file);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (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.narvis.frontend.twitter.AccessTwitter.java

License:Open Source License

private Pair<TwitterStream, Twitter> loadAccessTwitter(String token, String tokenSecret, String consumerKey,
        String consumerSecret) {/*  w  ww  . ja  va  2 s. c o m*/
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(token);
    cb.setOAuthAccessTokenSecret(tokenSecret);
    Configuration authConf = cb.build();
    return new Pair(new TwitterStreamFactory(authConf).getInstance(),
            new TwitterFactory(authConf).getInstance());
}