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:com.aremaitch.codestock2010.library.TwitterOAuth.java

License:Apache License

public TwitterOAuth() {
    t = new TwitterFactory().getInstance();
}

From source file:com.cafebab.app.TwitterPublisher.java

License:Open Source License

public void run() {
    while (true) {
        try {//from  ww  w . ja v  a  2  s  .c o  m
            Thread.sleep(TWITTER_FREQUENCY);
        } catch (InterruptedException e) {
        }
        try {
            Date startD = start.get();
            Date endD = end.get();
            Date now = new Date();
            long sinceEnd = now.getTime() - endD.getTime();
            long sinceStart = now.getTime() - startD.getTime();
            String tweet = null;
            if (sinceEnd > INTERVAL) {
                tweet = BABY_OK + convert(sinceEnd) + " (" + sdf.format(endD) + ").";
            } else {
                tweet = BABY_KO + convert(sinceStart) + " (" + sdf.format(startD) + ").";
            }
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.updateStatus(tweet);
            logger.info("Twitter published: " + tweet);
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:com.chantake.MituyaProject.Tool.Twitter.TwitterManager.java

License:Open Source License

/**
 * ?//  w ww.  j  a  v a2s  .co  m
 */
public void init() {
    plugin.Log("Twitter????");
    TwitterFactory factory = new TwitterFactory();
    //AccessToken at = new AccessToken(tokenKey, tokenSecret);
    // AccessToken??
    this.twitter = factory.getInstance();
    //this.twitter.setOAuthConsumer(consumerKey, consumerSecret);
    plugin.Log("Twitter????");
}

From source file:com.codegoogle.twitterandroid.TwitterApp.java

License:Apache License

public TwitterApp(Context context, String consumerKey, String secretKey) {
    this.context = context;
    this.consumerKey = consumerKey;
    this.secretKey = secretKey;

    twitter = new TwitterFactory().getInstance();
    session = new TwitterSession(context);
    progressDialog = new ProgressDialog(context);
    progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, secretKey);

    String request_url = TWITTER_REQUEST_URL;
    String access_token_url = TWITTER_ACCESS_TOKEN_URL;
    String authorize_url = TWITTER_AUTHORZE_URL;

    httpOauthprovider = new DefaultOAuthProvider(request_url, access_token_url, authorize_url);
    accessToken = session.getAccessToken();

    configureToken();//from  www . j  a v  a  2 s .c  o m
}

From source file:com.company.TwitterPopularLinks.java

License:Apache License

public void sparkStreaming(SparkConf conf) {

    ///Creates Streaming Context
    JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(1));

    //Create a Twitter
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessTokenKey, accessTokenKey_secret));

    JavaDStream<Status> stream = TwitterUtils.createStream(jsc, twitter.getAuthorization());

    JavaDStream<String> words = stream.map(new Function<Status, String>() {
        public String call(Status status) {
            return status.getText();
        }// ww  w.  j  av a  2 s.  c  om
    });

    JavaDStream<String> statuses = words.flatMap(new FlatMapFunction<String, String>() {
        public Iterable<String> call(String in) {
            return Arrays.asList(in.split(" "));
        }
    });
    //Get the stream of hashtags from the stream of tweets
    JavaDStream<String> hashTags = statuses.filter(new Function<String, Boolean>() {
        public Boolean call(String word) {
            return word.startsWith("#");
        }
    });
    //Count the hashtags over a 5 minute window
    JavaPairDStream<String, Integer> tuples = hashTags.mapToPair(new PairFunction<String, String, Integer>() {
        public Tuple2<String, Integer> call(String in) {
            return new Tuple2<String, Integer>(in, 1);
        }
    });
    //count these hashtags over a 5 minute moving window
    JavaPairDStream<String, Integer> counts = tuples
            .reduceByKeyAndWindow(new Function2<Integer, Integer, Integer>() {
                public Integer call(Integer i1, Integer i2) {
                    return i1 + i2;
                }
            }, new Function2<Integer, Integer, Integer>() {
                public Integer call(Integer i1, Integer i2) {
                    return i1 - i2;
                }
            }, new Duration(60 * 5 * 1000), new Duration(1 * 1000));

    counts.print();
    //jsc.checkpoint(checkPoint);
    jsc.start();
    jsc.awaitTermination();

}

