Example usage for twitter4j TwitterFactory getInstance

List of usage examples for twitter4j TwitterFactory getInstance

Introduction

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

Prototype

public Twitter getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:twit.TwitterConnector.java

/**
 * Default konstruktor//from w  ww  . j  av 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:twitah.Metodos.java

/**
 * Setting up twitter permissions to send and receive
 *//*from  w w w  .  j a va 2 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: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;/*  ww  w  . j  a v  a  2 s  . co m*/
    try {
        stat = tw.updateStatus(ch);
        return "Tweet ajout";
        //System.out.println("twitter updated");
    } catch (TwitterException ex) {
        ex.printStackTrace();
        return "Tweet non ajout";
    }
}

From source file:twitter.login.java

private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
    try {/*from  w ww  .  ja  v a2s .com*/
        //Source Code untuk Login ke situs Twitter dengan memakai
        //ConsumerKey,ConsumerSecret,AccessToken,dan AccessSecret
        //datFo Data=new datFo(txtConsumerKey.getText(),arrayToString(txtConsumerSecret.getPassword()),txtAccessToken.getText(),arrayToString(txtAccessSecret.getPassword()));
        datFo Data = new datFo();
        Data.setConsumerKey(txtConsumerKey.getText());
        Data.setConsumerSecret(arrayToString(txtConsumerSecret.getPassword()));
        Data.setAccessKey(txtAccessToken.getText());
        Data.setAccessSecret(arrayToString(txtAccessSecret.getPassword()));
        ConfigurationBuilder cf = new ConfigurationBuilder();
        cf.setDebugEnabled(true).setOAuthConsumerKey(Data.getConsumerKey())
                .setOAuthConsumerSecret(Data.getConsumerSecret()).setOAuthAccessToken(Data.getAccessKey())
                .setOAuthAccessTokenSecret(Data.getAccessSecret());
        TwitterFactory tf = new TwitterFactory(cf.build());
        twitter4j.Twitter tw = tf.getInstance();
        Home home = new Home(tw);
        home.setVisible(true);
        home.setAlwaysOnTop(true);
        this.setVisible(false);
        this.dispose();
    } catch (TwitterException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this, "diCheck lagi bro Key nya\n Atau Check Koneksi Bro", "Error",
                JOptionPane.OK_OPTION);
    }

}

From source file:twitter.metrics.TwitterMetrics.java

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

    try {

        /*Parte que guarda en un archivo*/
        // Se crea el libro
        HSSFWorkbook libro = new HSSFWorkbook();

        // Se crea una hoja dentro del libro
        HSSFSheet hoja = libro.createSheet();

        // Se crea una fila dentro de la hoja
        HSSFRow fila = hoja.createRow(0);

        // Se crea una celda dentro de la fila
        HSSFCell celda = fila.createCell(1);

        // Se crea el contenido de la celda y se mete en ella.
        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Twitter");
        celda.setCellValue(texto);
        /************************************/

        /*Conexion con Mongo DB*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoTwitter");

        DBCollection datos = db.getCollection("Datos");

        /***********************/

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);

        cb.setOAuthConsumerKey("TobUISZXWUhDda04ZBtFGQ");
        cb.setOAuthConsumerSecret("7xurVN3iP6VDcBfKdFJxVuNsJjExERFYNmQIDgtg");

        cb.setOAuthAccessToken("849956971-GJBiORhLIuWK4i3MJ2YCd4vidh65N1GzPIb6duXk");
        cb.setOAuthAccessTokenSecret("4MJgPS9grxVuKbczrPCdSjNnumhcWs7t7OLy2F4kkpOdu");

        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        User u = twitter.showUser("Pringles");

        System.out.println("Nombre: " + u.getName());
        System.out.println("Seguidores: " + u.getFollowersCount());
        System.out.println("Favoritos: " + u.getFavouritesCount());
        System.out.println("Seguidos: " + u.getFriendsCount());
        System.out.println("Ubicacion: " + u.getLocation());
        System.out.println("Descripcin: " + u.getDescription());
        System.out.println("");

        fila = hoja.createRow(1);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Nombre:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getName()));

        fila = hoja.createRow(2);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidores:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFollowersCount() + ""));

        fila = hoja.createRow(3);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Favoritos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFavouritesCount() + ""));

        fila = hoja.createRow(4);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFriendsCount() + ""));

        fila = hoja.createRow(5);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Ubicacin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getLocation() + ""));

        fila = hoja.createRow(6);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Descripcin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getDescription() + ""));

        fila = hoja.createRow(7);
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweets!!!"));

        fila = hoja.createRow(9);
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("IdTweet"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Cuenta"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweet"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Geolocation"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("Place"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("Retweets"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Favoritos"));

        Paging paging = new Paging(1, 1000);
        ResponseList<Status> s = twitter.getUserTimeline(u.getId(), paging);
        int i = 0;
        int filaNum = 10;
        for (Status st : s) {

            BasicDBObject obj = new BasicDBObject();

            obj.append("idTweet", s.get(i).getId() + "");
            obj.append("Cuenta", u.getName());
            obj.append("Tweet", s.get(i).getText());
            obj.append("Geolocation", s.get(i).getGeoLocation());
            obj.append("Place", s.get(i).getPlace());
            obj.append("Reteews", s.get(i).getRetweetCount());
            obj.append("Favoritos", s.get(i).getFavoriteCount());

            fila = hoja.createRow(filaNum);
            celda = fila.createCell(1);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getId() + ""));
            celda = fila.createCell(2);
            celda.setCellValue(new HSSFRichTextString(u.getName()));
            celda = fila.createCell(3);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getText()));
            celda = fila.createCell(4);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getGeoLocation() + ""));
            celda = fila.createCell(5);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getPlace() + ""));
            celda = fila.createCell(6);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getRetweetCount() + ""));
            celda = fila.createCell(7);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getFavoriteCount() + ""));

            i++;
            filaNum++;

            datos.insert(obj);
        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_Twitter.xls");
        libro.write(elFichero);
        elFichero.close();

        /********************************/

        System.out.println(i);

        //User usuario = twitter.showUser("@aaron21007");
        //    List<Status> statuses = twitter.getHomeTimeline();
        //    System.out.println("Showing home timeline.");
        //    for (Status status : statuses) {
        //        System.out.println(status.getUser().getName() + ":" +
        //                           status.getText());
        //    }

        //        Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance();
        //        
        //          List<String> listaTweets = new ArrayList();
        //          List<Long> ListaRettewts = new ArrayList();
        //          List<Integer> ListaFavoritos = new ArrayList();
        //          List<Integer> ListaMenciones = new ArrayList();
        //          List<Date> ListaFecha = new ArrayList();
        //          List<Long> ListaIds = new ArrayList();
        ////
        //          User usuario = unauthenticatedTwitter.showUser("@aaron21007");
        //          List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe();
        //          List<Status> favoritos = unauthenticatedTwitter.getFavorites();
        //          Paging paging = new Paging(1, 1000);
        //          ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(), paging);
        //          
        //          
        //          for (Status sta : statuses) {
        //              
        //            ListaIds.add(Long.valueOf(sta.getId()));
        //            listaTweets.add(sta.getText());
        //            ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + "")));
        //            ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length));
        //            ListaFecha.add(sta.getCreatedAt());
        //            ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount()));
        //              System.out.println(sta.getText());
        //              
        //          }
        //          
        //          
        //        
        //       
        //        
    } catch (Exception e) {
        System.err.println("Fallo................." + e);
    }
}

