Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

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();/*from ww  w .  j  a  v a  2s.c o m*/

    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();//ww  w  . j  av a2 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  w  ww.  jav a  2 s .c  om*/
 * @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.  jav  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 ww w  .  java2  s  .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:twitah.Metodos.java

/**
 * Setting up twitter permissions to send and receive
 *//* w  w  w.  j  a  v a2 s .c o m*/
public static void conecta() {
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("yFIIR0UR9q2HNaFEkQMUTVjVu");
    cb.setOAuthConsumerSecret("LVTz8Hpp9Ub6gNxaz4fwIqXhj92b44KZ8cnwoTwuVILpNuB6z1");
    cb.setOAuthAccessToken("285664852-eeZj0GBgkMsFwnLKLj4xfowdVXujqdvu174lrx8i");
    cb.setOAuthAccessTokenSecret("svAHdGjn3W7BXas3stbDoDJm4oy0iCndTCFvlr1A9c7HZ");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter 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;/*from w  w w.j a v  a2 s  .co  m*/
    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>");
    }
}

From source file:twitfeedbot.RespondServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ResponseList<Status> mentions;
    Twitter twit;/*  www . j a v a 2 s.c o  m*/
    StringBuilder builder = new StringBuilder();
    long lastPostId = 0;

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity lastPostIdEntity;

    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();
        mentions = twit.getMentionsTimeline();

        lastPostIdEntity = datastore.get(KeyFactory.createKey("lastPostIDEntity", "ID"));
        lastPostId = Long.parseLong(lastPostIdEntity.getProperty("lastPostID").toString());

        if (mentions.size() == 0 || mentions.get(0).getId() == lastPostId)
            resp.getWriter().println("No mentions so far...<br>");
        else {
            resp.getWriter().println("Responding to mentions...<br>");
            for (Status mention : mentions) {
                builder.setLength(0); // Clear the String Builder
                if (lastPostId < mention.getId()) {
                    //Figure out how to like a reply with certain words (best fuck etc)
                    if (mention.getUser().getId() == twit.getId())
                        ;//don't respond to myself
                    else if (mention.isRetweeted())
                        ; //don't respond to retweet
                    else if (mention.getText().toLowerCase().contains("bye")) // Say goodbye
                    {
                        builder.setLength(0); // Clear the String Builder 
                        builder.append("@").append(mention.getUser().getScreenName()).append(" Ok. Bye");
                    } else {
                        builder.setLength(0); // Clear the String Builder
                        builder.append("@").append(mention.getUser().getScreenName());
                        builder.append(" ");

                        //Append Wordnik example sentence
                        builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                        if (builder.length() > 140) {
                            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);
                        }
                    }
                    twit.updateStatus(builder.toString());
                    resp.getWriter().println("Reply posted: " + builder.toString() + "<br>");
                    builder.delete(0, builder.length()); //Clear the builder
                }
            }
            //Save last post ID
            lastPostIdEntity.setProperty("lastPostID", (Long.toString(mentions.get(0).getId())));
            datastore.put(lastPostIdEntity);
        }
    } 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 (EntityNotFoundException e) {
        resp.getWriter().println("lastPostID not found. Creating...<br>");
        lastPostIdEntity = new Entity("lastPostIDEntity", "ID");
        //lastPostIdEntity.setProperty("lastPostID", 0);
        lastPostIdEntity.setProperty("lastPostID", "883352596160946176");
        datastore.put(lastPostIdEntity);

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

From source file:twitfeedbot.UpdateStatusServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    StringBuilder builder = new StringBuilder(140);
    GetFeed feed = new GetFeed(feedsFile);
    Random r = new Random();

    resp.setContentType("text/plain; charset=UTF-8");

    try {//from   ww  w .  j  a v a  2  s .  co m
        resp.getWriter().println("Updating status...");
        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();

        //Append feed title
        try {
            builder.append(feed.title()).append(separator[(r.nextInt(separator.length))]);
        } catch (FeedException e) {
            resp.getWriter().println("Problem with RSS Feed <br> <pre>");
            e.printStackTrace(resp.getWriter());
        }

        //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);
        }
        //Add a global trend
        builder.append(
                " " + twit.getPlaceTrends(1).getTrends()[r.nextInt(twit.getPlaceTrends(1).getTrends().length)]
                        .getName());
        // Make up a trend by combining two words
        builder.append(" #" + WordsApi.randomWord().getWord() + WordsApi.randomWord().getWord());

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

        twit.updateStatus(builder.toString());
        resp.getWriter().println("Tweet posted: " + builder.toString());
    } 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>");
    }
}

From source file:Twitter.ajouterTweet.java

public String tweeter(String ch) {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("JFpW0Gry4Wwst4jRT8ViuFcHz")
            .setOAuthConsumerSecret("dre4sGP8yjqRil59yCfHMWzgGzvM47AbddudsNaLaTWtFSdN8u")
            .setOAuthAccessToken("4174408527-H22us84yvMouxO9PgHKxfSswamhzreT3VOeeMYS")
            .setOAuthAccessTokenSecret("u5vlzN32AUv6UPLiblqQzs8vsnasMp0oZpiEaeRfVXRdH");

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

    twitter4j.Twitter tw = tf.getInstance();
    Status stat;/*from  w  w w.  j  a v  a  2  s  .  c  o m*/
    try {
        stat = tw.updateStatus(ch);
        return "Tweet ajout";
        //System.out.println("twitter updated");
    } catch (TwitterException ex) {
        ex.printStackTrace();
        return "Tweet non ajout";
    }
}