Esempio n. 1
0
 /**
  * Transforms a twitter4j.Status object into a JSONObject
  *
  * @param pStatus a twitter4j.Status object
  * @return JSONObject
  */
 @SuppressWarnings("unchecked")
 public static JSONObject getJson(Status pStatus) {
   JSONObject jsonObj = null;
   if (pStatus != null) {
     jsonObj = new JSONObject();
     jsonObj.put("createdAt", pStatus.getCreatedAt());
     jsonObj.put("id", pStatus.getId());
     jsonObj.put("text", pStatus.getText());
     jsonObj.put("source", pStatus.getSource());
     jsonObj.put("isTruncated", pStatus.isTruncated());
     jsonObj.put("inReplyToStatusId", pStatus.getInReplyToStatusId());
     jsonObj.put("inReplyToUserId", pStatus.getInReplyToUserId());
     jsonObj.put("isFavorited", pStatus.isFavorited());
     jsonObj.put("isRetweeted", pStatus.isRetweeted());
     jsonObj.put("favoriteCount", pStatus.getFavoriteCount());
     jsonObj.put("inReplyToScreenName", pStatus.getInReplyToScreenName());
     jsonObj.put("geoLocation", pStatus.getGeoLocation());
     jsonObj.put("place", pStatus.getPlace());
     jsonObj.put("retweetCount", pStatus.getRetweetCount());
     jsonObj.put("isPossiblySensitive", pStatus.isPossiblySensitive());
     jsonObj.put("isoLanguageCode", pStatus.getIsoLanguageCode());
     jsonObj.put("contributorsIDs", pStatus.getContributors());
     jsonObj.put("retweetedStatus", pStatus.getRetweetedStatus());
     jsonObj.put("userMentionEntities", pStatus.getUserMentionEntities());
     jsonObj.put("urlEntities", pStatus.getURLEntities());
     jsonObj.put("hashtagEntities", pStatus.getHashtagEntities());
     jsonObj.put("mediaEntities", pStatus.getMediaEntities());
     jsonObj.put("currentUserRetweetId", pStatus.getCurrentUserRetweetId());
     jsonObj.put("user", pStatus.getUser());
   }
   return jsonObj;
 }
