Example usage for twitter4j User getId

List of usage examples for twitter4j User getId

Introduction

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

Prototype

long getId();

Source Link

Document

Returns the id of the user

Usage

From source file:twitter.metrics.TwitterMetrics.java

/**
 * @param args the command line arguments
 *///  w w  w . ja  v  a 2 s.  c  om
public static void main(String[] args) {

    try {

        /*Parte que guarda en un archivo*/
        // Se crea el libro
        HSSFWorkbook libro = new HSSFWorkbook();

        // Se crea una hoja dentro del libro
        HSSFSheet hoja = libro.createSheet();

        // Se crea una fila dentro de la hoja
        HSSFRow fila = hoja.createRow(0);

        // Se crea una celda dentro de la fila
        HSSFCell celda = fila.createCell(1);

        // Se crea el contenido de la celda y se mete en ella.
        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Twitter");
        celda.setCellValue(texto);
        /************************************/

        /*Conexion con Mongo DB*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoTwitter");

        DBCollection datos = db.getCollection("Datos");

        /***********************/

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);

        cb.setOAuthConsumerKey("TobUISZXWUhDda04ZBtFGQ");
        cb.setOAuthConsumerSecret("7xurVN3iP6VDcBfKdFJxVuNsJjExERFYNmQIDgtg");

        cb.setOAuthAccessToken("849956971-GJBiORhLIuWK4i3MJ2YCd4vidh65N1GzPIb6duXk");
        cb.setOAuthAccessTokenSecret("4MJgPS9grxVuKbczrPCdSjNnumhcWs7t7OLy2F4kkpOdu");

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

        User u = twitter.showUser("Pringles");

        System.out.println("Nombre: " + u.getName());
        System.out.println("Seguidores: " + u.getFollowersCount());
        System.out.println("Favoritos: " + u.getFavouritesCount());
        System.out.println("Seguidos: " + u.getFriendsCount());
        System.out.println("Ubicacion: " + u.getLocation());
        System.out.println("Descripcin: " + u.getDescription());
        System.out.println("");

        fila = hoja.createRow(1);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Nombre:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getName()));

        fila = hoja.createRow(2);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidores:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFollowersCount() + ""));

        fila = hoja.createRow(3);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Favoritos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFavouritesCount() + ""));

        fila = hoja.createRow(4);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Seguidos:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getFriendsCount() + ""));

        fila = hoja.createRow(5);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Ubicacin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getLocation() + ""));

        fila = hoja.createRow(6);
        celda = fila.createCell(0);
        celda.setCellValue(new HSSFRichTextString("Descripcin:"));
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString(u.getDescription() + ""));

        fila = hoja.createRow(7);
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweets!!!"));

        fila = hoja.createRow(9);
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("IdTweet"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Cuenta"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Tweet"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Geolocation"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("Place"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("Retweets"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Favoritos"));

        Paging paging = new Paging(1, 1000);
        ResponseList<Status> s = twitter.getUserTimeline(u.getId(), paging);
        int i = 0;
        int filaNum = 10;
        for (Status st : s) {

            BasicDBObject obj = new BasicDBObject();

            obj.append("idTweet", s.get(i).getId() + "");
            obj.append("Cuenta", u.getName());
            obj.append("Tweet", s.get(i).getText());
            obj.append("Geolocation", s.get(i).getGeoLocation());
            obj.append("Place", s.get(i).getPlace());
            obj.append("Reteews", s.get(i).getRetweetCount());
            obj.append("Favoritos", s.get(i).getFavoriteCount());

            fila = hoja.createRow(filaNum);
            celda = fila.createCell(1);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getId() + ""));
            celda = fila.createCell(2);
            celda.setCellValue(new HSSFRichTextString(u.getName()));
            celda = fila.createCell(3);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getText()));
            celda = fila.createCell(4);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getGeoLocation() + ""));
            celda = fila.createCell(5);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getPlace() + ""));
            celda = fila.createCell(6);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getRetweetCount() + ""));
            celda = fila.createCell(7);
            celda.setCellValue(new HSSFRichTextString(s.get(i).getFavoriteCount() + ""));

            i++;
            filaNum++;

            datos.insert(obj);
        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_Twitter.xls");
        libro.write(elFichero);
        elFichero.close();

        /********************************/

        System.out.println(i);

        //User usuario = twitter.showUser("@aaron21007");
        //    List<Status> statuses = twitter.getHomeTimeline();
        //    System.out.println("Showing home timeline.");
        //    for (Status status : statuses) {
        //        System.out.println(status.getUser().getName() + ":" +
        //                           status.getText());
        //    }

        //        Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance();
        //        
        //          List<String> listaTweets = new ArrayList();
        //          List<Long> ListaRettewts = new ArrayList();
        //          List<Integer> ListaFavoritos = new ArrayList();
        //          List<Integer> ListaMenciones = new ArrayList();
        //          List<Date> ListaFecha = new ArrayList();
        //          List<Long> ListaIds = new ArrayList();
        ////
        //          User usuario = unauthenticatedTwitter.showUser("@aaron21007");
        //          List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe();
        //          List<Status> favoritos = unauthenticatedTwitter.getFavorites();
        //          Paging paging = new Paging(1, 1000);
        //          ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(), paging);
        //          
        //          
        //          for (Status sta : statuses) {
        //              
        //            ListaIds.add(Long.valueOf(sta.getId()));
        //            listaTweets.add(sta.getText());
        //            ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + "")));
        //            ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length));
        //            ListaFecha.add(sta.getCreatedAt());
        //            ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount()));
        //              System.out.println(sta.getText());
        //              
        //          }
        //          
        //          
        //        
        //       
        //        
    } catch (Exception e) {
        System.err.println("Fallo................." + e);
    }
}

