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:javatwiter4j.NewJFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    String tweet = "";
    tweet = jTextField1.getText();//  w w w. jav  a 2s  .co m
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(apiKey, apiSecretKey);
        AccessToken accessTokenn = new AccessToken(accessToken, accessTokenSecret);
        twitter.setOAuthAccessToken(accessTokenn);
        twitter.updateStatus(tweet);
    } catch (Exception ex) {
        jLabel1.setText("Son Tweet: Gnderilemedi");
    }
    jLabel1.setText("Son Tweet: Gnderildi");
}

From source file:javatwitterserver.JavaTwitter.java

public JavaTwitter(String consumerKeyStr, String consumerSecretStr, String accessTokenStr,
        String accessTokenSecretStr) {
    this.consumerKeyStr = consumerKeyStr;
    this.consumerSecretStr = consumerSecretStr;
    this.accessTokenStr = accessTokenStr;
    this.accessTokenSecretStr = accessTokenSecretStr;
    twitter = null;/*from www  . j  av a 2 s.  co m*/
    accessToken = null;

    try {
        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(this.consumerKeyStr, this.consumerSecretStr);
        accessToken = new AccessToken(this.accessTokenStr, this.accessTokenSecretStr);
        twitter.setOAuthAccessToken(accessToken);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Jimbo.Cheerlights.TweetListener.java

License:Open Source License

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException// w ww  .  jav  a2  s.  co  m
 * @throws java.io.IOException
 * @throws org.apache.commons.cli.ParseException In case of command line error
 */
public static void main(String[] args) throws TwitterException, IOException, ParseException {
    // Set up simpler logging to stdout
    Jimbo.Logging.Logging.useStdout();

    LOG.log(Level.INFO, "Starting twitter listener");

    Options options = new Options();

    options.addOption("b", Listener.MQTT_BROKER_KEY, true, "URL of the broker")
            .addOption("c", Listener.MQTT_CLIENT_KEY, true, "The MQTT client name to use")
            .addOption("t", Listener.MQTT_TOPIC_KEY, true, "The MQTT topic to use");

    CommandLineParser parser = new DefaultParser();
    CommandLine command = parser.parse(options, args);

    MQTTClient mqtt = null;
    String mqtt_topic = Listener.DEFAULT_MQTT_TOPIC;

    if (command.hasOption(Listener.MQTT_BROKER_KEY)) {
        if (!command.hasOption(Listener.MQTT_CLIENT_KEY))
            throw new ParseException("MQTT without client name");

        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            mqtt_topic = command.getOptionValue(Listener.MQTT_TOPIC_KEY);

        try {
            mqtt = new MQTTClient(command.getOptionValue(Listener.MQTT_BROKER_KEY),
                    command.getOptionValue(Listener.MQTT_CLIENT_KEY));
            mqtt.run();
        }

        catch (MqttException e) {
            LOG.log(Level.WARNING, "Failed to create MQTT client: {0}", e.toString());
        }
    } else {
        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            LOG.warning("MQTT topic supplied but no broker");

        if (command.hasOption(Listener.MQTT_CLIENT_KEY))
            LOG.warning("MQTT client name but no broker");
    }

    Twitter twitter = new TwitterFactory().getInstance();
    StatusListener listener = new listener("224.1.1.1", (short) 5123, mqtt, mqtt_topic);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "#cheerlights" };

    fq.track(keywords);

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.filter(fq);

    LOG.log(Level.INFO, "Up and running....");
}

From source file:jp.co.tweetmap.util.TwitterUtils.java

License:Apache License

/**
 * Gets the Twitter instance. Access token is automatically set if it is saved.
 *
 * @param context {@link Context}, not {@code null}.
 * @return Twitter instance./*from   ww  w  . ja  v  a 2s  .c  o  m*/
 */
public static Twitter getTwitterInstance(Context context) {
    String consumerKey = context.getString(R.string.twitter_consumer_key);
    String consumerSecret = context.getString(R.string.twitter_consumer_secret_key);

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    if (hasAccessToken(context)) {
        twitter.setOAuthAccessToken(loadAccessToken(context));
    }
    return twitter;
}

From source file:jp.ky.twittersample.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 *
 * @param args message//w ww .  j  a  va  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);
    //        }
    String message = "Test5";
    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(message);
        //System.out.println("Successfully updated the status to [" + status.getText() + "].");
        AccountSettings as = twitter.getAccountSettings();
        System.out.println("accountsettings:" + as.getScreenName());

        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);
    }
}

