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:uta.ak.CollectTweets.java

public void collectTweetsByKeyWords(String keyWords, String sinceDate, String untilDate, String tag) {
    try {//from w  w  w .j  a  v a2 s  .c om

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

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

        Query query = new Query(keyWords);
        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();
        }

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

From source file:util.UtilConfig.java

public static Twitter getTwitterInstance() {
    if (twitter == null) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
                .setOAuthAccessToken(ACCESS_TOKEN).setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
    }/* ww  w .j a  va2s.  c  o m*/
    return twitter;
}

From source file:views.MeetingRoomPanel.java

public void initTimeline() {
    timelineFrame = new JFrame("@SIM_IST Timeline");

    timelineFrame.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    timelineTweets = new JTextArea();
    Font font = new Font("Gotham Narrow", Font.BOLD, 12);
    timelineTweets.setFont(font);//from w  ww . j a va2 s .c  o m
    timelineTweets.setEditable(false);
    timelineScrollPane = new JScrollPane(timelineTweets);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.ipady = 200;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    timelineFrame.add(timelineScrollPane, c);

    KeyReader keys = new KeyReader();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(keys.getConsumerKey())
            .setOAuthConsumerSecret(keys.getConsumerSecret()).setOAuthAccessToken(keys.getAccessToken())
            .setOAuthAccessTokenSecret(keys.getAccessTokenSecret());
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    try {
        System.out.println("timeline retreval worked");

        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
            timelineTweets
                    .append("@" + status.getUser().getScreenName() + " : " + status.getText() + "\n" + "\n");
            timelineTweets.setLineWrap(true);
            timelineTweets.setWrapStyleWord(true);
            timelineTweets.setCaretPosition(0);
            System.out.println("@" + status.getUser().getName() + " : " + status.getText());
        }

    } catch (TwitterException te) {
        System.out.print("timeline retreval failed");
        te.printStackTrace();
    }

    timelineFrame.pack();
    timelineFrame.setSize(600, 300);
    timelineFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    timelineFrame.setLocationRelativeTo(null);
    timelineFrame.setVisible(true);
}

From source file:wap.twitter.model.TwitterUtility.java

public List<Tweet> getTweets(String news) {
    TwitterFactory tf = config();
    Twitter twitter = tf.getInstance();
    try {//from  ww  w.ja va 2s .  c om
        List<Tweet> tws = new ArrayList<Tweet>();
        int i = 0;
        Query query = new Query("#" + news);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                Tweet tw = new Tweet();
                if (i == 8) {
                    break;
                } else {
                    tw.setTitle(news);
                    tw.setUser(tweet.getUser().getScreenName());
                    tw.setUrl(tweet.getSource());
                    tw.setImage(tweet.getUser().getProfileImageURL());
                    tw.setBody(tweet.getText());
                    tw.setSource(tweet.getSource());
                    tw.setId(tweet.getId() + "");
                    i++;
                }
                System.out.println("******************* " + tweet.getGeoLocation());
                tws.add(tw);
            }
        } while ((query = result.nextQuery()) != null);
        return tws;
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    return null;
}

From source file:wap.twitter.model.TwitterUtility.java

public List<Trend> getTrends(GeoLocation loc) throws TwitterException {
    TwitterFactory tf = config();
    Twitter twitter = tf.getInstance();
    List<Trend> tds = new ArrayList<Trend>();
    ResponseList<Location> locations;
    locations = twitter.getClosestTrends(loc);
    for (Location location : locations) {
        Trends trends = twitter.getPlaceTrends(location.getWoeid());
        for (int i = 0; i < trends.getTrends().length; i++) {
            if (i == 10) {
                break;
            }/*  ww w.j a  v  a  2 s  .  c  o  m*/
            tds.add(trends.getTrends()[i]);
        }
    }
    return tds;
}

From source file:wap.twitter.model.TwitterUtility.java

private static Integer getTrendLocationId(String locationName) {

    int idTrendLocation = 0;

    try {//from w  ww .j a va 2  s .  c  o m

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("yourConsumerKey")
                .setOAuthConsumerSecret("yourConsumerSecret").setOAuthAccessToken("yourOauthToken")
                .setOAuthAccessTokenSecret("yourOauthTokenSecret");

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

        ResponseList<Location> locations;
        locations = twitter.getAvailableTrends();

        for (Location location : locations) {
            if (location.getName().toLowerCase().equals(locationName.toLowerCase())) {
                idTrendLocation = location.getWoeid();
                break;
            }
        }

        if (idTrendLocation > 0) {
            return idTrendLocation;
        }

        return null;

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get trends: " + te.getMessage());
        return null;
    }

}

