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:TwitterSend2.java

License:BEER-WARE LICENSE

public void twitterConfiguration() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("2XYWWfo3BHdF17nVF6Nyg");
    cb.setOAuthConsumerSecret("XQtpXlLu8uJWgyI3XVEMHcCHCSwar9KbTnTWuXJmXk");
    cb.setOAuthAccessToken("613021275-Y3Utjpyh8cfAYpGel6UWs1aqzUMOdGuxuwsUc9jo");
    cb.setOAuthAccessTokenSecret("2NC2l6KgVVymgeNez9X2s0YezMhVXuO1UPq8j60IeI");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

From source file:TimeLine.java

private void btTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTwitActionPerformed
    // Tombol update status, show setelah update
    txtStatus.setText("");

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

    try {// ww w.  ja va2s  .co  m
        Status status = twitter.updateStatus(txStatus.getText());
        JOptionPane.showMessageDialog(rootPane, "Twit \n [ " + status.getText() + " ]\nTerkirim!");
    } catch (TwitterException ex) {
        JOptionPane.showMessageDialog(rootPane, "Tidak bisa mengirim : " + ex.getMessage());
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Status> statuses = null;
    try {
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:TimeLine.java

private void btTimelineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTimelineActionPerformed
    // TODO add your handling code here:
    txtTimeline.setText("");

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

    List<Status> statuses = null;
    try {//www. j ava  2 s  .co m
        statuses = twitter.getHomeTimeline();

        statuses.stream().forEach((status) -> {
            txtTimeline.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });
    } catch (TwitterException ex) {
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + ex.getMessage());
    }
}

From source file:TimeLine.java

private void btReloadTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReloadTwitActionPerformed
    // Tombol reload twit saya
    txtStatus.setText("");

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

    List<Status> statuses = null;
    try {//from ww w.  j  a  v a2 s  . c om
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:NewMain.java

/**
 * @param args the command line arguments
 *//* w  w w  .j  a v  a 2  s.co  m*/

public static void main(String[] args) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    ResponseList<twitter4j.Status> statuses = twitter.getHomeTimeline();
    System.out.println("Mostrando el timeline...");
    for (twitter4j.Status status : statuses) {
        System.out.println("@" + status.getUser().getScreenName() + ": " + status.getText());

    }
}

From source file:GetHomePageData.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww  . java2s .  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try {
        /* TODO output your page here. You may use following sample code. */
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GetHomePageData</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GetHomePageData at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("Olwk4ncLNgYZcROLvP9oAFrgv")
                .setOAuthConsumerSecret("eht2OHYflAV1Cu8GP9XA46zm7KbiivY35TytvJ91aMX67brKEF")
                .setOAuthAccessToken("1668200646-cR34ReTvqAUgQGNvFQWlbGNkGgksXvq7yFHWlO6")
                .setOAuthAccessTokenSecret("VAU21C4JHFCrbBfwDfTkdLEkSkpjBD7VFkFowFwLPAuoC");

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

        List<Status> statuses;
        //statuses= twitter.getHomeTimeline();
        out.println("Showing home timeline.");
        // for (Status status : statuses) 
        //   out.println(status.getUser().getName() + ":" +     status.getText());

    } catch (Exception e) {

    }
}