From source file:jp.wda.azeda.core.daemons.impl.RetweetsCrawlerImpl.java

License:Apache License

/**
 *
 *//*w w w.j a  va 2  s.  c  o  m*/
@Aspect("aop.requiredTx")
public void crawl() throws TwitterException {
    log.debug("crawl retweets!!" + tweets.size());
    if (tweets.size() == 0) {
        loadTweets();
    }
    if (tweets.size() == 0) {
        return;
    }

    RetweetedTweet tweet = tweets.remove(0);
    log.debug("check tweet " + tweet.getTweetID());

    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(tweet.getAccessToken().getAccessToken(),
            tweet.getAccessToken().getAccessTokenSecret());
    twitter.setOAuthAccessToken(accessToken);

    ResponseList<Status> rt = getRetweets(twitter, tweet.getTweetID());
    if (!alive) {
        return;
    }
    if (rt == null || rt.size() == 0) {
        return;
    }

    HashMap<Long, Status> retweets = new HashMap<Long, Status>();
    for (Status status : rt) {
        retweets.put(status.getUser().getId(), status);
    }

    List<Retweeter> registered = retweetersDao.getRetweeterIDs(tweet.getTweetID());
    for (Retweeter retweeter : registered) {
        long registeredUserID = retweeter.getRetweeterID();
        if (retweets.containsKey(registeredUserID)) {
            retweets.remove(registeredUserID);
            continue;
        }
    }
    if (retweets.size() == 0) {
        return;
    }

    for (Status status : retweets.values()) {
        long retweeter = status.getUser().getId();
        long oldest = System.currentTimeMillis() - retweetExpired * 60 * 1000L;
        if (status.getCreatedAt().getTime() < oldest) {
            log.info(tweet.getTweetID() + " retweet by " + status.getUser().getScreenName() + " ? "
                    + retweetExpired + "?????????");
            insertRetweeter(twitter.getId(), tweet.getTweetID(), retweeter);
            continue;
        }

        List<Status> userTimeline = loadRetweetersTweets(twitter, tweet.getTweetID(), retweeter, 1);
        if (!alive) {
            return;
        }
        if (userTimeline == null) {
            continue;
        }

        int skips = 0;
        for (int i = userTimeline.size() - 1; i >= 0; i--) {
            Status s = userTimeline.get(i);
            UserMentionEntity[] mentions = s.getUserMentionEntities();
            if (s.isRetweet()) {
                skips++;
                continue;
            }
            if (mentions == null || mentions.length > 0) {
                skips++;
                continue;
            }

            log.debug(s.getId() + ":" + s.getCreatedAt() + "(" + s.isRetweet() + ") " + s.getText());

            Retweet retweet = new Retweet();
            retweet.setTweetID(s.getId());
            retweet.setRetweetTo(tweet.getTweetID());
            retweet.setRetweeterID(retweeter);
            retweet.setTweettext(s.getText());
            retweet.setCreatedat(new Timestamp(s.getCreatedAt().getTime()));
            retweet.setSkiptweets(skips);
            retweet.setScreenName(status.getUser().getScreenName());
            dtoRetweets.add(retweet);

            insertRetweeter(twitter.getId(), tweet.getTweetID(), retweeter);
            break;
        }
    }

    register();
}

From source file:jp.wda.azeda.core.daemons.impl.UserCrawlerImpl.java

