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:de.jetsli.twitter.TwitterSearch.java

License:Apache License

/**
 * Opening the url will show you a PIN//from  www  .ja  v  a 2s.  c  o m
 *
 * @throws TwitterException
 */
public RequestToken doDesktopLogin() throws TwitterException {
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken("");
    System.out.println("Open the following URL and grant access to your account:");
    System.out.println(requestToken.getAuthorizationURL());
    return requestToken;

}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

/**
 * @return the url where the user should be redirected to
 *//*  w  w  w.  j a v a 2  s  .c  o  m*/
public String oAuthLogin(String callbackUrl) throws Exception {
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    tmpRequestToken = twitter.getOAuthRequestToken(callbackUrl);
    return tmpRequestToken.getAuthenticationURL();
}

From source file:de.jetwick.ese.search.Feeding.java

License:Apache License

public Collection<MyTweet> createReal() {
    List<MyTweet> tweets = new ArrayList<MyTweet>();
    try {/*from  w  w  w  .ja v a  2 s.  com*/
        // get some tweets about java
        Twitter twitter4j = new TwitterFactory().getInstance();
        for (int i = 0; i < 3; i++) {
            Query q = new Query("java");
            q.setRpp(100);
            for (Tweet tw : twitter4j.search(q).getTweets()) {
                MyTweet myTw = new MyTweet(tw.getId(), tw.getFromUser());
                myTw.setText(tw.getText());
                myTw.setCreatedAt(tw.getCreatedAt());
                myTw.setFromUserId(tw.getFromUserId());
                tweets.add(myTw);
            }
            Thread.sleep(1000);
        }
    } catch (Exception ex) {
        logger.error("Error while grabbing tweets from twitter!", ex);
    }

    return tweets;
}

From source file:de.jetwick.tw.NewClass.java

License:Apache License

