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:twitterlab.TwitterLab.java

/**
 * @param args the command line arguments
 *///  w w w  .j  a va2 s.c o  m
public static void main(String[] args) {
    // TODO code application logic here
    Users = new ArrayList();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("yBSAPlE6wiAQU6CyIiXHSapwN");
    cb.setOAuthConsumerSecret("3CjbEkYyIZvNZ07KYpC55v9vpqxoNmMs1IkC48Wqr5tKXjUnZk");
    cb.setOAuthAccessToken("858371720-0RASIMJeaMbWr2YPmCPyh5OgCP6Kesgz0WvdsLz7");
    cb.setOAuthAccessTokenSecret("cfi5JDGLTUOKHNj7yFIdivg0Hr1bCml3VlQXj5XCOyoFr");

    try {
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter tw = tf.getInstance();
        IDs ids = tw.getFriendsIDs(-1);
        long[] ID;
        if (ids.getIDs().length > 10) {
            ID = new long[10];
            System.arraycopy(ids.getIDs(), 0, ID, 0, 10);
        } else {
            ID = ids.getIDs();
        }
        ResponseList<User> Friends = tw.lookupUsers(ID);
        User[] A = new User[10];
        if (Friends.toArray().length > 0) {
            Users.add(new ArrayList(Arrays.asList(Friends.toArray(A))));
        }
        for (int i = 0; i < ID.length; i++) {
            IDs idsFriend = tw.getFriendsIDs(ID[i], -1);
            long[] IDfriend;
            if (idsFriend.getIDs().length > 10) {
                IDfriend = new long[10];
                System.arraycopy(idsFriend.getIDs(), 0, IDfriend, 0, 10);
            } else {
                IDfriend = idsFriend.getIDs();
            }
            ResponseList<User> FriendsFriend = tw.lookupUsers(IDfriend);
            A = new User[10];
            if (FriendsFriend.toArray().length > 0) {
                Users.add(new ArrayList(Arrays.asList(FriendsFriend.toArray(A))));
            }
            //System.out.println("Sleep?");
            TimeUnit.SECONDS.sleep(60);
        }

        for (int i = 0; i < Users.size(); i++) {
            for (int j = 0; j < Users.get(0).size(); j++) {
                System.out.println(Users.get(i).get(j).getScreenName());
            }
        }

    } catch (Exception e) {
        // Thread.currentThread().interrupt();
        e.printStackTrace();
    }

}

From source file:twittermongodbapp.TwitterMongoDBApp.java

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

    ConfigurationBuilder cf1 = new ConfigurationBuilder();
    ConfigurationBuilder cf2 = new ConfigurationBuilder();
    init(cf1);// w  w  w  .j  av a 2s. c  o m
    init(cf2);

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("tweetsTest");

    TwitterFactory tf = new TwitterFactory(cf2.build());
    twitter4j.Twitter twitter = tf.getInstance();
    /*
            
     System.out.println("Select option :");
     System.out.println("Collect tweets from Greece: 1");
     System.out.println("Save these tweets: 2");
     System.out.println("Exit: 0");
      Scanner scanner = new Scanner(System.in);
     int input = scanner.nextInt();
     if(input==1){
     CollectTweets ct = new CollectTweets();
     ct.collectTweets(db,cf1,twitter);
     }else if(input==2){
     SaveTweets st = new SaveTweets();
     st.saveTweets(db,twitter);
     }else if (input==0){
     mongoClient.close(); 
     return ;
     }else{
      System.out.println("Select property");
      System.out.println("Select option");
     System.out.println("Collect 20 tweets from Greece: 1");
     System.out.println("Save these tweets: 2");
     System.out.println("Exit : 0");
     }
    */
    SaveTweets st = new SaveTweets();
    st.saveTweets(db, twitter);
}

From source file:TwitterPublisher.Connexions.TwitterInterface.java

/**
 * Publish the given message on twitter.
 * @param message//from  w  w  w  .j  a  v  a  2 s .  c om
 * @throws TwitterException 
 */
public static void publish(String message) throws TwitterException {

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer("vIZ097dCEeXqnYofk8N6qTw9E", "GdN2pVxNTHJNRBZltaeeCDSTRScQL1bjCzlIgDza2WVRGfZ5SC");
    twitter.setOAuthAccessToken(new AccessToken("795590633918464001-NpyvUY0OylVbLNznVvoG98M8pMIaajv",
            "z1xR0jyHBbUsDioW3T7LIAC9b3FgTyvaGxgMSiGGn9cjR"));
    twitter.updateStatus(message);
    System.out.println("Twitter message has been published");

}