License:Apache License

/**
 *
 *//*  www .j  a v a  2  s  . c  o m*/
@Aspect("aop.requiredTx")
public void crawl() throws TwitterException {
    StoredAccessToken storedAccessToken = accessTokensDao.getAccessTokenByUserID(userID);
    if (storedAccessToken == null) {
        return;
    }
    if (!alive) {
        return;
    }
    log.debug("crawl user retweets!!");

    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(storedAccessToken.getAccessToken(),
            storedAccessToken.getAccessTokenSecret());
    twitter.setOAuthAccessToken(accessToken);

    List<Status> retweets = twitter.getRetweetsOfMe();
    if (!alive) {
        return;
    }

    List<RetweetedTweet> registered = dao.getAll(userID,
            new Timestamp(System.currentTimeMillis() - 365 * 24 * 60 * 60 * 1000L));
    List<Long> registeredIDs = new ArrayList<Long>();
    for (RetweetedTweet t : registered) {
        registeredIDs.add(t.getTweetID());
    }
    if (!alive) {
        return;
    }

    List<RetweetedTweet> dtos = new ArrayList<RetweetedTweet>();
    long oldest = System.currentTimeMillis() - expired * 24 * 60 * 60 * 1000L;
    for (Status s : retweets) {
        if (registeredIDs.contains(s.getId())) {
            continue;
        }
        if (s.getCreatedAt().getTime() < oldest) {
            continue;
        }

        RetweetedTweet dto = new RetweetedTweet();
        dto.setTweetID(s.getId());
        dto.setUserID(userID);
        dto.setTweettext(s.getText());
        dto.setCreatedat(new Timestamp(s.getCreatedAt().getTime()));
        dtos.add(dto);
    }
    if (!alive) {
        return;
    }
    dao.insertBatch(dtos);
}

From source file:jp.wda.azeda.core.logics.impl.TwitterServiceImpl.java

License:Apache License

/** {@inheritDoc} */
@Override/*from   w  ww  .  j  av a  2 s.c  om*/
public CheckAuthorizedResult checkAuthorized(String account, String callbackURL) throws TwitterException {
    CheckAuthorizedResult result = new CheckAuthorizedResult();
    StoredAccessToken at = accessTokensDao.getAccessToken(account);
    if (at != null) {
        return result;
    }

    Twitter twitter = new TwitterFactory().getInstance();
    String requestID = UUID.randomUUID().toString();
    RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL + requestID);
    requestTokens.put(requestID, requestToken);

    result.status = -1;
    result.redirectTo = requestToken.getAuthorizationURL();

    return result;
}

From source file:jp.wda.azeda.core.logics.impl.TwitterServiceImpl.java

License:Apache License

/** {@inheritDoc} */
@Override/*from   w  ww  . jav  a  2 s . com*/
public void registerAccessToken(String requestID, String oauthVerifier) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken requestToken = requestTokens.get(requestID);
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier);

    StoredAccessToken dbToken = new StoredAccessToken();
    dbToken.setUserID(accessToken.getUserId());
    dbToken.setAccount(accessToken.getScreenName());
    dbToken.setAccessToken(accessToken.getToken());
    dbToken.setAccessTokenSecret(accessToken.getTokenSecret());
    dbToken.setUpdatedAt(new java.sql.Timestamp(System.currentTimeMillis()));

    try {
        accessTokensDao.update(dbToken);
    } catch (NotSingleRowUpdatedRuntimeException ex) {
        accessTokensDao.insert(dbToken);
    }

    crawlerFactory.startCrawl(dbToken.getUserID());
}

From source file:Jums.SearchTweets.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param args search query/*from   www .  jav a2s. com*/
 */
public void main(String args) {
    System.out.println("java twitter4j.examples.search.SearchTweets [query]");
    System.exit(-1);

    Twitter twitter = new TwitterFactory().getInstance();
    try {
        Query query = new Query(args);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}