Example usage for twitter4j TwitterFactory getSingleton

List of usage examples for twitter4j TwitterFactory getSingleton

Introduction

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

Prototype

public static Twitter getSingleton() 

Source Link

Document

Returns default singleton Twitter instance.

Usage

From source file:org.kuali.mobility.conference.controllers.ConferenceController.java

License:Open Source License

@RequestMapping(value = "twitter-search", method = RequestMethod.GET)
public ResponseEntity<String> twitterSearch(@RequestParam(value = "term", required = true) String searchParam,
        @RequestParam(value = "since", required = false) String sinceParam, HttpServletRequest request) {

    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query(searchParam.isEmpty() ? "#kualidays" : searchParam);
    QueryResult result = null;/*  www.  j a  va  2s  . c om*/
    query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01");
    query.setCount(100);
    query.setResultType(Query.MIXED);
    String json = "";
    List<String> tweetList = new ArrayList<String>();

    try {
        result = twitter.search(query);
    } catch (TwitterException e) {
        System.err.println("Caught 'twitterSearch' IOException: " + e.getMessage());
    }

    String tweetInfo = "";
    for (Status status : result.getTweets()) {
        tweetInfo = "{";
        tweetInfo += "\"id\" : \"" + status.getId() + "\", ";
        tweetInfo += "\"avatar\" : \"" + status.getUser().getProfileImageURL() + "\", ";
        tweetInfo += "\"tweetedOn\" : \"" + status.getCreatedAt() + "\", ";
        tweetInfo += "\"tweetedOnParsed\" : \"" + status.getCreatedAt().getTime() + "\", ";
        tweetInfo += "\"screenname\" : \"" + status.getUser().getScreenName() + "\", ";
        tweetInfo += "\"status\" : \""
                + StringEscapeUtils.escapeHtml(status.getText().replaceAll("(\\r|\\n)", "")) + "\", ";
        tweetInfo += "\"truncated\" : \"" + (status.isTruncated() ? "true" : "false") + "\",";
        tweetInfo += "\"retweeted\" : \"" + (status.isRetweet() ? "true" : "false") + "\"";
        tweetInfo += "}";

        tweetList.add(tweetInfo);
    }

    json = "[" + StringUtils.arrayToDelimitedString(tweetList.toArray(), ",") + "]";

    return new ResponseEntity<String>(json, HttpStatus.OK);
}

From source file:org.n52.twitter.TwitterAccessTokenRetriever.java

License:Open Source License

public static void main(String args[]) throws Exception {
    String[] props = readProperties();
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(props[0], props[1]);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*w w  w  . j  ava  2  s.  c o m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        LOGGER.info("Open the following URL and grant access to your account:");
        LOGGER.info(requestToken.getAuthorizationURL());
        LOGGER.info("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                LOGGER.error("Unable to get the access token.");
            } else {
                LOGGER.error(te.getErrorMessage(), te);
            }
        }
    }
    storeAccessToken(accessToken.getToken(), accessToken.getTokenSecret());
}

From source file:org.openhab.action.twitter.internal.TwitterActionService.java

License:Open Source License

/**
 * Creates and returns a Twitter4J Twitter client.
 *
 * @return a new instance of a Twitter4J Twitter client.
 *//*w  w  w.j  ava  2s  .c  o  m*/
private static twitter4j.Twitter createClient() {
    twitter4j.Twitter client = TwitterFactory.getSingleton();
    client.setOAuthConsumer(consumerKey, consumerSecret);
    return client;
}

From source file:org.osframework.maven.plugins.twitter.AbstractTwitterMojo.java

License:Apache License

private Twitter getAuthenticatedTwitter() throws TwitterException {
    if (StringUtils.isBlank(consumerKey) || StringUtils.isBlank(consumerSecret)) {
        throw new TwitterException("Missing required credentials");
    }/*from w  w  w  .j av  a 2 s.  co  m*/
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    loadAccessToken(twitter);
    twitter.setOAuthAccessToken(authToken);
    return twitter;
}

From source file:org.primefaces.examples.mobile.TwitterView.java

License:Open Source License

public void search() {
    try {//from  w ww. j  ava  2s  .c o  m
        Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(keyword);
        tweets = twitter.search(query).getTweets();
    } catch (TwitterException exception) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Please try again");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        RequestContext.getCurrentInstance().update("main:messages");
    }
}