From source file:Twitter.Twitter.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("8e27WtNVhuIOt1EAyAdqV51Yk")
            .setOAuthConsumerSecret("dsgPVnwV53UwiPuAA5r0CbNykubjxmGHe7csf0Y1zGOV8KVe0r")
            .setOAuthAccessToken("4143520821-ZgULKYSyMRbrXytCvkmdGeXbd7L0bx4NOiM4fKC")
            .setOAuthAccessTokenSecret("jju1OwDCromI9r0QK1gU18MrFOkw1jsKFCQtXjFbv5G8A");

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

    twitter4j.Twitter tw = tf.getInstance();

    Status stat;//from w w  w . j  a v  a2s .  co m
    try {
        stat = tw.updateStatus(tweet.getText());

        //System.out.println("twitter updated");
    } catch (TwitterException ex) {
        Logger.getLogger(Twitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:TwitterAnalytics.TwitterAPI.java

private TwitterAPI() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumeSecretKey);
    builder.setOAuthAccessToken(accessToken);
    builder.setOAuthAccessTokenSecret(accessSecretToken);
    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);

    twitter = factory.getInstance();
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(// w ww  .  j  a v a2s  .  co m
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twitterapp.TwitterApp.java

public static void streamTweets() throws TwitterException {
    /*getting the trends */
    ConfigurationBuilder cb2 = new ConfigurationBuilder();

    cb2.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge");

    TwitterFactory tf = new TwitterFactory(cb2.build());
    Twitter twitter = tf.getInstance();
    Trends trends = twitter.getPlaceTrends(23424977);

    String top_trend = "";
    int top = 0;//from  ww w. j  a  v  a 2s .com
    for (Trend trend : trends.getTrends()) {
        if (top < 1) {
            top_trend = trend.getName();
            top++;
        }
    }

    System.out.println("top trend : " + top_trend);

    //Using the Streaming API to get real time tweets based on the trending topics as keywords
    /* configurating twiter4j */

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge")
            .setJSONStoreEnabled(true);
    /* end of configuration */

    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("myTweetdb2");
    MongoCollection<Document> collection = database.getCollection("myTweetCol5");
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {

            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            Document doc = Document.parse(rawJSON);

            collection.insertOne(doc);

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

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

    // twitterStream.sample();
    twitterStream.addListener(listener);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { top_trend };
    fq.track(keywords);
    twitterStream.filter(fq);
}

From source file:TwitterDownload.TwitterHandler.java

public TwitterHandler() {
    try {/*from  ww w  .  j  a  va  2  s.  com*/
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET_KEY)
                .setOAuthAccessToken(null).setOAuthAccessTokenSecret(null);
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
    } catch (IllegalStateException ex) {
        String s = ex.toString();
    } catch (Exception ex) {
        String s = ex.toString();
    }
}