Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory() 

Source Link

Document

Creates a TwitterFactory with the root configuration.

Usage

From source file:edu.stanford.muse.slant.SigninServlet.java

License:Apache License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  ww w  .  j  a v a 2 s .co  m*/
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(OAuth_consumerKey, OAuth_consumerSecret);
        request.getSession().setAttribute("twitter", twitter);
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (Exception e) {
        System.out.println(e);
    }

}

From source file:ehealth.external.twitter.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/*from  w  w  w .  jav a  2  s  . c  o m*/
 */

protected void loginTwitter(String[] args) {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        if (args.length < 2) {
            if (null == prop.getProperty("oauth.consumerKey")
                    && null == prop.getProperty("oauth.consumerSecret")) {
                // consumer key/secret are not set in twitter4j.properties
                System.out.println(
                        "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                System.exit(-1);
            }
        } else {
            prop.setProperty("oauth.consumerKey", args[0]);
            prop.setProperty("oauth.consumerSecret", args[1]);
            os = new FileOutputStream("twitter4j.properties");
            prop.store(os, "twitter4j.properties");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        AccessToken accessToken = null;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == accessToken) {
            System.out.println("Open the following URL and grant access to your account:");
            System.out.println(requestToken.getAuthorizationURL());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (UnsupportedOperationException ignore) {
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            }
            System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
            try {
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                }
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());

        try {
            prop.setProperty("oauth.accessToken", accessToken.getToken());
            prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, "twitter4j.properties");
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.exit(-1);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get accessToken: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:ens.demo.twitter.SigninServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w  .  j  av  a2 s . 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 {
    Twitter twitter = new TwitterFactory().getInstance();
    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:es.upm.oeg.examples.watson.servlets.TwitterAnalysisServlet.java

License:Apache License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from ww  w.  j  a  va2 s.c o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String twitterUsername = request.getParameter("twitter_name");
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    env = System.getenv();
    consumer_key = env.get("TWITTER_CONSUMER_KEY");
    consumer_secret = env.get("TWITTER_CONSUMER_SECRET");
    access_token = env.get("TWITTER_ACCESS_TOKEN");
    access_key = env.get("TWITTER_ACCESS_KEY");

    AccessToken accessToken = new AccessToken(access_token, access_key);

    try {
        twitter.setOAuthConsumer(consumer_key, consumer_secret);
        twitter.setOAuthAccessToken(accessToken);

        twitter4j.User a_name = twitter.showUser(twitterUsername);
        int followerCount = a_name.getFollowersCount();
        List<Status> retweets = twitter.getUserTimeline(twitterUsername, new Paging(1, 20)); // get the first twenty tweets
        int retweetCount = 0;
        List<String> langs = new ArrayList<>();
        List<String> translated = new ArrayList<>();

        StringBuilder aggregatedTextBuilder = new StringBuilder();
        String personalityInsights = null;

        for (Status tweet : retweets) {
            String tweetText = tweet.getText();
            try {
                String lang = languageIdentification.getLang(tweetText);
                langs.add(lang);
                String englishText;
                //TODO do the same for french and portuguese
                if (LanguageIdentificationService.ES_ES.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.ES_TO_EN);
                } else if (LanguageIdentificationService.FR_FR.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.FR_TO_EN);
                } else if (LanguageIdentificationService.PT_BR.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.PT_TO_EN);
                } else {
                    englishText = tweetText;
                }
                translated.add(englishText);
                aggregatedTextBuilder.append(englishText);

                personalityInsights = personalityInsightsService.analyse(aggregatedTextBuilder.toString());

            } catch (Exception e) {
                // Log something and return an error message
                logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
                request.setAttribute("error", e.getMessage());
            }

        }

        request.setAttribute("t_name", twitterUsername);
        request.setAttribute("rtweets", retweets);
        request.setAttribute("langs", langs);
        request.setAttribute("translated", translated);
        request.setAttribute("personalityInsights", personalityInsights);
        request.setAttribute("aggregatedText", aggregatedTextBuilder.toString());

        request.getRequestDispatcher("/myTweets.jsp").forward(request, response);
    } catch (TwitterException e) {

        e.printStackTrace();
        if (e.getErrorCode() == 215 || e.getErrorCode() == 32) {
            response.sendRedirect("../index.html?message=errorcode215");
        } else if (e.getErrorCode() == -1 || e.getErrorCode() == 34) {
            response.sendRedirect("../index.html?message=errorcode-1");
        } else {
            response.sendRedirect("../index.html?message=errorcode99");
        }
        //throw new ServletException("Encountered a problem fetching data from Twitter - " + e.getErrorMessage());
    }
}

From source file:eu.smartfp7.SocialNetworkSearchResults.TwitterPostData.java

License:Mozilla Public License

public TwitterPostData(Tweet TwitterPost) {
    Twitter twitter = new TwitterFactory().getInstance();
    UserName = TwitterPost.getFromUser();
    UserID = TwitterPost.getFromUserId() + "";

    this.Message = TwitterPost.getText();
    this.CreationDate = TwitterPost.getCreatedAt();
    this.Source = "Twitter";
    if (TwitterPost.getPlace() != null) {
        this.LocationName = TwitterPost.getPlace().getName();
        this.GeoLatitude = TwitterPost.getPlace().getGeometryCoordinates()[0][0].getLatitude();
        this.GeoLongitude = TwitterPost.getPlace().getGeometryCoordinates()[0][0].getLongitude();
    }//from   w  w  w.j  a v  a2 s.com
}