From source file:org.thehecklers.feed.TwitterFeed.java

License:Apache License

public TwitterFeed(String query) {
    //        this.setConsumer("Put Consumer Key Here", "Put Consumer Secret Here");
    //        this.setToken("Put Token Here", "Put Token Secret Here");

    this.twInstance = TwitterFactory.getSingleton();
    ///*from   w  ww .j  av  a  2s  .  c  om*/
    //        twInstance.setOAuthConsumer(this.getConsumerKey(), this.getConsumerSecret());
    //        twInstance.setOAuthAccessToken(new AccessToken(this.getToken(), this.getTokenSecret()));

    try {
        resultSet = twInstance.search(new Query(query));
        messages = resultSet.getTweets();
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterFeed.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.twitter.oauth.java

public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("SjLUa1Pwrs81nIAGiR4f1l4I7", "ISAXBmzqzYLKWQXAaOe09j34APvVOyxahHghLBSvvR0Psnhozl");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//from   ww  w  .  j a  v a 2  s .c  o  m
    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 aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    //persist to the accessToken for future reference.
    storeAccessToken((int) twitter.verifyCredentials().getId(), accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:org.wso2.fasttrack.project.roadlk.rest.DatasetGenerator.java

License:Open Source License

/**
 * @param consumerKey//from ww  w.ja v a  2 s .  c  o  m
 *            Twitter Consumer Key (API Key)
 * @param consumerSecret
 *            Twitter Consumer Secret (API Secret)
 * @param accessToken
 *            Twitter Access Token
 * @param accessTokenSecret
 *            Twitter Access Token Secret
 * @param pageLimit
 *            Maximum pages to be retrieved
 * @throws IOException
 * @throws TwitterException
 */
@SuppressWarnings("resource")
public void generateDataset(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret, int pageLimit) throws IOException, TwitterException {
    // Twitter object of Twitter4J library
    Twitter twitter = TwitterFactory.getSingleton();

    // Twitter API authentication
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    PrintWriter printWriter = null;

    try {
        printWriter = new PrintWriter(new BufferedWriter(new FileWriter("dataset.txt", true)));
    } catch (IOException e) {
        throw new IOException(e);
    }

    LOGGER.debug("Twitter feed extraction started.");

    for (int i = 1; i < pageLimit; i = i + 1) {

        Paging paging = new Paging(i, 100);
        ResponseList<Status> statuses = null;

        try {
            statuses = twitter.getUserTimeline("road_lk", paging);
        } catch (TwitterException e) {
            //LOGGER.error("TwitterException occurred." + e.getMessage());
            throw new TwitterException(e);
        }

        for (Status status : statuses) {
            printWriter.println(status.getCreatedAt() + ": " + status.getText());
        }
    }
    printWriter.close();
    LOGGER.debug("Twitter feed extraction completed.");
}

From source file:radnet.ConfigWindow.java

private void twit_submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_twit_submitActionPerformed
    // TODO add your handling code here:

    if (twit_submit.getText() == "Verify Pin") {
        try {//from w w w  .  j  a va2  s  . co  m
            if (twit_password.getText().length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, twit_password.getText());
                // prepare for twitter data dump

                System.out.println(accessToken.getScreenName());
                System.out.println(accessToken.getUserId());
                System.out.println(accessToken.getToken());
                System.out.println(accessToken.getTokenSecret());
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    } else {
        try {
            twitter = TwitterFactory.getSingleton();
            twitter.setOAuthConsumer("aC3MoxJN7AN23kHjVwf7Gq92H",
                    "JA0yGiAeBZsUfafVKuNoQ8kUY9nYqr7WCR5bp4LRMAxnKRM46a");
            requestToken = twitter.getOAuthRequestToken();
            accessToken = null;

            twit_password.setEnabled(true);
            twit_submit.setText("Verify Pin");
            Desktop.getDesktop().browse(java.net.URI.create(requestToken.getAuthenticationURL()));
        } catch (Exception ex) {
            System.out.println("An unhandled exception has occured.");
        }
    }
}

From source file:rtb.PopularTweetCollector.java

License:Apache License

public PopularTweetCollector() {
    twitter = TwitterFactory.getSingleton();
    logger = LoggerFactory.getLogger(PopularTweetCollector.class);
}