/** A thread using the search API */
public Thread search() {
    return new Thread() {

        @Override/* www .j  a  v  a  2s .  c  o m*/
        public void run() {
            int MINUTES = 2;
            Twitter twitter = new TwitterFactory().getInstance();
            try {
                while (!isInterrupted()) {
                    Query query = new Query(queryTerms);
                    // RECENT or POPULAR or MIXED
                    // doesn't make a difference if MIXED or RECENT
                    query.setResultType(Query.MIXED);
                    query.setPage(1);
                    query.setRpp(100);
                    QueryResult res = twitter.search(query);
                    for (Tweet tw : res.getTweets()) {
                        searchMap.put(tw.getId(), tw.getText());
                    }
                    Thread.sleep(MINUTES * 60 * 1000L);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

/**
 * Connect with twitter to get a new personalized twitter4j instance.
 *
 * @throws RuntimeException if verification or connecting failed
 *///  www . j  a  va 2 s . c  o m
public TwitterSearch initTwitter4JInstance(String token, String tokenSecret, boolean verify) {
    if (consumerKey == null)
        throw new NullPointerException("Please use init consumer settings!");

    setupProperties();
    AccessToken aToken = new AccessToken(token, tokenSecret);
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(aToken);
    try {
        //            RequestToken requestToken = t.getOAuthRequestToken();
        //            System.out.println("TW-URL:" + requestToken.getAuthorizationURL());
        if (verify)
            twitter.verifyCredentials();

        String str = "<user>";
        try {
            str = twitter.getScreenName();
        } catch (Exception ex) {
        }
        logger.info("create new TwitterSearch for " + str + " with verifification:" + verify);
    } catch (TwitterException ex) {
        // rate limit only exceeded
        if (ex.getStatusCode() == 400)
            return this;

        throw new RuntimeException(ex);
    }
    return this;
}

From source file:demo.happiness.AnalysisLogic.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  www . j  ava2 s .  com*/
 *
 * @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 {
    String username = request.getParameter("user");
    Twitter t = (new TwitterFactory()).getInstance();
    SentimentAnalyzer sa = new SentimentAnalyzer();
    sa.setUserName(username); // username 
    try {
        sa.start();
    } catch (TwitterException e) {
        RequestDispatcher rd = request.getRequestDispatcher("./index.jsp?msg=usernotfound");
        rd.forward(request, response);
    }
    Map<Date, Integer> dailyScore = sa.getDailyScore();
    String userurl = sa.getImageUrl();

    HttpSession session = request.getSession();
    session.setAttribute("dailyScore", dailyScore);
    session.setAttribute("userUrl", userurl);

    RequestDispatcher rd = request.getRequestDispatcher("./display.jsp");
    rd.forward(request, response);
}

From source file:dgsf.twittertree.AbstractNode.java

License:Open Source License

/** costruttore della classe {@link AbstractNode}
 * @param fatherFullKey chiave completa del nodo padre 
 * @param key chiave del nodo attuale/*from   w  w w. j  ava2  s.c o  m*/
 * @param father puntatore al nodo genitore
 * **/
public AbstractNode(String fatherFullKey, String key, Node father) {
    this.fullKey = fatherFullKey + "/" + key; /* crea il percorso assoluto del nodo */
    this.key = key; /* crea chiave del nodo */
    this.fatherNode = father; /* puntatore al nodo padre */

    /* Recupera l'oggetto di Twitter associato all'applicazione */
    this.twitter = new TwitterFactory().getInstance();
}

From source file:dk.netarkivet.harvester.tools.TwitterDecidingScope.java

License:Open Source License

/**
 * This routine makes any necessary Twitter API calls and queues the content discovered.
 *
 * @param controller The controller for this crawl.
 *//*from   w w w. ja va 2 s. c o m*/
@Override
public void initialize(CrawlController controller) {
    super.initialize(controller);
    twitter = (new TwitterFactory()).getInstance();
    keywords = null;
    try {
        keywords = (StringList) super.getAttribute(ATTR_KEYWORDS);
        pages = ((Integer) super.getAttribute(ATTR_PAGES)).intValue();
        geoLocations = (StringList) super.getAttribute(ATTR_GEOLOCATIONS);
        language = (String) super.getAttribute(ATTR_LANG);
        if (language == null) {
            language = "all";
        }
        resultsPerPage = (Integer) super.getAttribute(ATTR_RESULTS_PER_PAGE);
        queueLinks = (Boolean) super.getAttribute(ATTR_QUEUE_LINKS);
        queueUserStatus = (Boolean) super.getAttribute(ATTR_QUEUE_USER_STATUS);
        queueUserStatusLinks = (Boolean) super.getAttribute(ATTR_QUEUE_USER_STATUS_LINKS);
        queueKeywordLinks = (Boolean) super.getAttribute(ATTR_QUEUE_KEYWORD_LINKS);
    } catch (AttributeNotFoundException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (MBeanException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (ReflectionException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    for (Object keyword : keywords) {
        log.info("Twitter Scope keyword: {}", keyword);
    }
    // If keywords or geoLocations is missing, add a list with a single empty string so that the main loop is
    // executed at least once.
    if (keywords == null || keywords.isEmpty()) {
        keywords = new StringList("keywords", "empty keyword list", new String[] { "" });
    }
    if (geoLocations == null || geoLocations.isEmpty()) {
        geoLocations = new StringList("geolocations", "empty geolocation list", new String[] { "" });
    }
    log.info("Twitter Scope will queue {} page(s) of results.", pages);
    // Nested loop over keywords, geo_locations and pages.
    for (Object keyword : keywords) {
        String keywordString = (String) keyword;
        for (Object geoLocation : geoLocations) {
            String urlQuery = (String) keyword;
            Query query = new Query();
            query.setRpp(resultsPerPage);
            if (language != null && !language.equals("")) {
                query.setLang(language);
                urlQuery += " lang:" + language;
                keywordString += " lang:" + language;
            }
            urlQuery = "http://twitter.com/search/" + URLEncoder.encode(urlQuery);
            if (queueKeywordLinks) {
                addSeedIfLegal(urlQuery);
            }
            for (int page = 1; page <= pages; page++) {
                query.setPage(page);
                if (!keyword.equals("")) {
                    query.setQuery(keywordString);
                }
                if (!geoLocation.equals("")) {
                    String[] locationArray = ((String) geoLocation).split(",");
                    try {
                        GeoLocation location = new GeoLocation(Double.parseDouble(locationArray[0]),
                                Double.parseDouble(locationArray[1]));
                        query.setGeoCode(location, Double.parseDouble(locationArray[2]), locationArray[3]);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    final QueryResult result = twitter.search(query);
                    List<Tweet> tweets = result.getTweets();
                    for (Tweet tweet : tweets) {
                        long id = tweet.getId();
                        String fromUser = tweet.getFromUser();
                        String tweetUrl = "http://www.twitter.com/" + fromUser + "/status/" + id;
                        addSeedIfLegal(tweetUrl);
                        tweetCount++;
                        if (queueLinks) {
                            extractEmbeddedLinks(tweet);
                        }
                        if (queueUserStatus) {
                            String statusUrl = "http://twitter.com/" + tweet.getFromUser() + "/";
                            addSeedIfLegal(statusUrl);
                            linkCount++;
                            if (queueUserStatusLinks) {
                                queueUserStatusLinks(tweet.getFromUser());
                            }
                        }
                    }
                } catch (TwitterException e1) {
                    log.error(e1.getMessage());
                }
            }
        }

    }
    System.out.println(
            TwitterDecidingScope.class + " added " + tweetCount + " tweets and " + linkCount + " other links.");
}

From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java

public String authorizeTwitter() {
    String callbackURL = "http://" + PropertyUtil.getHostUrl() + "/dvn";
    callbackURL += getVDCRequestBean().getCurrentVDC() == null ? "/faces/networkAdmin/NetworkOptionsPage.xhtml"
            : getVDCRequestBean().getCurrentVDCURL() + "/faces/admin/OptionsPage.xhtml";

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

    try {//from  w w  w  .j a  v  a 2s  .co  m
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);
        getSessionMap().put("requestToken", requestToken);
        redirect(requestToken.getAuthorizationURL());
    } catch (TwitterException te) {
        te.printStackTrace();
    }

    return null;
}

From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java

public void addTwitter() {
    Long vdcId = getVDCRequestBean().getCurrentVDCId();

    try {//from w ww.ja  v  a  2s .  c o m
        Twitter twitter = new TwitterFactory().getInstance();
        AccessToken accessToken = twitter
                .getOAuthAccessToken((RequestToken) getSessionMap().remove("requestToken"), twitterVerifier);
        vdcService.setTwitterCredentials(accessToken.getToken(), accessToken.getTokenSecret(), vdcId);

        if (vdcId != null) {
            // refresh the current vdc object, since it has changed
            getVDCRequestBean().setCurrentVDC(vdcService.findById(vdcId));
        }
        getVDCRenderBean().getFlash().put("successMessage", "Automatic tweets are now enabled.");

    } catch (TwitterException te) {
        te.printStackTrace();
    }
}