From source file:twitterswingclient.TwitterClient.java

private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed
    // TODO add your handling code here:
    String consKey = "Your key";
    String consSecret = "Your secret";
    String accToken = "Your key";
    String accSecret = "Your secret";
    try {// w ww  .  ja  v  a2 s. co m

        TwitterFactory twitterFactory = new TwitterFactory();

        Twitter twitter = twitterFactory.getInstance();

        twitter.setOAuthConsumer(consKey, consSecret);

        twitter.setOAuthAccessToken(new AccessToken(accToken, accSecret));

        StatusUpdate statusUpdate = new StatusUpdate(status.getText());

        statusUpdate.setMedia("Feeling great",
                new URL("http://media3.giphy.com/media/el1tH0BzEWm4w/giphy.gif").openStream());

        Status stat = twitter.updateStatus(statusUpdate);

        textArea.append("status.toString() = " + stat.toString());
        textArea.append("status.getInReplyToScreenName() = " + stat.getInReplyToScreenName());
        textArea.append("status.getSource() = " + stat.getSource());
        textArea.append("status.getText() = " + stat.getText());
        textArea.append("status.getContributors() = " + Arrays.toString(stat.getContributors()));
        textArea.append("status.getCreatedAt() = " + stat.getCreatedAt());
        textArea.append("status.getCurrentUserRetweetId() = " + stat.getCurrentUserRetweetId());
        textArea.append("status.getGeoLocation() = " + stat.getGeoLocation());
        textArea.append("status.getId() = " + stat.getId());
        textArea.append("status.getInReplyToStatusId() = " + stat.getInReplyToStatusId());
        textArea.append("status.getInReplyToUserId() = " + stat.getInReplyToUserId());
        textArea.append("status.getPlace() = " + stat.getPlace());
        textArea.append("status.getRetweetCount() = " + stat.getRetweetCount());
        textArea.append("status.getRetweetedStatus() = " + stat.getRetweetedStatus());
        textArea.append("status.getUser() = " + stat.getUser());
        textArea.append("status.getAccessLevel() = " + stat.getAccessLevel());
        textArea.append("status.getHashtagEntities() = " + Arrays.toString(stat.getHashtagEntities()));
        textArea.append("status.getMediaEntities() = " + Arrays.toString(stat.getMediaEntities()));

        if (stat.getRateLimitStatus() != null) {
            textArea.append("status.getRateLimitStatus().getLimit() = " + stat.getRateLimitStatus().getLimit());
            textArea.append(
                    "status.getRateLimitStatus().getRemaining() = " + stat.getRateLimitStatus().getRemaining());
            textArea.append("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + stat.getRateLimitStatus().getResetTimeInSeconds());
            textArea.append("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + stat.getRateLimitStatus().getSecondsUntilReset());
            textArea.append("status.getRateLimitStatus().getRemainingHits() = "
                    + stat.getRateLimitStatus().getRemaining());
        }
        textArea.append("status.getURLEntities() = " + Arrays.toString(stat.getURLEntities()));
        textArea.append("status.getUserMentionEntities() = " + Arrays.toString(stat.getUserMentionEntities()));

    } catch (IOException ex) {
        textArea.append("IO Exception");
    } catch (TwitterException tw) {
        textArea.append("Twitter Exception");
    }
}

From source file:twittertestingagain.TwitterTesting.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException/*ww  w . ja va 2  s .c  o  m*/
 * @throws java.io.IOException
 */
public static void main(String[] args) throws TwitterException, IOException {

    /* ---------------------------Setting up twitter account authentication-------------------------------*/
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("YjICBJeNlnxAf3tFw7awLaCzS")
            .setOAuthConsumerSecret("8IfPzkr4opePnhCLLloKMP6X44IeNav0fLDrmtBrPbaHoxd1nO")
            .setOAuthAccessToken("4146680697-oOEPVezvvZ82vB7iP9HSbkoTG9ze9gH69XLrSCP")
            .setOAuthAccessTokenSecret("HZjsaabmVjeSkSX6vvVFdT3GWZek8xJ9RKfwaR57RDyEG");

    /* ---------------------------------File Writing Variables------------------------------------------------*/

    File outfile = new File("output.txt");
    FileWriter fwriter = new FileWriter(outfile);

    try (PrintWriter pWriter = new PrintWriter(fwriter)) {

        /*----------------------------------Search Parameters-------------------------------------*/

        String search = "chinese food";
        String lang = "en";
        /*------------------------End Search Parameters----------------------------------------*/

        int numTweets = 0;
        long maxID = -1;
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        try {

            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            //System.out.println(rateLimitStatus);
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

            /*System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
                searchTweetsRateLimit.getRemaining(),
                searchTweetsRateLimit.getLimit(),
                searchTweetsRateLimit.getSecondsUntilReset());
            */

            for (int queryNumber = 0; queryNumber < maxQueries; queryNumber++) {

                System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                pWriter.println("\n\n!!! Starting iteration #" + queryNumber + "\n\n");

                if (searchTweetsRateLimit.getRemaining() == 0) {
                    System.out.printf("!!! Sleeping for %d seconds due to rate limits\n",
                            searchTweetsRateLimit.getSecondsUntilReset());
                    Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                }
                //here is where we can send an object to the query
                Query query = new Query(search);
                query.setCount(tweetsPerQuery);
                query.resultType(Query.ResultType.recent);
                query.setLang(lang);

                if (maxID != -1) {
                    query.setMaxId(maxID - 1);
                }

                QueryResult result = twitter.search(query);

                if (result.getTweets().size() == 0) {
                    break;
                }

                for (Status s : result.getTweets()) {

                    numTweets++;

                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }

                    System.out.printf("On %s, @%-20s said: %s\n", s.getCreatedAt().toString(),
                            s.getUser().getScreenName(), cleanText(s.getText()));

                    pWriter.println("On " + s.getCreatedAt().toString() + " @" + s.getUser().getScreenName()
                            + " " + cleanText(s.getText()));

                }

                searchTweetsRateLimit = result.getRateLimitStatus();

            }

        }

        catch (Exception e) {

            System.out.println("Broken");

            e.printStackTrace();
        }
        System.out.printf("\n\nA total of %d tweets retrieved\n", numTweets);
        pWriter.println("\n\nA total of " + numTweets + " tweets retrieved\n\n");
        pWriter.close();

        /*while (result.hasNext()){
            numTweets += result.getCount();
        System.out.println(numTweets);
         for (Status status : result.getTweets()) {
             System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
         }  
         result.nextQuery();
        }
                   
                     
                 
                 
        /*
         QueryForm qf = new QueryForm();
           qf.show();
        */

    }

}

