Example usage for twitter4j Twitter showUser

List of usage examples for twitter4j Twitter showUser

Introduction

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

Prototype

User showUser(long userId) throws TwitterException;

Source Link

Document

Returns extended information of a given user, specified by ID or screen name as per the required id parameter.

Usage

From source file:com.tweetmyhome.db.TweetMyHomeDatabase.java

/**
 * "Elimina" o Agrega usuarios segun lo que contenga la base de datos
 * Se utiliza esta funcion para mantener la integridad de los datos respecto a twitter
 * @param ids /*from  w  ww .ja  v  a  2 s . c  o  m*/
 * @param tw 
 * @throws twitter4j.TwitterException 
 */
public void processTwiterUsersFromTwitterIds(long[] ids, Twitter tw) throws TwitterException {
    List<TwitterUser> db_users = getAllUsers();
    for (long id : ids) {
        long founded_id = NOT_EXIST;
        Iterator<TwitterUser> iterator_users = db_users.iterator();
        while (iterator_users.hasNext()) {
            TwitterUser tuser = iterator_users.next();
            if (!tuser.getRol().equals(UserRol.super_admin)) { // si no es super usuario
                if (tuser.getIdTwitterUser() == id) { // si coincide la id
                    founded_id = id;
                    debug("User founded in DB :" + id);
                    iterator_users.remove();
                    break;
                }
            } else { // saco al super usuario de la lista
                iterator_users.remove();
            }
        }
        if (founded_id == NOT_EXIST) {// no encontrado
            add(new TwitterUser(id, TwitterUserUtil.getTwitterUser(tw.showUser(id).getScreenName()),
                    UserRol.user, true));
            debug("Added new user to DB :" + id);
        }
    }
    db_users.forEach(u -> {
        if (u.isActivado()) {
            desactivateUserById(u.getIdTwitterUser());
            debug("Desactivated user :" + u.getIdTwitterUser());
        }
    });
}

From source file:com.twitstreet.servlet.CallBackServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    response.setHeader("Pragma", "no-cache"); //HTTP 1.0
    response.setDateHeader("Expires", 0); //prevents caching at the proxy server

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret());

    RequestToken requestToken = (RequestToken) request.getSession().getAttribute(REQUEST_TOKEN);
    String verifier = request.getParameter(OAUTH_VERIFIER);
    try {//  ww  w  . ja  va 2s.  c  o  m
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        long userId = accessToken.getUserId();
        String screenName = accessToken.getScreenName();
        String oauthToken = accessToken.getToken();
        String oauthTokenSecret = accessToken.getTokenSecret();
        User user = null;
        user = userMgr.getUserById(userId);
        //new user
        if (user == null) {
            twitter4j.User twUser = twitter.showUser(userId);
            user = new User();
            user.setId(userId);
            user.setUserName(screenName);
            user.setLastIp(request.getRemoteAddr());
            user.setOauthToken(oauthToken);
            user.setOauthTokenSecret(oauthTokenSecret);
            user.setCash(configMgr.getInitialMoney());
            user.setPictureUrl(twUser.getProfileImageURL().toExternalForm());

            user.setDescription(twUser.getDescription());
            user.setLongName(twUser.getName());
            user.setLocation(twUser.getLocation());
            user.setLanguage(twUser.getLang());
            user.setUrl(twUser.getURL() == null ? null : twUser.getURL().toExternalForm());

            userMgr.saveUser(user);
            String referenceId = (String) request.getSession().getAttribute(HomePageServlet.REFERENCE_ID);
            long referenceLong = -1;
            try {
                referenceLong = Long.parseLong(referenceId);
            } catch (NumberFormatException e) {
                logger.error("Parsing reference id failed: " + referenceId);
            }
            if (referenceLong > -1) {
                userMgr.invite(referenceLong, user.getId());
            }
            request.getSession().removeAttribute(HomePageServlet.REFERENCE_ID);

        } else {
            //existing user logging in again
            user = new User();
            user.setId(userId);
            user.setUserName(screenName);
            user.setLastIp(request.getRemoteHost());
            user.setOauthToken(oauthToken);
            user.setOauthTokenSecret(oauthTokenSecret);
            user.setAutoPlayer(false);
            userMgr.updateUser(user);
        }
        request.getSession().setAttribute(User.USER_ID, user.getId());
        Cookie cookies[] = createCookie(userId, oauthToken);
        writeCookies(response, cookies);
    } catch (TwitterException e) {
        throw new ServletException(e);
    }
    response.sendRedirect(request.getContextPath() + "/");
}

From source file:com.wavemaker.runtime.ws.TwitterFeedService.java