From source file:TwitterDownload.TwitterExel.java

public static String writeFollowers(long ID, List<User> followers, String path) {
    try {/*from   w w  w.  ja  v  a 2  s.  c  o  m*/
        path = path + "Tweets";

        File theDir = new File(path);

        // if the directory does not exist, create it
        if (!theDir.exists()) {
            theDir.mkdir();
        }

        String exlPath = path + "/" + ID + ".xls";

        File exlFile = new File(exlPath);
        WritableWorkbook writableWorkbook = null;
        WritableSheet writableSheet = null;
        int i = 0;
        while (exlFile.exists()) {
            i++;

            exlPath = path + "/" + ID + "_" + i + ".xls";

            exlFile = new File(exlPath);
        }

        writableWorkbook = Workbook.createWorkbook(exlFile);

        writableSheet = writableWorkbook.createSheet("FerretData", 0);

        try {
            Workbook existing = Workbook.getWorkbook(exlFile);
            writableWorkbook = Workbook.createWorkbook(exlFile, existing);

            writableSheet = writableWorkbook.getSheet(0);
        } catch (BiffException be) {

        }

        //Create Cells with contents of different data types.
        //Also specify the Cell coordinates in the constructor

        i = 0;
        i = writableSheet.getRows();

        if (i == 0) {
            Label userName = new Label(0, 0, "User Name");
            Label name = new Label(1, 0, "Name");
            Label desc = new Label(2, 0, "Description");
            Label date = new Label(3, 0, "Created Date");
            Label uID = new Label(4, 0, "Twitter ID");
            Label link = new Label(5, 0, "Link");

            //Add the created Cells to the sheet
            writableSheet.addCell(userName);
            writableSheet.addCell(name);
            writableSheet.addCell(desc);
            writableSheet.addCell(date);
            writableSheet.addCell(uID);
            writableSheet.addCell(link);

            i = 1;
        }

        for (int j = 0; j < followers.size(); j++) {
            User u = followers.get(j);

            Label userName = new Label(0, i + j, u.getScreenName());
            Label name = new Label(1, i + j, u.getName());
            Label desc = new Label(2, i + j, u.getDescription());
            DateTime date = new DateTime(3, i + j, u.getCreatedAt());
            Label uID = new Label(4, i + j, Long.toString(u.getId()));

            String link = "https://twitter.com/" + u.getScreenName();
            URL url = new URL(link);

            WritableHyperlink hl = new WritableHyperlink(5, j + 1, url);

            //Add the created Cells to the sheet
            writableSheet.addCell(userName);
            writableSheet.addCell(name);
            writableSheet.addCell(desc);
            writableSheet.addCell(date);
            writableSheet.addCell(uID);
            writableSheet.addHyperlink(hl);
        }

        //Write and close the workbook
        writableWorkbook.write();
        writableWorkbook.close();

        return exlPath;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (RowsExceededException e) {
        e.printStackTrace();
    } catch (WriteException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:twitterNetwork.twitteridextraction.java

public static void main(String args[]) throws TwitterException {
    ConfigurationBuilder cb1 = new ConfigurationBuilder();
    cb1.setOAuthConsumerKey(consumerKey2);
    cb1.setOAuthConsumerSecret(consumerSecret2);
    cb1.setOAuthAccessToken(twitterToken2);
    cb1.setOAuthAccessTokenSecret(twitterSecret2);

    Twitter twitter = new TwitterFactory(cb1.build()).getInstance();
    User user = twitter.showUser(5108161);
    System.out.println(user.getName());
    System.out.println("<h3>Displaying user id of user " + user.getScreenName() + "</h3><br/>");
    System.out.println(user.getId());

}

From source file:twitterrest.Followersids.java

License:Apache License

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

    String ScreenName = "anondroid5";//??

    // ?//w  w w  .jav a2  s .  c o m
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter twitter = new TwitterFactory(configuration).getInstance();

    List<Long> followersList = followers(twitter, ScreenName);//?
    System.out.println(ScreenName + ":FolloweID List");
    for (int i = 0; i < followersList.size(); i++) {
        System.out.println("[" + (i + 1) + "]" + followersList.get(i));
        //?
        User user = twitter.showUser(followersList.get(i));
        System.out.println("User ID : " + user.getId());//UserID
        System.out.println("ScreenName : " + user.getScreenName());//ScreenName
        System.out.println("User's Name : " + user.getName());//UserName
        System.out.println("Number of Followers : " + user.getFollowersCount());//Number of Followers
        System.out.println("Number of Friends : " + user.getFriendsCount());//Number of Friends
        System.out.println("Language : " + user.getLang());//Language
    }
}

From source file:uk.ac.cam.cl.dtg.segue.auth.TwitterAuthenticator.java

License:Apache License

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference)
        throws NoUserException, IOException, AuthenticatorSecurityException {
    Credential credentials = credentialStore.get(internalProviderReference);
    twitter.setOAuthAccessToken(new AccessToken(credentials.getAccessToken(), credentials.getRefreshToken()));

    try {//from  w w  w  . j a  va 2s .  c  om
        twitter4j.User userInfo = twitter.verifyCredentials();

        if (userInfo != null) {
            // Using twitter id for email field is a hack to avoid a duplicate
            // exception due to null email field. Alistair and Steve dislike this...
            String givenName = null;
            String familyName = null;
            if (userInfo.getName() != null) {
                String[] names = userInfo.getName().split(" ");
                if (names != null) {
                    if (names.length > 0) {
                        givenName = names[0];
                    }
                    if (names.length > 1) {
                        familyName = names[1];
                    }
                }
            }

            return new UserFromAuthProvider(String.valueOf(userInfo.getId()), givenName, familyName,
                    userInfo.getId() + "-twitter", EmailVerificationStatus.NOT_VERIFIED, null, null, null);
        } else {
            throw new NoUserException();
        }
    } catch (TwitterException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:uk.ac.susx.tag.method51.twitter.Tweet.java

License:Apache License

public Tweet(Status status) {
    this();//  w w  w. j  a v a  2s. c o m
    created = status.getCreatedAt();
    id = status.getId();
    text = status.getText();

    inReplyToStatusId = status.getInReplyToStatusId();
    inReplyToUserId = status.getInReplyToUserId();

    originalText = null;
    retweetId = -1;
    isTruncated = status.isTruncated();
    isRetweet = status.isRetweet();
    Status entities = status;
    if (isRetweet) {
        Status origTweet = status.getRetweetedStatus();
        entities = origTweet;
        retweetId = origTweet.getId();
        originalText = text;
        text = origTweet.getText();
    }

    StringBuilder sb = new StringBuilder();

    for (HashtagEntity e : entities.getHashtagEntities()) {
        sb.append(e.getText());
        sb.append(" ");
    }
    hashtags = sb.toString();
    sb = new StringBuilder();

    for (UserMentionEntity e : entities.getUserMentionEntities()) {
        sb.append(e.getScreenName());
        sb.append(" ");
    }
    mentions = sb.toString();
    sb = new StringBuilder();

    for (URLEntity e : entities.getURLEntities()) {
        //String url = e.getURL();
        String url = e.getExpandedURL();
        if (url == null) {
            url = e.getURL();
            if (url != null) {
                sb.append(url);
            }

        } else {
            sb.append(url);
        }
        sb.append(" ");
    }
    urls = sb.toString();
    sb = new StringBuilder();

    //seems to be null if no entries
    MediaEntity[] mediaEntities = entities.getMediaEntities();
    if (mediaEntities != null) {
        for (MediaEntity e : mediaEntities) {
            String url = e.getMediaURL();
            sb.append(url);
            sb.append(" ");
        }
        mediaUrls = sb.toString();
    } else {
        mediaUrls = "";
    }

    received = new Date();

    source = status.getSource();
    GeoLocation geoLoc = status.getGeoLocation();
    Place place = status.getPlace();

    if (geoLoc != null) {

        geoLong = geoLoc.getLongitude();
        geoLat = geoLoc.getLatitude();
    } else if (place != null && place.getBoundingBoxCoordinates() != null
            && place.getBoundingBoxCoordinates().length > 0) {

        GeoLocation[] locs = place.getBoundingBoxCoordinates()[0];

        double avgLat = 0;
        double avgLon = 0;

        for (GeoLocation loc : locs) {

            avgLat += loc.getLatitude();
            avgLon += loc.getLongitude();
        }

        avgLat /= locs.length;
        avgLon /= locs.length;

        geoLat = avgLat;
        geoLong = avgLon;
    } else {

        geoLong = null;
        geoLat = null;
    }

    twitter4j.User user = status.getUser();

    if (user != null) {
        userId = user.getId();
        location = user.getLocation();
        screenName = user.getScreenName();
        following = user.getFriendsCount();
        name = user.getName();
        lang = user.getLang();
        timezone = user.getTimeZone();
        userCreated = user.getCreatedAt();
        followers = user.getFollowersCount();
        statusCount = user.getStatusesCount();
        description = user.getDescription();
        url = user.getURL();
        utcOffset = user.getUtcOffset();
        favouritesCount = user.getFavouritesCount();

        this.user = new User(user);
    }
}

From source file:uk.co.cathtanconsulting.twitter.TwitterSource.java

License:Apache License

/**
 * @param status/*from  www.ja  v a2  s.c om*/
 * 
 * Generate a TweetRecord object and submit to 
 * 
 */
private void extractRecord(Status status) {
    TweetRecord record = new TweetRecord();

    //Basic attributes
    record.setId(status.getId());
    //Using SimpleDateFormat "yyyy-MM-dd'T'HH:mm:ss'Z'"
    record.setCreatedAtStr(formatterTo.format(status.getCreatedAt()));
    //Use millis since epoch since Avro doesn't do dates
    record.setCreatedAtLong(status.getCreatedAt().getTime());
    record.setTweet(status.getText());

    //User based attributes - denormalized to keep the Source stateless
    //but also so that we can see user attributes changing over time.
    //N.B. we could of course fork this off as a separate stream of user info
    User user = status.getUser();
    record.setUserId(user.getId());
    record.setUserScreenName(user.getScreenName());
    record.setUserFollowersCount(user.getFollowersCount());
    record.setUserFriendsCount(user.getFriendsCount());
    record.setUserLocation(user.getLocation());

    //If it is zero then leave the value null
    if (status.getInReplyToStatusId() != 0) {
        record.setInReplyToStatusId(status.getInReplyToStatusId());
    }

    //If it is zero then leave the value null
    if (status.getInReplyToUserId() != 0) {
        record.setInReplyToUserId(status.getInReplyToUserId());
    }

    //Do geo. N.B. Twitter4J doesn't give use the geo type
    GeoLocation geo = status.getGeoLocation();
    if (geo != null) {
        record.setGeoLat(geo.getLatitude());
        record.setGeoLong(geo.getLongitude());
    }

    //If a status is a retweet then the original tweet gets bundled in
    //Because we can't guarantee that we'll have the original we can
    //extract the original tweet and process it as we have done this time
    //using recursion. Note: we will end up with dupes.
    Status retweetedStatus = status.getRetweetedStatus();
    if (retweetedStatus != null) {
        record.setRetweetedStatusId(retweetedStatus.getId());
        record.setRetweetedUserId(retweetedStatus.getUser().getId());
        extractRecord(retweetedStatus);
    }

    //Submit the populated record onto the channel
    processRecord(record);
}

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

License:Apache License

private Set<Long> readPartyIds(Twitter twitter, String screenName, String slug, String party) {
    Set<Long> ids = new HashSet<>();

    try {/*ww  w . j  ava  2  s. c  om*/
        long cursor = -1;
        PagableResponseList<User> response = null;
        do {
            response = twitter.getUserListMembers(screenName, slug, cursor);
            for (User user : response) {
                LOGGER.debug("Read id for user @{}", user.getScreenName());
                ids.add(user.getId());
            }
            cursor = response.getNextCursor();
        } while (response != null && response.hasNext());
    } catch (TwitterException e) {
        LOGGER.error("Twitter exception updating {} party list : {}", party, e.getMessage());
    }

    return ids;
}

From source file:Utils.ConvertUsers.java

License:Open Source License

public Set<TwitterUser> convertAll(Set<User> users) {

    Set<TwitterUser> twitterUsers = new HashSet();
    TwitterUser twitterUser;//  ww w.j ava2  s.c  o  m

    for (User user : users) {
        twitterUser = new TwitterUser();
        twitterUser.setCreated_at(user.getCreatedAt());
        twitterUser.setDescription(user.getDescription());
        twitterUser.setFollowers_count(user.getFollowersCount());
        twitterUser.setLang(user.getLang());
        twitterUser.setLocation(user.getLocation());
        twitterUser.setName(user.getName());
        twitterUser.setProfile_image_url(user.getProfileImageURL());
        twitterUser.setScreen_name(user.getScreenName());
        twitterUser.setIdTwitter(user.getId());
        twitterUser.setFriends_count(user.getFriendsCount());
        twitterUser.setProfile_banner_url(user.getProfileBannerURL());
        twitterUsers.add(twitterUser);
    }
    return twitterUsers;
}

From source file:Utils.ConvertUsers.java

License:Open Source License

public TwitterUser convertOne(User user) {

    TwitterUser twitterUser;//from w  w w  . j  a va2 s .c o  m

    twitterUser = new TwitterUser();
    twitterUser.setCreated_at(user.getCreatedAt());
    twitterUser.setDescription(user.getDescription());
    twitterUser.setFollowers_count(user.getFollowersCount());
    twitterUser.setLang(user.getLang());
    twitterUser.setLocation(user.getLocation());
    twitterUser.setName(user.getName());
    twitterUser.setProfile_image_url(user.getProfileImageURL());
    twitterUser.setScreen_name(user.getScreenName());
    twitterUser.setIdTwitter(user.getId());
    twitterUser.setFriends_count(user.getFriendsCount());
    twitterUser.setProfile_banner_url(user.getProfileBannerURL());

    return twitterUser;
}