From source file:twitter_contornos.Metodos.java

/**
 * Introducir claves para que se conecte a tu cuenta de Twitter y puedas utilizar 
 * este programa sin errores.//from  w  w  w. ja  v  a 2s  .  c o  m
 * Los * representan donde tienes que introducir las claves.
 */
public void clave() {
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("LvDvh1O59uDWrShwe7kBUXPfG")
            .setOAuthConsumerSecret("r0xXqIZVjuSi11v0OAUCIJVjaunEUTfIsTw0HVAxgUyFyHDzoc")
            .setOAuthAccessToken("847339034858762240-vEg6mva8GnITk37oiJlA008xKFUA0M5")
            .setOAuthAccessTokenSecret("LnrfJbq0TkvGK2wMUVzDtb0oF4q49XhT78dLtS7IaQ9jF");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

From source file:twittterbot08.TwittterBot08.java

/**
 * @param consumerKey/*w  w  w  . ja va 2  s. co m*/
 * @param consumerSecret
 * @param accessToken
 * @param accessTokenSecret
 * @return 
 */

public Twitter intializeToken(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret) {

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessTokenSecret);
    Configuration configuration = configurationBuilder.build();

    if (configuration != null)
        System.out.println("Configuration is Authenticated!");

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

    return twitter;
}

From source file:uk.co.flax.ukmp.twitter.TwitterListManager.java

License:Apache License

@Override
public void start() throws Exception {
    Configuration authConfig = buildConfiguration();
    TwitterFactory factory = new TwitterFactory(authConfig);
    Twitter twitter = factory.getInstance();

    updateThread = new ListUpdateThread(twitter);
    updateThread.start();// ww w  .  ja  v  a  2s.c o m
}

From source file:uniandes.edu.twitterreader.TwitterApp.java

