Example usage for twitter4j Status getPlace

List of usage examples for twitter4j Status getPlace

Introduction

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

Prototype

Place getPlace();

Source Link

Document

Returns the place attached to this status

Usage

From source file:socialImport.twitter.TweetToDatabaseImportListener.java

License:Open Source License

@Override
public void onStatus(Status status) {
    Date dateOfCreation = status.getCreatedAt();
    String authorName = status.getUser().getName();
    Gender gender = Gender.unknown;//  ww w  .  j  a  v  a 2s .com
    int yearOfBirth = -1;
    Author author = new Author(authorName, gender, yearOfBirth);
    GeoTag geoTag = null;
    Place place = status.getPlace();
    GeoLocation[][] geoLocation = null;
    if (place != null) {
        geoLocation = place.getBoundingBoxCoordinates();
    }
    if (geoLocation != null) {
        float latitude = 0;
        float longitude = 0;
        int noOfCoordinates = geoLocation[0].length;
        for (int i = 0; i < noOfCoordinates; i++) {
            latitude += geoLocation[0][i].getLatitude();
            longitude += geoLocation[0][i].getLongitude();
        }
        latitude = latitude / noOfCoordinates;
        longitude = longitude / noOfCoordinates;
        geoTag = new GeoTag(latitude, longitude);
    }
    String postText = status.getText();
    long retweetCount = status.getRetweetCount();
    TweetPost tweet = new TweetPost(streamDescriptor, dateOfCreation, author, geoTag, postText, retweetCount);
    System.out.println(author);
    System.out.println(geoTag);
    System.out.println(status.getText());
    dataModule.savePost(tweet);

}

From source file:teambootje.TwitterAPI.java