From source file:WebApp.TwitterConsumer.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    OAuthConsumer consumer = null;/* ww  w .j av  a  2  s . c o  m*/
    OAuthAccessor accessor = null;
    try {
        consumer = CookieConsumer.getConsumer("twitter", getServletContext());
        accessor = CookieConsumer.getAccessor(request, response, consumer);

        String TWITTER_CONSUMER_KEY = consumer.consumerKey;
        String TWITTER_SECRET_KEY = consumer.consumerSecret;
        String TWITTER_ACCESS_TOKEN = accessor.accessToken;
        String TWITTER_ACCESS_TOKEN_SECRET = accessor.tokenSecret;
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
                .setOAuthConsumerSecret(TWITTER_SECRET_KEY).setOAuthAccessToken(TWITTER_ACCESS_TOKEN)
                .setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET);
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang=\"es\"><head>");
        out.println("<meta charset=\"UTF-8\">");
        out.println(
                "   <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>\n"
                        + "   <link rel=\"stylesheet\" href=\"css/style.css\">\n"
                        + "   <link rel=\"stylesheet\" href=\"css/bootstrap.css\">");
        out.println("<link rel=\"stylesheet\" href=\"css/flat-ui.css\">\n");
        //Query query = new Query("Dom2D");
        //QueryResult result;
        //do {
        //result = twitter.
        out.println("<body><header>\n" + "      <img src =\"Stalker.jpg \" width = 800 >\n" + "      <br>\n"
                + "      <br>\n" + "   </header>\n" + "   <section style=\"height: auto;\">\n"
                //+ "      <p> \n"
                //+ "          <input id=\"user\" type=\"text\" placeholder=\"Nombre de usuario\"/>"
                //+ "      </p>\n"
                + "      <h4 style=\"font-family:Comic Sans MS\">Timeline</h4>\n");
        List<Status> tweets = twitter.getUserTimeline();
        tweets.stream().forEach((tweet) -> {
            out.println("      <div class=\"tweet\">\n" + "         <div class=\"info\">\n"
                    + "            <p class=\"user\">\n" + "               <span class=\"name\">"
                    + tweet.getUser().getName() + "</span>\n" + "               <span class=\"username\">"
                    + tweet.getUser().getScreenName() + "</span>\n" + "               <span class=\"date\">"
                    + tweet.getCreatedAt() + "</span>\n" + "            </p>\n"
                    + "            <p class=\"text\">" + tweet.getText() + "</p>\n" + "         </div>\n"
                    + "      </div>\n");
        });
        out.println("   </section>\n" + "   <footer>\n"
                + "         <a href = \"https://www.facebook.com/\">Desarrolladores</a>\n"
                + "<a href=\"Reset\">Logout</a>" + "   </footer></body>");
        out.println("</html>");
        //} while ((query = result.nextQuery()) != null);
    } catch (Exception e) {
        CookieConsumer.handleException(e, request, response, consumer);
    }
}

