Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

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

Prototype

public Configuration build() 

Source Link

Usage

From source file:tweet.Miner.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param toSearch  /* w  w  w.j a v  a  2 s.  c  o  m*/
 */
public List<Status> mine(String toSearch) {
    List<Status> results = new ArrayList<Status>();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
            .setOAuthAccessToken(OAUTH_ACCESS_TOKEN).setOAuthAccessTokenSecret(OAUTH_ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {
        Query query = new Query(toSearch);
        query.setCount(100);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            results.addAll(result.getTweets());
            for (Status tweet : tweets) {
                System.out.println(
                        tweet.getId() + " @ " + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return results;
}

From source file:tweetdownloader.cnr_stable.version.TwitterAuthHandler.java

/**
 * Is used to get permission for get the tweets.
 * @return/*w w  w.jav a 2  s .co  m*/
 */
public OAuth2Token getOAuth2Token() {
    OAuth2Token token = null;
    ConfigurationBuilder cb;
    cb = new ConfigurationBuilder();
    cb.setApplicationOnlyAuthEnabled(true);
    cb.setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET);
    try {
        token = new TwitterFactory(cb.build()).getInstance().getOAuth2Token();
    } catch (Exception e) {
        System.out.println("Could not get OAuth2 token");
        e.printStackTrace();
        System.exit(0);
    }
    return token;
}

From source file:tweetdownloader.cnr_stable.version.TwitterAuthHandler.java

/**
 * This method give you the auth to work with Twitter API
 * @return istance of Twitter/*from  w  w  w .  j  a  v a  2  s  . c o m*/
 */
public Twitter getTwitter() {
    OAuth2Token token;
    token = getOAuth2Token();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setApplicationOnlyAuthEnabled(true);
    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
    cb.setOAuth2TokenType(token.getTokenType());
    cb.setOAuth2AccessToken(token.getAccessToken());
    return new TwitterFactory(cb.build()).getInstance();
}

From source file:tweete.Tweete.java

License:Open Source License

public void updateTweete(String sta) {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("######################")
            .setOAuthConsumerSecret("######################")
            .setOAuthAccessToken("############################################")
            .setOAuthAccessTokenSecret("############################################");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//from ww  w  .ja v a 2 s.c om

    try {

        twitter.updateStatus(sta);

        System.out.println("Successfully updated the status in Twitter.");

    } catch (TwitterException te) {

        if (401 == te.getStatusCode()) {
            System.out.println("Unable to get the access token.");
        }

        else if (92 == te.getStatusCode()) {
            System.out.println("SSL is required");
        }

        else {
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    } catch (Exception e) {
        System.out.println("Something went wrong");
    }
}

From source file:tweete.Tweete.java

License:Open Source License

public void showTimeline() {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("######################")
            .setOAuthConsumerSecret("######################")
            .setOAuthAccessToken("############################################")
            .setOAuthAccessTokenSecret("############################################");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//ww w  . j  av a  2s.c  om

    try {
        ResponseList<Status> a = twitter.getUserTimeline(new Paging(1, 10));
        String statuses = "";
        for (Status b : a) {
            statuses = statuses + b.getText() + "\n\n---------------------------------------\n\n";

        }

        new TweeteTimeline().Timeline(statuses);
    } catch (TwitterException te) {
        //te.printStackTrace();

        if (401 == te.getStatusCode()) {
            System.out.println("Unable to get the access token.");
        }

        else if (92 == te.getStatusCode()) {
            System.out.println("SSL is required");
        }

        else {
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    } catch (Exception e) {
        System.out.println("Something went wrong");
    }
}

From source file:tweete.Tweete.java

License:Open Source License

public void sendMessage(String id, String msg) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("######################")
            .setOAuthConsumerSecret("######################")
            .setOAuthAccessToken("############################################")
            .setOAuthAccessTokenSecret("############################################");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();/* www. j  a  v a 2  s  .  c o m*/

    try {
        DirectMessage message = null;
        message = twitter.sendDirectMessage(id, msg);
        System.out.println("Sent: " + message.getText() + " to @" + message.getRecipientScreenName());

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

        if (401 == te.getStatusCode()) {
            System.out.println("Unable to get the access token.");
        }

        else if (92 == te.getStatusCode()) {
            System.out.println("SSL is required");
        }

        else {
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    } catch (Exception e) {
        System.out.println("Something went wrong");
    }

}

From source file:tweetmining.MiningFunctions.java

/**
 * This method creates an instance of Miningfunctions based on your TwitterApss credentials.
 * You should as well check filepaths to put yours.
 * //from  ww w. j  a v a  2 s.  co m
 * @throws FileNotFoundException 
 */

public MiningFunctions() throws FileNotFoundException, IOException {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);

    tf = new TwitterFactory(configurationBuilder.build());

    twitter = tf.getInstance();

    File f = new File(fichero1);
    File f2 = new File(fichero2);
    File f3 = new File(fichero3);
    if (!f.exists())
        f.createNewFile();
    if (!f2.exists())
        f2.createNewFile();
    if (!f3.exists())
        f3.createNewFile();
    pw = new PrintWriter(new FileOutputStream(f, true));
    pw2 = new PrintWriter(new FileOutputStream(f2, true));
    pw3 = new PrintWriter(new FileOutputStream(f3, true));

    listener = new StatusListener() {
        public void onStatus(Status status) {
            if (status.getGeoLocation() != null) {
                cont++;
                System.out.println("Loc not null----" + cont);
                GeoLocation loc = status.getGeoLocation();
                pw.println(String.valueOf(loc.getLatitude()) + ";" + String.valueOf(loc.getLongitude()) + ";"
                        + status.getUser().getName());
                System.out.println(
                        loc.getLatitude() + " " + loc.getLongitude() + " " + status.getUser().getName());
            }
            pw2.println(status.getUser().getName() + "--->" + status.getText());
            try {
                CloseWriteAndOpen();
            } catch (FileNotFoundException ex) {
                java.util.logging.Logger.getLogger(MiningFunctions.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

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

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

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };
    configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
}

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 *///from  w w  w  .j a  v  a  2 s . c  o  m
public static void main(String[] args) throws Exception {

    ConfigurationBuilder configurtacion = new ConfigurationBuilder();
    configurtacion.setDebugEnabled(true).setOAuthConsumerKey("KdVOb7h8mqcjWIfkXXED2G6sJ")
            .setOAuthConsumerSecret("EXImfgfGCYIbWZIOSEeYVvaDE5oxwJZY7UIuwUusbyRWf2ds7l")
            .setOAuthAccessToken("785481406654722049-aRARaHgZujPZIdpYla4mVZIMMlvzJRb")
            .setOAuthAccessTokenSecret("YWWQwbFw8K7rxsnivwpBRZVoQlUhMYy7gOs7KUWOb8Rvy");
    Twitter twitter = new TwitterFactory(configurtacion.build()).getInstance();
    twitter.getUserTimeline();

    String hashtag = "#ElectionNight";
    Query busqueda = new Query(hashtag);
    int numeroTweets = 1500;
    long ultimo = Long.MAX_VALUE;
    ArrayList<Status> tweets = new ArrayList<Status>();

    while (tweets.size() < numeroTweets) {
        if (numeroTweets - tweets.size() > 255) {
            busqueda.setCount(255);
        } else {
            busqueda.setCount(numeroTweets - tweets.size());
        }
        try {
            QueryResult result = twitter.search(busqueda);
            tweets.addAll(result.getTweets());
            System.out.println("Generados " + tweets.size() + " tweets" + "\n");
            for (Status t : tweets) {
                if (t.getId() < ultimo) {
                    ultimo = t.getId();
                }
                System.out.println("Generados " + tweets.size() + " tweets" + "\n");

            }

        } catch (TwitterException excepcion) {
            System.out.println("Sin conexin " + excepcion);
        }
        ;
        busqueda.setMaxId(ultimo - 1);
    }

    // guardamos los datos
    java.util.Date fecha = new Date();
    int hora = fecha.getHours();
    int minuto = fecha.getMinutes();
    System.out.println();
    String nombre = "Datos_" + hashtag + " " + hora + " " + minuto + ".txt";
    File f = new File(nombre);
    FileWriter fw = new FileWriter(f);
    BufferedWriter bw = new BufferedWriter(fw);

    System.out.println("identificador\tUsuario\ttweet\n");
    for (int i = 0; i < tweets.size(); i++) {
        Status estadoTweet = (Status) tweets.get(i);

        GeoLocation loc = estadoTweet.getGeoLocation();
        String user = estadoTweet.getUser().getScreenName();
        String msg = estadoTweet.getText();
        Boolean sensitive = estadoTweet.isPossiblySensitive();
        int fav = estadoTweet.getFavoriteCount();

        System.out.println("Id: " + i + "| User: " + user + "| Texto: " + msg + "| SentimientoPositivo: "
                + sensitive + "$\n");
        int id = i + 1;
        bw.append(msg + " | " + sensitive + ";");
        bw.newLine();

    }
    bw.close();
}

From source file:twit.TwitterConnector.java

/**
 * Default konstruktor//from  w  ww  . j  a  v a2s . com
 */
public TwitterConnector() {
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("EGisMj2osHyIrjSzFAOez9xPh")
            .setOAuthConsumerSecret("NvuqjYKYxUiYonAYbnnYLk3gJanf229nmAGXhV3YBsJewx2JJa")
            .setOAuthAccessToken("1675728624-aayjWcvZq7ESXsAlX8LuqOdSbN06QKlTMLN38Cp")
            .setOAuthAccessTokenSecret("34XQ2OBsDmYzbecH4Cz8gwtSA0BgejqxSXzVHiPsvVX9B");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

From source file:twitfeedbot.BotherSomeoneServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Twitter twit;// ww w  .j  ava 2  s .  com
    StringBuilder builder = new StringBuilder();
    User victim = null;
    long cursor = -1;
    long[] friendIDs, victimIDs;
    Random r = new Random();

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();

        Trends t = twit.getPlaceTrends(1); //global trends
        friendIDs = twit.getFollowersIDs(twit.getId(), cursor).getIDs();
        if (friendIDs.length == 0)
            resp.getWriter().println("Cannot find any followers to bother");
        else {
            victimIDs = twit.getFollowersIDs(friendIDs[r.nextInt(friendIDs.length)], cursor).getIDs();
            if (victimIDs.length == 0)
                resp.getWriter().println("Cannot find any followers to bother");
            else {
                victim = twit.showUser(victimIDs[r.nextInt(victimIDs.length)]);
                builder.append("@" + victim.getScreenName()).append(" ");
                //Append Wordnik example sentence
                builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                if (builder.length() > 140) //Tweets are maximum 140 characters
                {
                    if (builder.lastIndexOf(";", 110) > 0)
                        builder.setLength(builder.lastIndexOf(";", 110));
                    else if (builder.lastIndexOf(":", 110) > 0)
                        builder.setLength(builder.lastIndexOf(":", 110));
                    else if (builder.lastIndexOf(",", 110) > 0)
                        builder.setLength(builder.lastIndexOf(",", 110));
                    else
                        builder.setLength(110);
                }
                builder.append(" " + t.getTrends()[r.nextInt(t.getTrends().length)].getName());

                if (builder.length() > 140)
                    builder.setLength(140); //Tweets are limited to 140 characters

                twit.updateStatus(builder.toString());
                resp.getWriter().println("Tweet posted: " + builder.toString() + "<br>");
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}