From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Get the authorization URL and send it back in a sticky broadcast.
 *///from   ww w. ja v a 2  s .  c  o m
private void processGetAuthURL() {

    //create a RequestToken to use to create the request URL 
    // token will be used later to decode result from twitter.com
    // and needs to be saved to static variable in MSTwitter
    RequestToken reqToken = null;
    Twitter twitter4j = null;
    String url = null;
    int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL; // be optimistic 

    try {
        twitter4j = new TwitterFactory().getInstance();
        twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
    } catch (IllegalStateException e) {
        // No network access or token already available
        resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
        Log.e(MSTwitter.TAG, e.toString());
    }

    // get the token
    if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) {
        try {
            reqToken = twitter4j.getOAuthRequestToken(MSTwitter.CALLBACK_URL);
        } catch (TwitterException e) {
            int tErrorNum = MSTwitter.getTwitterErrorNum(e, this);
            // No network access 
            resultCode = tErrorNum;
            Log.e(MSTwitter.TAG, e.getExceptionCode() + ": " + e.getMessage());
        } catch (IllegalStateException e) {
            // No network access or token already available
            resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_TOKEN_ALREADY_AVALIABLE;
            Log.e(MSTwitter.TAG, e.toString());
        }
    }

    // if we got the request token then use it to get the url
    if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) {
        url = reqToken.getAuthenticationURL();
        // save the request token
        MSTwitter.smReqToken = reqToken;
    }

    // broadcast the results
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MSTwitter.INTENT_BROADCAST_MSTWITTER);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_SERVICE_TASK,
            MSTwitterService.MST_SERVICE_TASK_GET_AUTH_URL);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_AUTHURL_RESULT, resultCode);
    if (url != null) {
        broadcastIntent.putExtra(MSTwitterService.MST_KEY_AUTHURL_RESULT_URL, url);
    }
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_TEXT, mText);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_IMAGE_PATH, mImagePath);
    sendStickyBroadcast(broadcastIntent);
}

From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Make the token and save using SharedPreferences. Then send back a sticky broadcast
 * @param extras Bundle containing the oauth verifier string
 *//*from   w w  w . j av  a2s.  c o m*/
private void processMakeToken(Bundle extras) {
    AccessToken accessToken = null;
    int resultCode = MSTwitter.MST_RESULT_NO_PASSED_OAUTH;
    // get the oAuth verifier string from the bundle
    String oAuthVerifier = extras.getString(MST_KEY_AUTH_OAUTH_VERIFIER);
    if (oAuthVerifier != null) {
        // first setup the twitter4j object
        resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;
        Twitter twitter4j = null;
        try {
            twitter4j = new TwitterFactory().getInstance();
            twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
        } catch (IllegalStateException e) {
            // No network access or token already available
            resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
            Log.e(MSTwitter.TAG, e.toString());
        }

        // now get the access token
        if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) {
            try {
                accessToken = twitter4j.getOAuthAccessToken(MSTwitter.smReqToken, oAuthVerifier);
            } catch (NullPointerException e) {
                resultCode = MSTwitter.MST_RESULT_BAD_RESPONSE_FROM_TWITTER;
                Log.e(MSTwitter.TAG, e.toString());
            } catch (UnsupportedOperationException e) {
                resultCode = MSTwitter.MST_RESULT_BAD_RESPONSE_FROM_TWITTER;
                Log.e(MSTwitter.TAG, e.toString());
            } catch (TwitterException e) {
                resultCode = MSTwitter.getTwitterErrorNum(e, this);
                Log.e(MSTwitter.TAG, e.getLocalizedMessage());
            }
        }
    }

    if (accessToken != null) {
        // save the access token parts
        String token = accessToken.getToken();
        String secret = accessToken.getTokenSecret();

        // Create shared preference object to remember if the user has already given us permission
        SharedPreferences refs = this.getSharedPreferences(MSTwitter.PERF_FILENAME, Context.MODE_PRIVATE);
        Editor editor = refs.edit();
        editor.putString(MSTwitter.PREF_ACCESS_TOKEN, token);
        editor.putString(MSTwitter.PREF_ACCESS_TOKEN_SECRET, secret);
        editor.commit();
        resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;
    }

    // broadcast the results
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MSTwitter.INTENT_BROADCAST_MSTWITTER);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_SERVICE_TASK,
            MSTwitterService.MST_SERVICE_TASK_MAKE_TOKEN);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_MAKE_TOKEN_RESULT, resultCode);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_TEXT, mText);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_IMAGE_PATH, mImagePath);
    sendStickyBroadcast(broadcastIntent);
}