From source file:wedt.project.MainWindow.java

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
    statusLabel.setText("Trwa wyszukiwanie...");
    lockUI();//w w w .j a v a2 s .c  om
    SwingWorker<List<Status>, Void> worker = new SwingWorker<List<Status>, Void>() {

        @Override
        protected List<Status> doInBackground() throws Exception {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey("PG0vtiQ73sbKKCfp9JfqyQ")
                    .setOAuthConsumerSecret("ITCkTQiqCh3aVZexXentwnwCJooVpUOcpkIENPKowI")
                    .setOAuthAccessToken("89783194-z0J1KLudg6MFMhhysKmL29zB5wBjxfxWUboAh6lAI")
                    .setOAuthAccessTokenSecret("ytOdt7t8P1OrmAI2ZCRoX30ZC3eLcDSgPY8gOa6FCwQ");
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();

            try {
                Query query = new Query(searchField.getText());
                query.setCount(10);
                query.setLang("en");
                if (checkBoxLatest.isSelected() && checkBoxPopular.isSelected())
                    query.setResultType(Query.ResultType.mixed);
                else if (checkBoxLatest.isSelected())
                    query.setResultType(Query.ResultType.recent);
                else if (checkBoxPopular.isSelected())
                    query.setResultType(Query.ResultType.popular);

                QueryResult result = twitter.search(query);
                return result.getTweets();

            } catch (TwitterException e) {
                statusLabel.setText("Wyszukiwanie nie powiodlo sie");
                e.printStackTrace();
                //System.out.println("Failed to search tweets: " + te.getMessage());
                JOptionPane.showMessageDialog(null, e.getMessage(), "Blad pobierania wynikow wyszukiwania",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            return null;
        }

        @Override
        protected void done() {
            try {
                List<Status> tweets = get();
                listModel = new DefaultListModel();
                tweetsList.setModel(listModel);
                tweets.stream().forEach((tweet) -> {
                    listModel.addElement(tweet.getText());
                });
                statusLabel.setText("Gotowe");
            } catch (Exception ex) {
                ex.printStackTrace();
                statusLabel.setText("Wyszukiwanie nie powiodlo sie");
            }
            unlockUI();
        }
    };
    worker.execute();
}

From source file:wise.TwitterUtils.java

public ArrayList<CheckinObject> dataList(String cityCode, String selectedDate, String maxTweetParam,
        String topTweetParam) throws IOException, JSONException, ParseException {
    ArrayList<CheckinObject> checkinList = new ArrayList<>();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.CONSUMER_KEY)
            .setOAuthConsumerSecret(Constants.CONSUMER_SECRET).setOAuthAccessToken(Constants.TOKEN)
            .setOAuthAccessTokenSecret(Constants.TOKEN_SECRET);

    Integer maxTweet = Integer.parseInt(maxTweetParam);
    Integer topTweet = Integer.parseInt(topTweetParam);

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

    DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);

    Date startDate = format.parse(selectedDate);

    Calendar c = Calendar.getInstance();
    c.setTime(startDate);//from   w  w  w  .  j ava2s.com
    c.add(Calendar.DATE, 1);
    Date endDate = c.getTime();

    Query query = SetQueryString(cityCode, startDate, endDate);

    QueryResult result = null;
    try {
        while (query != null && checkinList.size() <= maxTweet) {
            result = twitter.search(query);
            if (result != null) {
                for (Status status : result.getTweets()) {

                    for (URLEntity urlEntity : status.getURLEntities()) {
                        String urlCheckinId = urlEntity.getExpandedURL()
                                .substring(urlEntity.getExpandedURL().lastIndexOf("/") + 1);
                        GeoLocation geo = status.getGeoLocation();

                        CheckinObject checkin = new CheckinObject();
                        checkin.CheckinId = urlCheckinId;
                        checkin.Count = 1;//status.getRetweetCount() + status.getFavoriteCount() + 1;
                        checkin.Latitude = geo.getLatitude();
                        checkin.Longitude = geo.getLongitude();

                        if (!checkin.containsSameCoordinates(checkinList, checkin.Latitude,
                                checkin.Longitude)) {
                            checkinList.add(checkin);
                        } else {
                            int indexOfCheckinId = checkin.getIndexByCoordinates(checkinList, checkin.Latitude,
                                    checkin.Longitude);
                            checkinList.get(indexOfCheckinId).setCheckinCount(checkin.Count);
                            checkinList.get(indexOfCheckinId).setReplacementCheckinId(checkin.CheckinId);
                        }
                    }
                }

                query = result.nextQuery();
            } else {
                query = null;
            }
        }

    } catch (TwitterException e) {
    }

    Collections.sort(checkinList, new CountComparator());

    if (checkinList.size() > topTweet) {
        checkinList.subList(topTweet, checkinList.size()).clear(); // get top x
    }

    FourSquareCheckin fsq = new FourSquareCheckin();

    for (CheckinObject checkin : checkinList) {
        fsq = getVenueInfo(checkin);
        checkin.LocationName = fsq.VenueName;
        checkin.Image = fsq.VenueImage;
    }

    return checkinList;
}

From source file:wordgame.WordGame.java

public static void initGame(String file) throws FileNotFoundException {
    Scanner s = new Scanner(new File(file)); //open the file
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true) //populate the twitter details with the proper API informatin
            .setOAuthConsumerKey(s.nextLine()).setOAuthConsumerSecret(s.nextLine())
            .setOAuthAccessToken(s.nextLine()).setOAuthAccessTokenSecret(s.nextLine());
    TwitterFactory tf = new TwitterFactory(cb.build());
    t = tf.getInstance();
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 731852008030916608L }); //Track our tweets
    twitterStream.addListener(new MentionListener()); //Set the listener to our MentionListener class
    twitterStream.filter(filterQuery); //begin listening
}