Example usage for twitter4j User getName

List of usage examples for twitter4j User getName

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the name of the user

Usage

From source file:social.controller.GetTwitterToken.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  www. ja  v  a2s. c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //        processRequest(request, response);
    String pin = request.getParameter("pin");
    AccessToken accessToken = null;
    String user_name = "";
    try {
        if (pin.length() > 0) {
            accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        } else {
            accessToken = twitter.getOAuthAccessToken();
        }
        twitter4j.User user = twitter.showUser(twitter.getScreenName());
        user_name = user.getName();
    } catch (TwitterException te) {
        if (401 == te.getStatusCode()) {
            logger.log(Level.SEVERE, "Unable to get the access token.", te);
        } else {
            logger.log(Level.SEVERE, "", te);
        }
    }

    token = accessToken.getToken();
    tokenSecret = accessToken.getTokenSecret();
    response.setContentType("text/plain");
    response.getWriter().write(token + "," + tokenSecret + "," + user_name);

}

From source file:t.twitter.TTwitterModule.java

License:Open Source License

@Kroll.method
public void connect(HashMap args) {
    KrollDict arg = new KrollDict(args);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", ""))
            .setOAuthConsumerSecret(arg.optString("apisecret", ""))
            .setOAuthAccessToken(arg.optString("accesstoken", ""))
            .setOAuthAccessTokenSecret(arg.optString("accesssecret", ""));
    AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build());
    twitter = tf.getInstance();//from w  ww  .j  a  v a 2  s  .  c  om

    twitter.addListener(new TwitterAdapter() {
        @Override
        public void updatedStatus(Status status) {
            Log.d("Twitter", "text: " + status.getText());
        }

        @Override
        public void searched(QueryResult result) {
            HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>();
            List<Status> tweets = result.getTweets();
            KrollDict[] dList = new KrollDict[tweets.size()];

            // sort tweets
            Collections.sort(tweets, new Comparator<Status>() {
                public int compare(Status o1, Status o2) {

                    if (desc) {
                        if (o2.getId() < o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else {
                        if (o2.getId() > o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }
                }
            });

            // return tweets to titanium
            int i = 0;
            for (Status tweet : tweets) {
                if (lastID == -1 || lastID < tweet.getId()) {
                    KrollDict d = new KrollDict();
                    d.put("username", tweet.getUser().getScreenName());
                    d.put("userimage", tweet.getUser().getProfileImageURL());
                    d.put("text", tweet.getText());
                    d.put("date", tweet.getCreatedAt());
                    d.put("id", Long.toString(tweet.getId()));
                    dList[i] = d;
                    lastID = tweet.getId();
                    i++;
                }
            }

            KrollDict[] dList2 = new KrollDict[i];

            // shorten array
            System.arraycopy(dList, 0, dList2, 0, i);

            event.put("tweets", dList2);
            success.call(getKrollObject(), event);

            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void verifiedCredentials(User user) {

            HashMap<String, KrollDict> event = new HashMap<String, KrollDict>();
            KrollDict d = new KrollDict();

            d.put("user_name", user.getName());
            d.put("screen_name", user.getScreenName());
            d.put("image_path", user.getProfileImageURL());
            event.put("user_info", d);
            success.call(getKrollObject(), event);
            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void onException(TwitterException e, TwitterMethod method) {
            synchronized (LOCK) {
                LOCK.notify();
            }
            Log.e("twitter", "error: " + e.getErrorMessage());
        }
    });
    Log.d("Twitter", "connected");
}

From source file:the_vaps_project.The_vaps_project.java

public static void main(String[] args)/* throws TwitterException */ {
    // TODO code application logic here

    /*//from   w w w . j a va  2 s  .  c om
            
    List<Status> status = twitter.getHomeTimeline();
    for(Status st : status){
    System.out.println(st.getUser().getName()+"--------"+st.getText());
    System.out.println(st.getCreatedAt());
    }*/

    // The factory instance is re-useable and thread safe.
    /*Twitter twitter2 = tf.getSingleton();
     Query query = new Query("source:twitter4j yusukey");
     QueryResult result = twitter.search(query);
     for (Status statuss : result.getTweets()) {
     System.out.println("@" + statuss.getUser().getName() + ":" + statuss.getText());
     }*/
    TwitterCriteria criteria = null;
    Tweet t = null;
    criteria = TwitterCriteria.create()

            .setMaxTweets(10).setUntil("2016-11-08").setQuerySearch("#NeverTrump");

    /*Scribe s = new Scribe();
    s.detruireFichier("tweets.xml");
    s.ouvrir("tweets.xml");
    s.ecrire("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    s.ecrire("<tweets>\n");
    for (int i = 0; i < TweetManager.getTweets(criteria).size(); i++) {
    t = TweetManager.getTweets(criteria).get(i);
    s.ecrire("\t<tweet>\n");
    s.ecrire("\t\t<text><![CDATA["+t.getText()+"]]></text>\n");
    s.ecrire("\t\t<hashtags>"+t.getHashtags()+"</hashtags>\n");
    s.ecrire("\t\t<date>"+t.getDate()+"</date>\n");
    s.ecrire("\t\t<username>"+t.getUsername()+"</username>\n");
    s.ecrire("\t\t<retweets>"+t.getRetweets()+"</retweets>\n");
    s.ecrire("\t\t<favorites>"+t.getFavorites()+"</favorites>\n");
    s.ecrire("\t\t<id>"+t.getId()+"</id>\n");
    s.ecrire("\t\t<geo>"+t.getGeo()+"</geo>\n");
    s.ecrire("\t\t<mentions>"+t.getMentions()+"</mentions>\n");
    s.ecrire("\t\t<permalink>"+t.getPermalink()+"</permalink>\n");
    s.ecrire("\t\t<smileys>"+t.getSmileys()+"</smileys>\n");
    s.ecrire("\t\t<polarite>"+t.getPolarite()+"</polarite>\n");
    s.ecrire("\t</tweet>\n");
            
    corpus.ecrire(s.filtrerTexte(t.getText() + "\n"));
    }
    s.ecrire("</tweets>");
            
    s.fermer();*/

    /* SUPER SITE D'EXEMPLES
    https://github.com/yusuke/twitter4j/tree/master/twitter4j-examples/src/main/java/twitter4j/examples*/

    /*PARTIE GRAPHE DES RETWEETS*/
    Set<String> nameOfUsers = new HashSet<>();
    for (int i = 0; i < TweetManager.getTweets(criteria).size(); i++) {
        t = TweetManager.getTweets(criteria).get(i);
        System.out.println(t.getUsername());
        nameOfUsers.add(t.getUsername());
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("gVaO166IGfSCun5Esj1sZ5bX3")
            .setOAuthConsumerSecret("KhN1L4pXCG5U6d6tee1IGUnIV1bqxieQJDxE2HOx3AGI5npQRE")
            .setOAuthAccessToken("822018210178469888-4Pr1KRE2rmFvof0O5IUdTlxtkGKamU4")
            .setOAuthAccessTokenSecret("D1thDl7k8v2s1SupU5ZGhK3U7Mphb69fpUW4JuDou5O65");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter4j.Twitter twitter = tf.getInstance();

    /*String[] screenNames = nameOfUsers.toArray(new String[0]);
    ResponseList<User> usersNames;
    long cursor = -1;
    IDs ids;
    try {
    usersNames = twitter.lookupUsers(screenNames);
    for(User u: usersNames){
        System.out.println(u.getId()+" "+u.getName()+" "+u.getName());
        ids = twitter.getFollowersIDs("username", cursor);
        twitter.getFollowers
    }
                        
            
    } catch (TwitterException ex) {
    Exceptions.printStackTrace(ex);
    }*/

    Set<DuoKey> utilisateurs = new HashSet<>();
    Set<DuoKey> liens = new HashSet<>();

    //User us;

    try {
        int nbpages = 0;
        long cursor = -1;
        PagableResponseList<User> listeFollowersTemp;
        ArrayList<User> listeFollowers = new ArrayList<User>();
        for (String s : nameOfUsers) {
            if (!utilisateurs.contains(new DuoKey(s, "auteurTweet"))) {

                utilisateurs.add(new DuoKey(s, "auteurTweet"));

                //listeFollowersTemp = twitter.getFollowersList(s, -1);
                do {
                    TimeUnit.MINUTES.sleep(1);
                    listeFollowersTemp = twitter.getFollowersList(s, cursor);

                    for (User u : listeFollowersTemp) {
                        listeFollowers.add(u);
                    }
                    nbpages++;
                } while (((cursor = listeFollowersTemp.getNextCursor()) != 0) && nbpages <= 9); //4=100 followers par auteur de tweet recherch
            }
            System.out.println(s + ", mes followers sont :");
            for (User u : listeFollowers) {
                utilisateurs.add(new DuoKey(u.getName(), "auteurTweet"));
                liens.add(new DuoKey(u.getName(), s));
                System.out.println("\t" + u.getName());
            }
            listeFollowers.clear();
            nbpages = 0;
        }
    } catch (TwitterException | InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    }

    Scribe sc = new Scribe();
    sc.detruireFichier("graphFollowers.gexf");
    sc.ouvrir("graphFollowers.gexf");
    sc.ecrire("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    sc.ecrire(
            "<gexf xmlns=\"http://www.gexf.net/1.2draft/gexf.xsd\" version=\"1.2\" xmlns:viz=\"http://www.gexf.net/1.1draft/viz\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd\">\n");
    sc.ecrire("\t<meta lastmodifieddate=\"2017-02-17\">\n");
    sc.ecrire("\t\t<creator>Pirboss</creator>\n");
    sc.ecrire("\t\t<description>Test v2</description>\n");
    sc.ecrire("\t</meta>\n");
    sc.ecrire("\t<graph defaultedgetype=\"directed\" mode=\"static\">\n");
    sc.ecrire("\t\t<nodes>\n");
    ArrayList<DuoKey> distinctListOfUsers = new ArrayList(utilisateurs);
    System.out.println(distinctListOfUsers.size());
    for (int i = 0; i < distinctListOfUsers.size(); i++) {
        sc.ecrire("\t\t\t<node id=\"" + distinctListOfUsers.get(i).getX().replace("&", "&amp;") + "\" label=\""
                + distinctListOfUsers.get(i).getX().replace("&", "&amp;") + "\"/>\n");
    }
    sc.ecrire("\t\t</nodes>\n");
    sc.ecrire("\t\t<edges>\n");
    ArrayList<DuoKey> distinctListOfLinks = new ArrayList(liens);
    System.out.println(distinctListOfLinks.size());
    for (int i = 0; i < liens.size(); i++) {
        sc.ecrire("\t\t\t<edge id=\"" + i + "\" source=\""
                + distinctListOfLinks.get(i).getX().replace("&", "&amp;") + "\" target=\""
                + distinctListOfLinks.get(i).getY().replace("&", "&amp;") + "\"/>\n");
    }

    sc.ecrire("\t\t</edges>\n");
    sc.ecrire("\t</graph>\n");
    sc.ecrire("</gexf>");
    sc.fermer();

    PreviewJFrame p = new PreviewJFrame();
    p.script();

    /*PARTIE GRAPHE DES MENTIONS*/
    //NE PAS OUBLIE LE COUP DE REMPLACER LES .replace("&", "&amp;") POUR LE XML 
    /*Set<String> users = new HashSet<>();
    HashMap<DuoKey, Integer> map;
    map = new HashMap<DuoKey, Integer>();
    DuoKey duokey;
    for (int i = 0; i < TweetManager.getTweets(criteria).size(); i++) {
    System.out.println(i);
    t = TweetManager.getTweets(criteria).get(i);
    users.add(t.getUsername());
    if(!t.getMentions().isEmpty()){
        for(String target : t.getMentions().split(" ")){
            target = target.replaceFirst("@", "");
            users.add(target);
            duokey = new DuoKey(t.getUsername(), target);
            if(map.get(duokey) != null){
                map.put(duokey, map.get(duokey)+1);
            }else{
                map.put(duokey, 1);
            }
        }
    }
    }
            
    Scribe s = new Scribe();
    s.detruireFichier("tweets.gexf");
    s.ouvrir("tweets.gexf");
    s.ecrire("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    s.ecrire("<gexf xmlns=\"http://www.gexf.net/1.2draft/gexf.xsd\" version=\"1.2\" xmlns:viz=\"http://www.gexf.net/1.1draft/viz\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd\">\n");
    s.ecrire("\t<meta lastmodifieddate=\"2017-02-17\">\n");
    s.ecrire("\t\t<creator>Pirboss</creator>\n");
    s.ecrire("\t\t<description>Test v1</description>\n");
    s.ecrire("\t</meta>\n");
    s.ecrire("\t<graph defaultedgetype=\"directed\" mode=\"static\">\n");
    s.ecrire("\t\t<nodes>\n");
    ArrayList distinctList = new ArrayList(users);
    for(int i=0; i<distinctList.size(); i++){
    s.ecrire("\t\t\t<node id=\""+i+"\" label=\""+distinctList.get(i)+"\"/>\n");
    }
    s.ecrire("\t\t</nodes>\n");
    s.ecrire("\t\t<edges>\n");
    Iterator ite = map.entrySet().iterator();
    int jj=0;
    while (ite.hasNext()) {
    Map.Entry pair = (Map.Entry)ite.next();
    s.ecrire("\t\t\t<edge id=\""+(jj++)+"\" source=\""+distinctList.indexOf(((DuoKey)pair.getKey()).getX())+"\" target=\""+distinctList.indexOf(((DuoKey)pair.getKey()).getY())+"\" weight=\""+pair.getValue()+"\"/>\n");
    ite.remove(); // avoids a ConcurrentModificationException
    }
    s.ecrire("\t\t</edges>\n");
    s.ecrire("\t</graph>\n");
    s.ecrire("</gexf>");
    s.fermer();
            
    PreviewJFrame pr = new PreviewJFrame();
    pr.script();*/
}

From source file:tweetcrawling.TweetCrawler.java

public ArrayList<String> getValueToWrite(Status status) {

    // Getting the value to be written

    Long tid = status.getId();/*from www.  j av a  2s.  c  o  m*/
    String tweetid = tid.toString();

    ArrayList<String> valueToWrite = new ArrayList<String>();

    User user = status.getUser();
    String screenname = user.getScreenName();
    String name = user.getName();
    String url = getTweetUrl(screenname, tweetid);

    String body = status.getText().replace("\n", " ");

    valueToWrite.add(body.replace(",", " ")); // element: body
    valueToWrite.add(url); // element: id
    valueToWrite.add(screenname); // element: userid
    valueToWrite.add(name); // element: user

    // element: gender
    if (name != null && !name.isEmpty()) {
        valueToWrite.add(getUserGender(name));
    } else if (screenname != null && !screenname.isEmpty()) {
        valueToWrite.add(getUserGender(screenname));
    } else {
        valueToWrite.add("");
    }

    valueToWrite.add(user.getLocation()); // element: location
    valueToWrite.add("" + user.getFollowersCount()); // element: followercount
    valueToWrite.add("" + user.getFriendsCount()); // element: friendscount
    valueToWrite.add("" + user.getStatusesCount()); // element: statuscount

    try {
        List<String> coor = new ArrayList<String>();
        String latitude = "" + status.getGeoLocation().getLatitude();
        String longitude = "" + status.getGeoLocation().getLongitude();
        coor.add(latitude);
        coor.add(longitude);

        if (coor != null && !coor.isEmpty() && coor.size() > 0) {
            valueToWrite.add(coor.get(0)); // element: latitude
            valueToWrite.add(coor.get(1)); // element: longitude
            valueToWrite.add(coor.get(0) + "," + coor.get(1));
        } else {
            valueToWrite.add(null);
            valueToWrite.add(null);
            valueToWrite.add(null);
        }
    } catch (Exception e) {
        valueToWrite.add(null);
        valueToWrite.add(null);
        valueToWrite.add(null);
    }

    try {

        String geoname = status.getPlace().getName();
        String country = status.getPlace().getCountry();

        if (geoname != null) {
            valueToWrite.add(geoname);
        } else {
            valueToWrite.add(null);
        }

        if (country != null) {
            valueToWrite.add(country);
        } else {
            valueToWrite.add(null);
        }

    } catch (Exception e) {
        valueToWrite.add(null);
        valueToWrite.add(null);
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = status.getCreatedAt();
    valueToWrite.add(dateFormat.format(date)); // element: date
    valueToWrite.add(getDateCrawler()); // element: datecrawler
    valueToWrite.add(status.getInReplyToScreenName()); // element: replyto

    String tooltip = "";
    try {

        String geoname = status.getPlace().getName();
        if (geoname != null) {
            tooltip = "user = " + name + ", geoname = " + geoname;
        }

    } catch (Exception e) {
        tooltip = "";
    }
    valueToWrite.add(tooltip.trim()); // element: tooltip
    valueToWrite.add(SOURCE); // element: source

    return valueToWrite;
}

From source file:tweetcrawling.TweetCrawler.java

public void printTweets(String csvOut) throws IOException, TwitterException {

    for (Status status : getStatuses()) {

        // Getting the value to be written

        Long tid = status.getId();
        String tweetid = tid.toString();

        ArrayList<String> valueToWrite = new ArrayList<String>();

        User user = status.getUser();
        String screenname = user.getScreenName();
        String name = user.getName();
        String url = getTweetUrl(screenname, tweetid);

        valueToWrite.add(url); // element: id
        valueToWrite.add(screenname); // element: userid
        valueToWrite.add(name); // element: user

        // element: gender
        if (name != null && !name.isEmpty()) {
            valueToWrite.add(getUserGender(name));
        } else if (screenname != null && !screenname.isEmpty()) {
            valueToWrite.add(getUserGender(screenname));
        } else {/* www .  j a v a  2  s .c  om*/
            valueToWrite.add("");
        }

        valueToWrite.add(user.getLocation()); // element: location
        valueToWrite.add("" + user.getFollowersCount()); // element: followercount
        valueToWrite.add("" + user.getFriendsCount()); // element: friendscount
        valueToWrite.add("" + user.getStatusesCount()); // element: statuscount

        try {
            List<String> coor = new ArrayList<String>();
            String latitude = "" + status.getGeoLocation().getLatitude();
            String longitude = "" + status.getGeoLocation().getLongitude();
            coor.add(latitude);
            coor.add(longitude);

            if (coor != null && !coor.isEmpty() && coor.size() > 0) {
                valueToWrite.add(coor.get(0)); // element: latitude
                valueToWrite.add(coor.get(1)); // element: longitude
                valueToWrite.add(coor.get(0) + "," + coor.get(1));
            } else {
                valueToWrite.add(null);
                valueToWrite.add(null);
                valueToWrite.add(null);
            }
        } catch (Exception e) {
            valueToWrite.add(null);
            valueToWrite.add(null);
            valueToWrite.add(null);
        }

        try {

            String geoname = status.getPlace().getName();
            String country = status.getPlace().getCountry();

            if (geoname != null) {
                valueToWrite.add(geoname);
            } else {
                valueToWrite.add(null);
            }

            if (country != null) {
                valueToWrite.add(country);
            } else {
                valueToWrite.add(null);
            }

        } catch (Exception e) {
            valueToWrite.add(null);
            valueToWrite.add(null);
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = status.getCreatedAt();
        valueToWrite.add(dateFormat.format(date)); // element: date
        valueToWrite.add(getDateCrawler()); // element: datecrawler
        valueToWrite.add(status.getText()); // element: body
        valueToWrite.add(status.getInReplyToScreenName()); // element: replyto

        String tooltip = "";
        try {

            String geoname = status.getPlace().getName();
            if (geoname != null) {
                tooltip = "user = " + name + ", geoname = " + geoname;
            }

        } catch (Exception e) {
            tooltip = "";
        }
        valueToWrite.add(tooltip.trim()); // element: tooltip
        valueToWrite.add(SOURCE); // element: source

        // Write valueToWrite to csv external file

        FileWriter fw = new FileWriter(csvOut, true);
        PrintWriter pw = new PrintWriter(fw);

        String content = "'";

        for (int i = 0; i < valueToWrite.size() - 1; i++) {
            content += valueToWrite.get(i) + "','";
        }

        content += valueToWrite.get(valueToWrite.size()) + "'";

        pw.print(content);

        pw.flush();
        pw.close();
        fw.close();

    }
}

From source file:twitbak.MentionBak.java

License:Open Source License

public void statusToJson(Status status) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    User poster = status.getUser();
    result.put("Poster ID", poster.getId());
    result.put("Poster", poster.getScreenName());
    result.put("Poster Name", poster.getName());
    result.put("Created At", status.getCreatedAt().toString());
    result.put("ID", status.getId());
    result.put("Text", status.getText());
    long inReplyToStatusId = status.getInReplyToStatusId();
    if (inReplyToStatusId != -1) {
        result.put("In Reply To Status ID", status.getInReplyToStatusId());
    }//from   w w w  .j  a va  2  s .c o m
    long inReplyToUserID = status.getInReplyToUserId();
    result.put("In Reply To User ID", inReplyToUserID);
    if (inReplyToUserID != -1) {
        result.put("In Reply To Screen Name", status.getInReplyToScreenName());
    }
    boolean isFavorited = status.isFavorited();
    if (isFavorited) {
        result.put("Favorited", status.isFavorited());
    }
    statusArray().put(result);
}

From source file:twitbak.TwitBak.java

License:Open Source License

/**
 * Returns a JSONObject containing user data.
 * @param user/* w  w w.ja v  a 2s.c o  m*/
 * @return
 * @throws TwitterException
 * @throws JSONException
 */
//TODO - should be void to match other Bak classes 
static JSONObject userToJson(User user) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    JSONObject userData = new JSONObject();
    userData.put("ID", user.getId());
    userData.put("Screen Name", user.getScreenName());
    userData.put("Name", user.getName());
    userData.put("Description", user.getDescription());
    userData.put("Profile Image URL", user.getProfileImageURL());
    userData.put("URL", user.getURL());
    userData.put("Protected", user.isProtected());
    userData.put("Followers", user.getFollowersCount());
    userData.put("Created At", user.getCreatedAt().toString());
    userData.put("Favorites", user.getFavouritesCount());
    userData.put("Friends", user.getFriendsCount());
    userData.put("Location", user.getLocation());
    userData.put("Statuses", user.getStatusesCount());
    userData.put("Profile Background Color", user.getProfileBackgroundColor());
    userData.put("Profile Background Image URL", user.getProfileBackgroundImageUrl());
    userData.put("Profile Sidebar Border Color", user.getProfileSidebarBorderColor());
    userData.put("Profile Sidebar Fill Color", user.getProfileSidebarFillColor());
    userData.put("Profile Text Color", user.getProfileTextColor());
    userData.put("Time Zone", user.getTimeZone());
    result.put("User data", userData);
    return result;
}

From source file:twitter.metrics.TwitterMetrics.java

/**
 * @param args the command line arguments
 *///  w w  w. j  a  v  a2 s  .com
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 {/*w w  w  . jav a 2s  .co 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:TwitterLookUpUsers.LookupUsers.java

License:Apache License

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

    Postgresql.DBBaglan();//from w ww.  jav  a 2 s .  c om
    Postgresql.DBSelect();
    Twitter twitter = new TwitterFactory().getInstance();

    for (int j = 0; j < sonuc.length; j++) {

        try {
            User user = twitter.showUser(sonuc[j]);
            if (user.getStatus() != null) {
                System.out.println((j + 1) + ". Sorgu___________________________________");
                System.out.println("@" + user.getScreenName());
                System.out.println(user.getTimeZone());
                System.out.println("@" + user.getName());
                System.out.println("@" + user.getURL());
                System.out.println("LOKASYONN  : " + user.getLocation());
                System.out.println("@" + user.getDescription());
                System.out.println("@" + user.getOriginalProfileImageURL());
                System.out.println("@" + user.getMiniProfileImageURL());
                System.out.println("@" + user.getProfileBackgroundImageURL());
                System.out.println("_______________________________________________");

                if (lokasyon[j].contains(user.getLocation()))

                {
                    System.out.println("KULLANICI BU OLABLR*************************");

                }
            } else {

                // the user is protected
                System.out.println((j + 1) + ". Sorgu______________________________________");
                System.out.println("@" + user.getScreenName() + "---- KULLANICI PUBLIC DEL");
                System.out.println("___________________________________________________");
            }

        }

        catch (TwitterException te)

        {
            te.printStackTrace();

            if ((te.getErrorCode() == 88)) {
                System.err.println("EXCEED..............");
                Thread.sleep(900000); //wait 15 min
            }
            System.out.println();

        }

    }

    System.exit(0);
}