Esempio n. 2
0
  public static Record buildTweet(Schema schema, Status status) {
    GenericRecordBuilder builderTweet = new GenericRecordBuilder(schema);

    builderTweet.set("created_at", status.getCreatedAt().getTime());
    builderTweet.set("favorite_count", status.getFavoriteCount());
    builderTweet.set("favorited", status.isFavorited());
    builderTweet.set("id", status.getId());
    builderTweet.set("in_reply_to_screen_name", status.getInReplyToScreenName());
    if (status.getInReplyToStatusId() != -1)
      builderTweet.set("in_reply_to_status_id", status.getInReplyToStatusId());
    if (status.getInReplyToUserId() != -1)
      builderTweet.set("in_reply_to_user_id", status.getInReplyToUserId());
    builderTweet.set("lang", status.getLang());
    builderTweet.set("possibly_sensitive", status.isPossiblySensitive());
    builderTweet.set("retweet_count", status.getRetweetCount());
    builderTweet.set("retweeted", status.isRetweeted());
    builderTweet.set("source", status.getSource());
    builderTweet.set("text", status.getText());
    builderTweet.set("truncated", status.isTruncated());
    if (status.getWithheldInCountries() != null)
      builderTweet.set("withheld_in_countries", Arrays.asList(status.getWithheldInCountries()));
    if (status.getGeoLocation() != null)
      builderTweet.set(
          "coordinates",
          Arrays.asList(
              status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));

    builderTweet.set("entities", buildEntities(schema.getField("entities").schema(), status));

    if (status.getPlace() != null)
      builderTweet.set(
          "place",
          buildPlace(schema.getField("place").schema().getTypes().get(1), status.getPlace()));

    User user = status.getUser();
    if (user != null && schema.getField("user") != null) {
      Schema schemaUser = schema.getField("user").schema();
      GenericRecordBuilder builderUser = new GenericRecordBuilder(schemaUser);
      builderUser.set("contributors_enabled", user.isContributorsEnabled());
      builderUser.set("created_at", user.getCreatedAt().getTime());
      builderUser.set("default_profile", user.isDefaultProfile());
      builderUser.set("default_profile_image", user.isDefaultProfileImage());
      builderUser.set("description", user.getDescription());
      builderUser.set(
          "entities",
          buildURLEntity(schemaUser.getField("entities").schema(), user.getURLEntity()));
      builderUser.set("favourites_count", user.getFavouritesCount());
      builderUser.set("followers_count", user.getFollowersCount());
      builderUser.set("friends_count", user.getFriendsCount());
      builderUser.set("geo_enabled", user.isGeoEnabled());
      builderUser.set("id", user.getId());
      builderUser.set("is_translator", user.isTranslator());
      builderUser.set("lang", user.getLang());
      builderUser.set("listed_count", user.getListedCount());
      builderUser.set("location", user.getLocation());
      builderUser.set("name", user.getName());
      builderUser.set("screen_name", user.getScreenName());
      builderUser.set("profile_background_color", user.getProfileBackgroundColor());
      builderUser.set("profile_background_image_url", user.getProfileBackgroundImageURL());
      builderUser.set(
          "profile_background_image_url_https", user.getProfileBackgroundImageUrlHttps());
      builderUser.set("profile_background_tile", user.isProfileBackgroundTiled());
      builderUser.set("profile_banner_url", user.getProfileBannerURL());
      builderUser.set("profile_image_url", user.getProfileImageURL());
      builderUser.set("profile_image_url_https", user.getProfileBackgroundImageUrlHttps());
      builderUser.set("profile_link_color", user.getProfileLinkColor());
      builderUser.set("profile_sidebar_border_color", user.getProfileSidebarBorderColor());
      builderUser.set("profile_sidebar_fill_color", user.getProfileSidebarFillColor());
      builderUser.set("profile_text_color", user.getProfileTextColor());
      builderUser.set("profile_use_background_image", user.isProfileUseBackgroundImage());
      builderUser.set("protected", user.isProtected());
      builderUser.set("show_all_inline_media", user.isShowAllInlineMedia());
      builderUser.set("statuses_count", user.getStatusesCount());
      builderUser.set("time_zone", user.getTimeZone());
      builderUser.set("url", user.getURL());
      builderUser.set("utc_offset", user.getUtcOffset());
      builderUser.set("verified", user.isVerified());
      if (user.getStatus() != null && schemaUser.getField("status") != null)
        builderUser.set(
            "status",
            buildTweet(schemaUser.getField("status").schema().getTypes().get(1), user.getStatus()));
      if (user.getWithheldInCountries() != null)
        builderUser.set("withheld_in_countries", Arrays.asList(user.getWithheldInCountries()));
      builderTweet.set("user", builderUser.build());
    }

    if (status.getQuotedStatus() != null && schema.getField("quoted_status") != null)
      builderTweet.set(
          "quoted_status",
          buildTweet(
              schema.getField("quoted_status").schema().getTypes().get(1),
              status.getQuotedStatus()));

    if (status.getRetweetedStatus() != null && schema.getField("retweeted_status") != null)
      builderTweet.set(
          "retweeted_status",
          buildTweet(
              schema.getField("retweeted_status").schema().getTypes().get(1),
              status.getRetweetedStatus()));

    return builderTweet.build();
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("GetFriendUpdates: enter");
    String user = request.getParameter("user");
    String group = request.getParameter("gid");
    String session = request.getParameter("session");
    String pageStr = request.getParameter("page");
    int page = 1;
    if (pageStr != null) {
      page = Integer.parseInt(pageStr);
    }

    String tweetIdStr = request.getParameter("tweetId");
    long tweetId = 0;
    if (tweetIdStr != null && tweetIdStr.length() > 0) {
      tweetId = Long.parseLong(tweetIdStr);
    }

    int userId = 0;
    int groupId = 0;
    if (user != null) {
      userId = Integer.parseInt(user);
    }

    if (group != null) {
      groupId = Integer.parseInt(group);
    }

    System.out.println(
        "GetFriendUpdates: userId:" + userId + ", groupId: " + groupId + ", session: " + session);

    /*
     * Set the content type(MIME Type) of the response.
     */
    response.setContentType("application/json");

    PrintWriter out = response.getWriter();

    DB db = new DB();
    AccessToken accessToken = db.isSessionValid(userId, groupId, session);
    if (userId == 0 || groupId == 0 || session.equals("") || accessToken == null) {
      out.print("{ success: false, \"msg\": \"Authentication failed.\"};");
      out.close();
      System.out.println("GetFriendUpdates: exit(false)");
      return;
    }

    Twitter twitter = new TwitterFactory().getInstance();
    Properties prop = TwitterProperties.getProperties();
    twitter.setOAuthConsumer(prop.getProperty("consumer.key"), prop.getProperty("consumer.secret"));
    twitter.setOAuthAccessToken(accessToken);

    int newTweetCount = 0;
    int oldTweetCount = 0;
    String tweetJSON = "[";
    int newPage = page;

    try {
      long oldTweetId = getLastReadTweet(userId);
      long newTweetId = oldTweetId;
      int i = 0;

      while (true) {
        System.out.println("Getting page: " + page);
        ResponseList<Status> tweets = twitter.getHomeTimeline(new Paging(page, 20));
        for (Status status : tweets) {
          Status retweetStatus = status.getRetweetedStatus();
          User tweetUser = status.getUser();
          long currentTweetId = status.getId();
          if (tweetId == 0 || (tweetId > 0 && tweetId < currentTweetId)) {
            if (i > 0) {
              tweetJSON += ",";
            }
            tweetJSON += "{ " + "\"id\": \"" + currentTweetId + "\",";
            if (retweetStatus != null) {
              tweetJSON +=
                  "\"text\": \""
                      + Constants.escape(retweetStatus.getText())
                      + "\","
                      + "\"date\": \""
                      + Constants.getTimeStr(retweetStatus.getCreatedAt())
                      + "\","
                      + "\"user\": \""
                      + Constants.escape(retweetStatus.getUser().getScreenName())
                      + "\","
                      + "\"src\": \""
                      + Constants.escape(retweetStatus.getSource())
                      + "\","
                      + "\"img\": \""
                      + Constants.escape(retweetStatus.getUser().getProfileImageURL().toString())
                      + "\","
                      + "\"RT\":\""
                      + tweetUser.getScreenName()
                      + "\","
                      + "\"RID\": \""
                      + retweetStatus.getId()
                      + "\",";
              if (retweetStatus.isFavorited()) {
                tweetJSON += "\"favorite\":true,";
              } else {
                tweetJSON += "\"favorite\":false,";
              }

            } else {
              tweetJSON +=
                  "\"text\": \""
                      + Constants.escape(status.getText())
                      + "\","
                      + "\"date\": \""
                      + Constants.getTimeStr(status.getCreatedAt())
                      + "\","
                      + "\"user\": \""
                      + Constants.escape(tweetUser.getScreenName())
                      + "\","
                      + "\"src\": \""
                      + Constants.escape(status.getSource())
                      + "\","
                      + "\"img\": \""
                      + Constants.escape(tweetUser.getProfileImageURL().toString())
                      + "\","
                      + "\"RT\": \"\",";
              if (status.isFavorited()) {
                tweetJSON += "\"favorite\":true,";
              } else {
                tweetJSON += "\"favorite\":false,";
              }
            }

            if (oldTweetId >= currentTweetId) {
              //							System.out.println("Old tweet: " + currentTweetId + "(" + oldTweetId + ")");
              tweetJSON += "\"old\":true}";
              oldTweetCount++;
            } else {
              newTweetCount++;
              //							System.out.println("New tweet: " + currentTweetId + "(" + oldTweetId + ")");
              if (newTweetId < currentTweetId) {
                newTweetId = currentTweetId;
              }
              tweetJSON += "\"old\":false}";
            }
            i++;
          }
        }

        System.out.println("newTweetCount: " + newTweetCount + ", oldTweetCount: " + oldTweetCount);
        if (oldTweetCount == 0 && newTweetCount > 0 && page < 5) {
          page++;
        } else {
          break;
        }
      }

      System.out.println("Old tweet: " + oldTweetId + ", new Tweet: " + newTweetId);
      if (newTweetId > oldTweetId) {
        updateLastReadTweet(userId, newTweetId);
      }
      /* test-data when internet is not UP */
      //		tweetJSON += "{ " +
      //		"\"text\": \"This is a test tweet.\"," +
      //		"\"date\": \"31-12-2009\"," +
      //		"\"user\": \"ammubhai\"," +
      //		"\"src\": \"echofone\"," +
      //		"\"img\": \"images/user1.png\"" +
      //		"}";
    } catch (TwitterException e) {
      //		e.printStackTrace();
      //			System.err.println("ERROR: " + e.getLocalizedMessage());
      //			String errText = e.getMessage();
      //			int index = errText.indexOf("<!DOCTYPE ");
      //			String errorMsg = errText.substring(0, index - 1);
      //			errorMsg = errorMsg.replaceAll("(\r\n|\r|\n|\n\r)", "");
      out.print(
          "{\"success\": false, \"msg\": \""
              + TwitterError.getErrorMessage(e.getStatusCode())
              + "\"}");
      out.close();
      return;
    }
    tweetJSON += "]";

    out.print(
        "{ \"success\": true,"
            + "\"page\": "
            + newPage
            + ","
            + "\"result\": "
            + tweetJSON
            + ","
            + "\"count\": "
            + newTweetCount
            + " }");
    out.close();
    System.out.println("GetFriendUpdates(" + userId + "): exit(true)");
    return;
  }