From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Sets access token, sends tweet.//from   w  w w. ja v  a  2 s  .  c  o m
 * @category Helpers
 * @return result code
 */
private int sendTweet(String text, String imagePath, AccessToken accessToken) {
    int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;

    // check to make sure we have data and access before tweeting
    if (text == null && imagePath == null) {
        return MSTwitter.MST_RESULT_NO_DATA_TO_SEND;
    }
    if (accessToken == null) {
        return MSTwitter.MST_RESULT_NOT_AUTHORIZED;
    }

    // get twitter4j object
    Twitter twitter4j = null;
    try {
        twitter4j = new TwitterFactory().getInstance();
        twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
    } catch (IllegalStateException e) {
        // No network access or token already available
        resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
        Log.e(MSTwitter.TAG, e.toString());
        return resultCode;
    }

    // Create and set twitter access credentials from token and or secret
    twitter4j.setOAuthAccessToken(accessToken);
    try {
        // finally update the status (send the tweet)
        StatusUpdate status = new StatusUpdate(text);
        if (imagePath != null) {
            status.setMedia(new File(imagePath));
        }
        twitter4j.updateStatus(status);
    } catch (TwitterException e) {
        return MSTwitter.getTwitterErrorNum(e, this);
    }

    return resultCode;
}

From source file:com.eclipsesource.iot.photosensor.example.Main.java

License:Open Source License

private static Twitter setupTwitter() throws TwitterException {
    if (TWITTER_CONFIGURED) {
        TwitterFactory factory = new TwitterFactory();
        final Twitter twitter = factory.getInstance();
        AccessToken accessToken = loadAccessToken();
        authenticateTwitter(accessToken, twitter);
        currentStatus = getCurrentStatus(twitter);
        return twitter;
    }//from   w ww  .  ja va  2s  .  c  om
    return null;
}

From source file:com.esz.thaifloodreporter.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 *
 * @param args message/*from w w w  .j av  a 2 s  .  c om*/
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            RequestToken requestToken = twitter.getOAuthRequestToken();
            System.out.println("Got request token.");
            System.out.println("Request token: " + requestToken.getToken());
            System.out.println("Request token secret: " + requestToken.getTokenSecret());
            AccessToken accessToken = null;

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (null == accessToken) {
                System.out.println("Open the following URL and grant access to your account:");
                System.out.println(requestToken.getAuthorizationURL());
                System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
                String pin = br.readLine();
                try {
                    if (pin.length() > 0) {
                        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                    } else {
                        accessToken = twitter.getOAuthAccessToken(requestToken);
                    }
                } catch (TwitterException te) {
                    if (401 == te.getStatusCode()) {
                        System.out.println("Unable to get the access token.");
                    } else {
                        te.printStackTrace();
                    }
                }
            }
            System.out.println("Got access token.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                System.out.println("OAuth consumer key/secret is not set.");
                System.exit(-1);
            }
        }
        Status status = twitter.updateStatus(args[0]);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}