public TwitterApp() {

    // Twitter Configuration
    ConfigurationBuilder cf = new ConfigurationBuilder();
    cf.setDebugEnabled(true).setOAuthConsumerKey("Pjh11zSaQp7uI4Qe6HZrnXp5f")
            .setOAuthConsumerSecret("dCT2Z85JQ0B9FPafVrbEP26cC4dGduMkQeRT29YIU4Mhl8bhk0")
            .setOAuthAccessToken("105491840-OzLXnQyvNrpfm7pp6X0b6olTDWKKWmxvdhlQnA2a")
            .setOAuthAccessTokenSecret("edrCvTf2AOo7xIpuBwFNLY5GS0Dbx35KbFygMzs17hvrY");

    cf.setJSONStoreEnabled(true);/* w w w . ja  va2  s. c o  m*/

    TwitterFactory tf = new TwitterFactory(cf.build());
    twitter = tf.getInstance();

    // Mongo connection
    mongoDB = new MongoClient(DB_SERVER, DB_PORT).getDatabase(DB_NAME);
    if (mongoDB.getCollection(COLLECTION_NAME) == null) {
        mongoDB.createCollection(COLLECTION_NAME);
    }
    mongoCollection = mongoDB.getCollection(COLLECTION_NAME);

}

From source file:uta.ak.CollectTweets.java

public void collectTweetsByFileList(String sinceDate, String untilDate, String tag) {
    try {//from  w  w w  .  j a  va 2s.  c  o  m
        // The factory instance is re-useable and thread safe.
        System.out.println("Start to collect tweets from :");
        Set<String> mediaList = new HashSet<String>();
        Resource res = new ClassPathResource("new-social-meida-list.txt");
        //                File stopwords=res.getFile();
        //      File stopwords=new File("/Users/zhangcong/dev/corpus/StopWordTable2.txt");
        InputStreamReader isr = new InputStreamReader(res.getInputStream());
        //            File medias=new File(path);
        //            BufferedReader mdsreader = new BufferedReader(new FileReader(medias));
        BufferedReader mdsreader = new BufferedReader(isr);
        String tempString = mdsreader.readLine();
        while ((tempString = mdsreader.readLine()) != null) {
            System.out.println(tempString.toLowerCase());
            mediaList.add(tempString.toLowerCase());
        }

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3")
                .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj")
                .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf")
                .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        /*
        Connection con = null; //MYSQL
        Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
        con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
        System.out.println("connection yes");
                
        String insertSQL="INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) "
                        + "VALUES (NOW(), \"AK\", ?, ?, ?, ?)";
        PreparedStatement insertPS = con.prepareStatement(insertSQL);
        */

        //?usttmp??
        String restUrl = "http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (String mediastr : mediaList) {
            Query query = new Query("from:" + mediastr);
            query.setSince(sinceDate);
            query.setUntil(untilDate);
            query.setCount(100);
            query.setLang("en");

            QueryResult result = twitter.search(query);
            for (Status status : result.getTweets()) {
                System.out.println("@" + status.getUser().getScreenName() + " | "
                        + status.getCreatedAt().toString() + ":" + status.getText());
                System.out.println("Inserting the record into the table...");

                String formattedDate = format1.format(status.getCreatedAt());
                /*
                insertPS.setString (1, status.getUser().getScreenName());
                insertPS.setString (2, status.getText());
                insertPS.setString (3, tag);
                insertPS.setString (4, formattedDate);
                insertPS.addBatch();*/

                //                    if(null!=status.getText()){
                //                        break;
                //                    }

                String interfaceMsg = "<message> " + "    <title> "
                        + ((null != status.getUser().getScreenName()) ? status.getUser().getScreenName()
                                : "NO TITLE")
                        + "    </title> " + "    <text> " + StringEscapeUtils.escapeXml10(status.getText())
                        + "    </text> " + "    <textCreatetime> " + formattedDate + "    </textCreatetime> "
                        + "    <tag> " + tag + "    </tag> " + "</message>";

                //                    String restUrl="http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

                RestTemplate restTemplate = new RestTemplate();

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.TEXT_XML);
                headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
                //            headers.setContentLength();
                HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

                ResponseEntity<String> resresult = restTemplate.exchange(restUrl, HttpMethod.POST, entity,
                        String.class);

                System.out.println(resresult.getBody());
                if (resresult.getBody().contains("<result>failed</result>")) {
                    throw new RuntimeException("response message error");
                }

            }
        }

        //            System.out.println("Start to insert records...");
        //            insertPS.clearParameters();
        //            int[] results = insertPS.executeBatch();

    } catch (Exception te) {
        te.printStackTrace();
        System.out.println("Failed: " + te.getMessage());
        System.exit(-1);
    }
}