From source file:MapDemo.java

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

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();
    boolean flag = true;
    // Ask the user for a search string.
    String searchStr = "ParkandGoUNL";

    // Create a Query object.
    Query query = new Query(searchStr);

    // Send API request to execute a search with the given query.
    QueryResult result = twitter.search(query);

    // Display search results.
    result.getTweets().stream().forEach((Status status) -> {
        System.out.println("\n" + status.getText() + status.getCreatedAt());
    });/*from   w  w w .j  av  a 2s . c om*/

    if (flag) {

        GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");
        List<Marker> markers = new ArrayList<>();
        Marker e = new Marker(GeocodingApi.geocode(context, "616 North 16th Street, Lincoln, Nebraska, USA")
                .await()[0].geometry.location, "marker1", "KKG", new Date());
        markers.add(e);

        StreetExtractor se = new StreetExtractor();
        List<Address> address = se.find("Park and Go 601 North 16th Street");
        address.forEach(((Address a) -> {

            try {
                Marker m = new Marker(
                        GeocodingApi.geocode(context, a.getAddress()).await()[0].geometry.location, "marker0",
                        "A Tweet", new Date());
                markers.add(m);
            } catch (Exception ex) {
                Logger.getLogger(MapDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }));

        Map map = new Map(markers);
        map.create();
    }
}

From source file:TweetMapManager.java

public static void main(String[] args) {

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();
    String searchStr = "#ParkandGoUNL";
    Query query = new Query(searchStr);

    GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");
    List<Marker> markers = new LinkedList<>();
    StreetExtractor se = new StreetExtractor();
    LocalTime now = LocalTime.now();

    while (true) {
        DayOfWeek today = LocalDate.now().getDayOfWeek();
        if (today.getValue() < WEEKEND) {
            if (now.isAfter(STARTTIME) && now.isBefore(ENDTIME)) {

                // Send API request to execute a search with the given query.
                QueryResult results = null;
                try {
                    results = twitter.search(query);
                } catch (TwitterException ex) {
                    LOGGER.warn(ex.getMessage());
                }//from   w w  w .ja v a2s  .  co  m

                // Display search results.
                if (results != null) {
                    results.getTweets().stream().forEach((Status status) -> {
                        try {

                            Date created = status.getCreatedAt();
                            String text = status.getText();
                            LOGGER.info(status.getText());
                            LatLng location;
                            if (status.getGeoLocation() != null) {
                                location = new LatLng(status.getGeoLocation().getLatitude(),
                                        status.getGeoLocation().getLongitude());
                            } else {
                                String modified = text.replace("#ParkAndGoUNL", "");
                                List<Address> address = se.find(modified);

                                location = GeocodingApi.geocode(context, address.get(0).getAddress())
                                        .await()[0].geometry.location;
                            }
                            String id = UUID.randomUUID().toString().substring(0, 8);
                            Marker m = new Marker(location, "m" + id, text, created);
                            markers.add(m);
                        } catch (Exception ex) {
                            LOGGER.warn(ex.getMessage());
                        }

                    });
                }
                if (!markers.isEmpty()) {
                    Marker m = markers.get(markers.size() - 1);

                    if (m.getTimestamp().getTime() < Time.valueOf(now.minusMinutes(30)).getTime()) {
                        DailyLogs.addMarkerToLog(m, today);
                        markers.remove(m);
                    }
                }
                Map map = new Map(markers);
                map.create();
            } else {
                //wait 5 hours
                try {
                    LOGGER.info("Sleeping 5 hours");
                    Thread.sleep((long) 1.8e+7);
                } catch (InterruptedException ex) {
                    LOGGER.warn(ex.getMessage());
                }
            }

            now = LocalTime.now();
        } else {
            try {
                //Wait a day
                LOGGER.info("Sleeping 1 day");
                Thread.sleep((long) 8.64e+7);
            } catch (InterruptedException ex) {
                LOGGER.warn(ex.getMessage());
            }
        }
        try {
            LOGGER.info("Successful Loop, Resting");
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            LOGGER.warn(ex.getMessage());
        }
    }
}

From source file:twitterGateway_v2_06.java

License:Creative Commons License

public void SetupTwitter() {
    //twitterIn = new TwitterConnectStream();
    //accessToken = new AccessToken(TwitterAccessToken, TwitterAccessTokenSecret);
    //TwitterOAuthAuthorization.setOAuthAccessToken(accessToken);
    //TwitterOAuthAuthorization = new OAuthAuthorization(conf);
    //TwitterOAuthAuthorization.setOAuthConsumer(TwitterConsumerKey, TwitterConsumerSecret);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(TwitterConsumerKey)
            .setOAuthConsumerSecret(TwitterConsumerSecret).setOAuthAccessToken(TwitterAccessToken)
            .setOAuthAccessTokenSecret(TwitterAccessTokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitterOut = tf.getInstance();
    //  try {// w  w w .  ja  va2s . c  om
    //  twitterOut.updateStatus("Hello World!");
    //  }
    //  catch (TwitterException ex) {
    //    println(ex);
    //  }
    ActivityLogAddLine("twitter connector ready");
    output = createWriter("log.txt");

    StatusListener twitterIn = new StatusListener() {
        public void onStatus(Status status) {
            double Longitude;
            double Latitude;
            GeoLocation GeoLoc = status.getGeoLocation();
            if (GeoLoc != null) {
                //println("YES got a location");
                Longitude = GeoLoc.getLongitude();
                Latitude = GeoLoc.getLatitude();
            } else {
                Longitude = 0;
                Latitude = 0;
            }
            println(TimeStamp() + "\t" + Latitude + "\t" + Longitude + "\t" + status.getUser().getScreenName()
                    + "\t" + status.getText());
            output.println(TimeStamp() + "\t" + Latitude + "\t" + Longitude + "\t"
                    + status.getUser().getScreenName() + "\t" + status.getText());
            output.flush();
            TwitterToOsc(status.getUser().getScreenName(), status.getText());
        }

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

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

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

        public void onException(Exception ex) {
            println("CAUGHT in the ACT: " + ex);
        }
    };

    ConfigurationBuilder cbIn = new ConfigurationBuilder();
    cbIn.setDebugEnabled(true).setOAuthConsumerKey(TwitterConsumerKey)
            .setOAuthConsumerSecret(TwitterConsumerSecret).setOAuthAccessToken(TwitterAccessToken)
            .setOAuthAccessTokenSecret(TwitterAccessTokenSecret);

    TwitterStreamFactory ts = new TwitterStreamFactory(cbIn.build());
    TwitterStream twitterStream = ts.getInstance();
    twitterStream.addListener(twitterIn);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    FilterQuery twitterFilter = new FilterQuery(0, TwitterFollowIDs, TwitterTrackWords);
    twitterStream.filter(twitterFilter);
}

From source file:Pencarian.java

private void btSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSearchActionPerformed
    // TODO add your handling code here:
    txtSearchTimeline.setText("");

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

    Query query = new Query(txSearch.getText());
    QueryResult result = null;/*  w  w  w .  ja va 2s.  c  om*/

    try {
        result = twitter.search(query);

        result.getTweets().stream().forEach((status) -> {
            txtSearchTimeline.append("@" + status.getUser().getScreenName() + ":" + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });
    } catch (TwitterException ex) {
        Logger.getLogger(Pencarian.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(rootPane, "Failed !! " + ex.getMessage());
    }
}