License:Open Source License

/**
 * Reads from the InputStream of the specified URL and builds the feed object from the returned XML.
 * /*from w  w w .j a  v a  2s  .  c  om*/
 * @param screenId users screen Id
 * @return A feed object.
 */
@ExposeToClient
public Feed getFeed(String screenId) {
    try {
        Twitter twitter = getTwitter();
        User user = twitter.showUser(screenId);
        if (user == null) {
            logger.debug("No user present with the screen name [" + screenId + "]");
            throw new WMRuntimeException("No user present with the screen name [" + screenId + "]");
        }
        if (user.isProtected()) {
            logger.debug("Tweets for the user with the screen name [" + screenId + "] are protected");
            throw new WMRuntimeException(
                    "Tweets for the user with the screen name [" + screenId + "] are protected");
        }
        ResponseList<Status> tweetStatus = twitter.getUserTimeline(screenId);
        return FeedBuilder.getFeed(screenId, tweetStatus);
    } catch (TwitterException e) {
        logger.warn("Cannot get the twitter feed for the user [" + screenId + "]", e);
        throw new WMRuntimeException(e);
    }
}

From source file:crawling.GetUserTimelineMulti.java

License:Apache License

public void showRateLimit() {
    for (Twitter twitter : this.twitters) {
        try {/*from w w w  .ja v  a 2 s  . com*/
            System.out.println(twitter.showUser(twitter.getId()).getRateLimitStatus());
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:de.vanita5.twittnuker.loader.support.ParcelableUserLoader.java

License:Open Source License

private static User showUser(final Twitter twitter, final long id, final String screenName)
        throws TwitterException {
    if (id != -1)
        return twitter.showUser(id);
    else if (screenName != null)
        return twitter.showUser(screenName);
    return null;/*w  w  w .  j  av  a2s .  c o  m*/
}

From source file:demo.UserFollowers.java

License:Apache License

public static void main(String[] args) throws TwitterException, IOException {
    //?//from w  w  w  .j  a v a 2 s.  c  om
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter tw = new TwitterFactory(configuration).getInstance();
    //String screenName = "masason";
    String screenName = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print(
            "??ScreenName???????!! ex)masason : ");
    screenName = br.readLine();

    //?
    List<Long> followersList = followers(tw, screenName);
    for (int i = 0; i < followersList.size(); i++) {
        //???idscreenName?
        User user = tw.showUser(followersList.get(i));
        System.out.println("[" + (i + 1) + "]" + "ScreenName : " + "[" + user.getScreenName() + "]  "
                + "UserIds : " + followersList.get(i));
    }
}

From source file:demo.UserInfo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {
    //?//www .  j a v  a2s .  c  o m
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter tw = new TwitterFactory(configuration).getInstance();
    String screenName = "";

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("????ScreenName???????!! ex)masason : ");
    screenName = br.readLine();
    //String screenName = "masason";//masason
    try {
        //?&
        User user = tw.showUser(screenName);
        System.out.println("???");
        System.out.println("User ID : " + user.getId());
        System.out.println("ScreenName : " + user.getScreenName());
        System.out.println("User's Name : " + user.getName());
        System.out.println("Number of Followers : " + user.getFollowersCount());
        System.out.println("Number of Friends : " + user.getFriendsCount());
        System.out.println("Language : " + user.getLang());
        //?
        Status status = user.getStatus();
        System.out.println("???");
        System.out.println("User Created : " + status.getCreatedAt());
        System.out.println("Status ID : " + status.getId());
        System.out.println(status.getSource());
        System.out.println("Tweet" + status.getText());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  va 2  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:it.baywaylabs.jumpersumo.twitter.TwitterUtility.java

License:Open Source License

/**
 * Twitter utility for extract id from twitter username.
 *
 * @param name Twitter User Name.//w  w w . j a v a 2s  .  c o m
 * @param twitter Twitter4j instance.
 * @return Twitter Id user, or 0 if is not find.
 */
public Long getIdUser(String name, Twitter twitter) {
    if (twitter != null) {
        User user = null;
        try {
            user = twitter.showUser(name);
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return user.getId();
    }
    return 0l;
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterUtility.java

License:Open Source License

/**
 *
 * Twitter utility for extract twitter username from id.
 *
 * @param id Twitter User id.//from  w w w .java 2s .  co  m
 * @param twitter Twitter4j instance.
 * @return Twitter User Name or blank string if is not find.
 */
public String getNameUser(Long id, Twitter twitter) {
    if (twitter != null) {
        User user = null;
        try {
            user = twitter.showUser(id);
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return user.getName();
    }
    return "";
}