public static void timeline() throws TwitterException, SQLException {
    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query("ssrotterdam");
    query.setCount(100);/*from   w w  w. j ava2  s .c o  m*/
    /**
     ** setSince kan alleen tot 7 dagen terug worden gebruikt***
     */

    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        if (status.getPlace() != null) {
            cityVar = status.getPlace().getName();
            countryVar = status.getPlace().getCountry();
        } else {
            countryVar = null;
            cityVar = null;
        }

        java.util.Date utilDate = status.getCreatedAt();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        date = sqlDate;
        post = status.getText();
        screenName = status.getUser().getScreenName();
        try {
            ImportIntoSQL.TwitterImport();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:testtweet.TweetUsingTwitter4jExample.java

/**
 * @param args the command line arguments
 */// w ww. java  2  s  .c  o  m
public static void main(String[] args) throws IOException, TwitterException {

    //Instantiate a re-usable and thread-safe factory
    TwitterFactory twitterFactory = new TwitterFactory(Data.getConf().build());

    //Instantiate a new Twitter instance
    Twitter twitter = twitterFactory.getInstance();

    /*
    //setup OAuth Consumer Credentials
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
            
    //setup OAuth Access Token
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    */

    //Instantiate and initialize a new twitter status update
    StatusUpdate statusUpdate = new StatusUpdate(
            //your tweet or status message
            "Twitter API #Hacked");
    //attach any media, if you want to
    /*
    statusUpdate.setMedia(
    //title of media
    "http://h1b-work-visa-usa.blogspot.com"
    , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream());
    */
    //tweet or update status
    Status status = twitter.updateStatus(statusUpdate);

    //response from twitter server
    System.out.println("status.toString() = " + status.toString());
    System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
    System.out.println("status.getSource() = " + status.getSource());
    System.out.println("status.getText() = " + status.getText());
    System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
    System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
    System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
    System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
    System.out.println("status.getId() = " + status.getId());
    System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
    System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
    System.out.println("status.getPlace() = " + status.getPlace());
    System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
    System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
    System.out.println("status.getUser() = " + status.getUser());
    System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
    System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
    System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
    if (status.getRateLimitStatus() != null) {
        System.out
                .println("status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
        System.out.println(
                "status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining());
        System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                + status.getRateLimitStatus().getResetTimeInSeconds());
        System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                + status.getRateLimitStatus().getSecondsUntilReset());
        System.out.println("status.getRateLimitStatus().getRemainingHits() = "
                + status.getRateLimitStatus().getRemaining());
    }
    System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
    System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
}

From source file:trendulo.ingest.twitter.USCountryCodeStatusFilter.java

License:Apache License

@Override
public boolean accept(Status status) {

    if (status.getPlace() != null && status.getPlace().getCountryCode() != null
            && status.getPlace().getCountryCode().equals("US")) {
        return true;
    }/*from www  . j a v  a 2 s.  com*/
    return false;

}

From source file:tweetcrawling.TweetCrawler.java

public ArrayList<String> getValueToWrite(Status status) {

    // Getting the value to be written

    Long tid = status.getId();//  w ww  .jav a 2 s. c om
    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();/*from w  ww .  j  a v  a  2  s.  co m*/
        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 {
            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:Twitter.Frame.java

public Document statustoJSON(Status status) {
    Document doc = new Document();
    if (status.getText() != null)
        doc.append("tweet", status.getText());
    if (status.getUser().getName() != null)
        doc.append("name", status.getUser().getName());
    if (status.getPlace() != null)
        doc.append("place", status.getPlace().toString());
    if (status.getUser().getScreenName() != null)
        doc.append("nick", status.getUser().getScreenName());
    if (status.getGeoLocation() != null)
        doc.append("gloc", status.getGeoLocation().toString());
    doc.append("fcont", status.getFavoriteCount());
    doc.append("rcunt", status.getRetweetCount());
    if (status.getRetweetedStatus() != null)
        doc.append("rstate", status.getRetweetedStatus().getText());

    tacol.setText(tacol.getText() + doc.toJson() + "\n");//imprimimos el tweet en el frame
    return doc;//from ww  w  .java  2 s.c  om
}

From source file:twitterapi.TwitterAPI.java

public static void timeline() throws TwitterException, SQLException {
    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query("ssrotterdam");
    query.setCount(100);/*from   ww  w . j a  va2 s . c o  m*/
    /**
     ** setSince kan alleen tot 7 dagen terug worden gebruikt***
     */

    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        String locationCity = null;
        String locationCountry = null;
        if (status.getPlace() != null) {
            cityVar = status.getPlace().getName();
            countryVar = status.getPlace().getCountry();
        } else {
            countryVar = null;
            cityVar = null;
        }

        java.util.Date utilDate = status.getCreatedAt();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        date = sqlDate;
        post = status.getText();
        screenName = status.getUser().getScreenName();
        try {
            ImportIntoSQL.TwitterImport();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

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

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(//from  w  w w .j  a  va2  s .  c o  m
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:TwitterDownload.TwitterExel.java

public static String writeTweets(long ID, List<Status> tweets, String path) {
    try {/*from  w w  w . j  a v a  2s.  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 text = new Label(0, 0, "Tweeted Text");
            Label date = new Label(1, 0, "Tweeted Date");
            Label reTweets = new Label(2, 0, "ReTweet Count");
            Label favor = new Label(3, 0, "Favourite Count");
            Label place = new Label(4, 0, "Place");
            Label geo = new Label(5, 0, "GeoLocation");
            Label link = new Label(6, 0, "Link");
            Label user = new Label(7, 0, "User");

            //Add the created Cells to the sheet
            writableSheet.addCell(text);
            writableSheet.addCell(date);
            writableSheet.addCell(reTweets);
            writableSheet.addCell(favor);
            writableSheet.addCell(place);
            writableSheet.addCell(geo);
            writableSheet.addCell(link);
            writableSheet.addCell(user);

            i = 1;
        }

        for (int j = 0; j < tweets.size(); j++) {
            Status s = tweets.get(j);

            String placeString = s.getPlace() != null ? s.getPlace().toString() : "";
            if (placeString.contains("{"))
                placeString = placeString.substring(placeString.indexOf("{"), placeString.length() - 1);

            Label text = new Label(0, i + j, s.getText());
            DateTime date = new DateTime(1, i + j, s.getCreatedAt());
            Number reTweets = new Number(2, i + j, s.getRetweetCount());
            Number favor = new Number(3, i + j, s.getFavoriteCount());
            Label place = new Label(4, j + 1, placeString);
            Label geo = new Label(5, j + 1, s.getGeoLocation() != null ? s.getGeoLocation().toString() : "");

            String link = "https://twitter.com/" + s.getUser().getScreenName() + "/status/" + s.getId();
            URL url = new URL(link);

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

            Label user = new Label(7, j + 1, s.getUser().getScreenName());

            //Add the created Cells to the sheet
            writableSheet.addCell(text);
            writableSheet.addCell(date);
            writableSheet.addCell(reTweets);
            writableSheet.addCell(favor);
            writableSheet.addCell(place);
            writableSheet.addCell(geo);
            writableSheet.addHyperlink(hl);
            writableSheet.addCell(user);
        }

        //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;
}