From source file:examples.GetUserListStatuses.java

License:Apache License

/**
 * Usage: java twitter4j.examples.list.GetUserListStatuses [list id]
 *
 * @param args message//from   ww  w.  j av  a  2s.c  o  m
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.list.GetUserListStatuses [list id]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        Paging page = new Paging(1);
        ResponseList<Status> statuses;
        do {
            statuses = twitter.getUserListStatuses(Integer.parseInt(args[0]), page);
            for (Status status : statuses) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }
            page.setPage(page.getPage() + 1);
        } while (statuses.size() > 0 && page.getPage() <= 10);
        System.out.println("done.");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to list statuses: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:free.chessclub.bot.TwitterManager.java

License:Apache License

public void connect() {
    try {//from  w  w w.  jav  a2  s.co m
        File configInfo = new File("twitter_Auth.cfg");
        Scanner fileReader = new Scanner(configInfo);
        String consumerKeyStr = fileReader.nextLine().trim();
        String consumerSecretStr = fileReader.nextLine().trim();
        String accessTokenStr = fileReader.nextLine().trim();
        String tokenSecretStr = fileReader.nextLine().trim();
        //String pinStr = fileReader.nextLine().trim();

        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
        twitter.setOAuthAccessToken(new AccessToken(accessTokenStr, tokenSecretStr));
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:geo.GetSimilarPlaces.java

License:Apache License

/**
 * Usage: java twitter4j.examples.geo.GetSimilarPlaces [latitude] [longitude] [place id]
 *
 * @param args message//from   w w w  .  j  a v a 2  s . c om
 */
public static void main(String[] args) {
    if (args.length < 3) {
        System.out.println(
                "Usage: java twitter4j.examples.geo.GetSimilarPlaces [latitude] [longitude] [name] [place id]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        GeoLocation location = new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1]));
        String name = args[2];
        String containedWithin = null;
        if (args.length >= 4) {
            containedWithin = args[3];
        }
        ResponseList<Place> places = twitter.getSimilarPlaces(location, name, containedWithin, null);
        if (places.size() == 0) {
            System.out.println("No location associated with the specified condition");
        } else {
            for (Place place : places) {
                System.out.println("id: " + place.getId() + " name: " + place.getFullName() + " name: "
                        + place.getFullName());
                Place[] containedWithinArray = place.getContainedWithIn();
                if (containedWithinArray != null && containedWithinArray.length != 0) {
                    System.out.println("  contained within:");
                    for (Place containedWithinPlace : containedWithinArray) {
                        System.out.println("  id: " + containedWithinPlace.getId() + " name: "
                                + containedWithinPlace.getFullName());
                    }
                }
            }
        }
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to find similar places: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:geo.ReverseGeoCode.java

License:Apache License

/**
 * Usage: java twitter4j.examples.geo.ReverseGeoCode [latitude] [longitude]
 *
 * @param args message/*from  ww w  .j  a v a  2 s  .  c o  m*/
 */
public static void main(String[] args) {
    if (args.length < 2) {
        System.out.println("Usage: java twitter4j.examples.geo.ReverseGeoCode [latitude] [longitude]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        GeoQuery query = new GeoQuery(
                new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1])));
        ResponseList<Place> places = twitter.reverseGeoCode(query);
        if (places.size() == 0) {
            System.out.println("No location associated with the specified lat/lang");
        } else {
            for (Place place : places) {
                System.out.println("id: " + place.getId() + " name: " + place.getFullName());
                Place[] containedWithinArray = place.getContainedWithIn();
                if (containedWithinArray != null && containedWithinArray.length != 0) {
                    System.out.println("  contained within:");
                    for (Place containedWithinPlace : containedWithinArray) {
                        System.out.println("  id: " + containedWithinPlace.getId() + " name: "
                                + containedWithinPlace.getFullName());
                    }
                }
            }
        }
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to retrieve places: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:geo.SearchPlaces.java

License:Apache License

/**
 * Usage: java twitter4j.examples.geo.SearchPlaces [ip address] or [latitude] [longitude]
 *
 * @param args message/*from w ww .j a  v a2 s .com*/
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println(
                "Usage: java twitter4j.examples.geo.SearchPlaces [ip address] or [latitude] [longitude]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        GeoQuery query;
        if (args.length == 2) {
            query = new GeoQuery(new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1])));
        } else {
            query = new GeoQuery(args[0]);
        }
        ResponseList<Place> places = twitter.searchPlaces(query);
        if (places.size() == 0) {
            System.out.println("No location associated with the specified IP address or lat/lang");
        } else {
            for (Place place : places) {
                System.out.println("id: " + place.getId() + " name: " + place.getFullName());
                Place[] containedWithinArray = place.getContainedWithIn();
                if (containedWithinArray != null && containedWithinArray.length != 0) {
                    System.out.println("  contained within:");
                    for (Place containedWithinPlace : containedWithinArray) {
                        System.out.println("  id: " + containedWithinPlace.getId() + " name: "
                                + containedWithinPlace.getFullName());
                    }
                }
            }
        }
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to retrieve places: " + te.getMessage());
        System.exit(-1);
    }
}