public boolean getMentions(Twitter twitter) {
    boolean newActivity = false;

    try {
      if (lastRefresh != 0l) {
        Paging paging = new Paging(1, 50, lastRefresh);
        List<Status> mentions = twitter.getMentionsTimeline(paging);

        if (mentions.size() > 0) {
          insertMentions(mentions);
          commitLastRefresh(mentions.get(0).getId());
          newActivity = true;
        }
      } else {
        Paging paging = new Paging(1, 1);
        List<Status> lastMention = twitter.getMentionsTimeline(paging);

        if (lastMention.size() > 0) {
          commitLastRefresh(lastMention.get(0).getId());
        }
      }
    } catch (TwitterException e) {
      e.printStackTrace();
    }

    return newActivity;
  }
  public void testEmptyJSON() throws Exception {
    HttpClientImpl http = new HttpClientImpl();

    // empty User list
    List<User> users =
        UserJSONImpl.createUserList(
            http.get("http://twitter4j.org/en/testcases/statuses/friends/T4J_hudson.json"), conf);
    Assert.assertTrue(users.size() == 0);
    assertDeserializedFormIsEqual(users);

    // empty Status list
    List<Status> statuses =
        StatusJSONImpl.createStatusList(
            http.get("http://twitter4j.org/en/testcases/statuses/friends/T4J_hudson.json"), conf);
    Assert.assertTrue(statuses.size() == 0);
    assertDeserializedFormIsEqual(statuses);

    // empty DirectMessages list
    List<DirectMessage> directMessages =
        DirectMessageJSONImpl.createDirectMessageList(
            http.get("http://twitter4j.org/en/testcases/statuses/friends/T4J_hudson.json"), conf);
    Assert.assertTrue(directMessages.size() == 0);
    assertDeserializedFormIsEqual(directMessages);

    // empty Trends list
    List<Trends> trends =
        TrendsJSONImpl.createTrendsList(
            http.get("http://twitter4j.org/en/testcases/trends/daily-empty.json"),
            conf.isJSONStoreEnabled());
    Assert.assertTrue(trends.size() == 0);
    assertDeserializedFormIsEqual(trends);
  }
  public boolean getFollowers(Twitter twitter) {
    boolean newActivity = false;

    try {
      List<User> followers =
          twitter.getFollowersList(
              useSecondAccount
                  ? AppSettings.getInstance(context).secondScreenName
                  : AppSettings.getInstance(context).myScreenName,
              -1,
              200);
      User me = twitter.verifyCredentials();

      int oldFollowerCount = sharedPrefs.getInt("activity_follower_count_" + currentAccount, 0);
      Set<String> latestFollowers =
          sharedPrefs.getStringSet(
              "activity_latest_followers_" + currentAccount, new HashSet<String>());

      Log.v(TAG, "followers set size: " + latestFollowers.size());
      Log.v(TAG, "old follower count: " + oldFollowerCount);
      Log.v(TAG, "current follower count: " + me.getFollowersCount());

      List<User> newFollowers = new ArrayList<User>();
      if (latestFollowers.size() != 0) {
        for (int i = 0; i < followers.size(); i++) {
          if (!latestFollowers.contains(followers.get(i).getScreenName())) {
            Log.v(TAG, "inserting @" + followers.get(i).getScreenName() + " as new follower");
            newFollowers.add(followers.get(i));
            newActivity = true;
          } else {
            break;
          }
        }
      }

      insertFollowers(newFollowers);

      latestFollowers.clear();
      for (int i = 0; i < 50; i++) {
        if (i < followers.size()) {
          latestFollowers.add(followers.get(i).getScreenName());
        } else {
          break;
        }
      }

      SharedPreferences.Editor e = sharedPrefs.edit();
      e.putStringSet("activity_latest_followers_" + currentAccount, latestFollowers);
      e.putInt("activity_follower_count_" + currentAccount, me.getFollowersCount());
      e.commit();
    } catch (TwitterException e) {
      e.printStackTrace();
    }

    return newActivity;
  }
 public void testCategoryAsJSON() throws Exception {
   List<Category> categories =
       CategoryJSONImpl.createCategoriesList(
           getJSONArrayFromClassPath("/dao/suggestions.json"), null, conf);
   Assert.assertEquals(20, categories.size());
   Assert.assertEquals("art-design", categories.get(0).getSlug());
   Assert.assertEquals("Art & Design", categories.get(0).getName());
   Assert.assertTrue(0 < categories.get(0).getSize());
 }
  public void grab(Date timeLimit) {
    log.info("Twitter grabber started...");
    Twitter twitter = new TwitterFactory().getInstance();

    List<Brand> brandList = handler.getBrandProvider().getAllBrands();
    ArticleProvider articleProvider = handler.getArticleProvider();

    for (Brand b : brandList) {
      Query query = new Query(b.getName());
      query.setRpp(PAGE_SIZE);
      query.setLang("ru");
      query.setResultType(Query.MIXED);

      List<Tweet> resultTweets = new LinkedList<Tweet>();
      QueryResult queryResult;
      int pageNumber = 1;

      try {
        do {
          query.setPage(pageNumber);
          queryResult = twitter.search(query);
          resultTweets.addAll(queryResult.getTweets());
          pageNumber++;
          log.info(pageNumber);
        } while (ISSUANCE_SIZE > resultTweets.size());
      } catch (TwitterException e) {
        throw new RuntimeException(e);
      }
      log.info("tweets in da111y: " + resultTweets.size());
      twitter = null;
      twitter = new TwitterFactory().getInstance();

      for (Tweet t : resultTweets) {
        articleProvider.writeArticleToDataStore(
            new Article(-1, b.getId(), 2, "", t.getText(), "", getSimpleTime(t.getCreatedAt()), 1));
      }
    }
    log.info("twitter grabber finished succesful.");
  }
  public void testUserAsJSON() throws Exception {
    // single User
    HttpClientWrapper http = new HttpClientWrapper();
    JSONObject json = getJSONObjectFromClassPath("/dao/user.json");
    User user = new UserJSONImpl(json);
    Assert.assertTrue(user.isGeoEnabled());
    Assert.assertFalse(user.isVerified());
    Assert.assertEquals(id1.screenName, user.getName());
    Assert.assertEquals(id1.screenName, user.getScreenName());
    Assert.assertNotNull(user.getLocation());
    Assert.assertNotNull(user.getDescription());
    Assert.assertNotNull(user.getProfileImageURL());
    Assert.assertNotNull(user.getURL());
    Assert.assertFalse(user.isProtected());

    Assert.assertTrue(0 <= user.getFavouritesCount());
    Assert.assertTrue(0 <= user.getFollowersCount());
    Assert.assertTrue(0 <= user.getFriendsCount());
    Assert.assertNotNull(user.getCreatedAt());
    Assert.assertNotNull(user.getTimeZone());
    Assert.assertNotNull(user.getProfileBackgroundImageURL());

    Assert.assertTrue(0 <= user.getStatusesCount());
    Assert.assertNotNull(user.getProfileBackgroundColor());
    Assert.assertNotNull(user.getProfileTextColor());
    Assert.assertNotNull(user.getProfileLinkColor());
    Assert.assertNotNull(user.getProfileSidebarBorderColor());
    Assert.assertNotNull(user.getProfileSidebarFillColor());
    Assert.assertNotNull(user.getProfileTextColor());

    Assert.assertTrue(1 < user.getFollowersCount());
    Assert.assertNotNull(user.getStatus().getCreatedAt());
    Assert.assertNotNull(user.getStatus().getText());
    Assert.assertNotNull(user.getStatus().getSource());
    Assert.assertFalse(user.getStatus().isFavorited());
    Assert.assertEquals(-1, user.getStatus().getInReplyToStatusId());
    Assert.assertEquals(-1, user.getStatus().getInReplyToUserId());
    Assert.assertFalse(user.getStatus().isFavorited());
    Assert.assertNull(user.getStatus().getInReplyToScreenName());
    assertDeserializedFormIsEqual(user);
    Assert.assertTrue(0 <= user.getListedCount());
    List<User> users;

    // User list
    users =
        UserJSONImpl.createUserList(
            http.get("http://twitter4j.org/en/testcases/statuses/followers/T4J_hudson.json"), conf);
    Assert.assertTrue(users.size() > 0);
    assertDeserializedFormIsEqual(users);
  }
Пример #7
0
        /**
         * Called when the user's timeline has arrived
         *
         * @param statuses The user's latest statuses
         */
        @Override
        public void gotUserTimeline(ResponseList<Status> statuses) {
          SoomlaUtils.LogDebug(TAG, "getFeed/onComplete");

          List<String> feeds = new ArrayList<String>();
          for (Status post : statuses) {
            feeds.add(post.getText());
          }

          boolean hasMore;
          if (feeds.size() >= PAGE_SIZE) {
            lastFeedCursor++;
            hasMore = true;
          } else {
            lastFeedCursor = 1;
            hasMore = false;
          }
          RefFeedListener.success(feeds, hasMore);
          clearListener(ACTION_GET_FEED);
        }
  public void testSchema() throws Exception {
    String[] schema;
    String url;

    //        JSONObject json = new
    // JSONObject("{\"a\":\"avalue\",\"b\":\"bvalue\",\"c\":{\"c-1\":12,\"c-2\":\"c-2value\"}}");
    //        schema = new String[]{"a", "b", "c/c-1", "c/c-2"};
    //        validateJSONObjectSchema(json, schema);
    //        try {
    //            schema = new String[]{"a", "b", "c/c-1"};
    //            validateJSONObjectSchema(json, schema);
    //            fail("c/c-2 is missing. expecting an AssertionFailedError.");
    //        } catch (AssertionFailedError ignore) {
    ////            ignore.printStackTrace();
    //        }
    //        try {
    //            schema = new String[]{"a", "b"};
    //            validateJSONObjectSchema(json, schema);
    //            fail("c is missing. expecting an AssertionFailedError.");
    //        } catch (AssertionFailedError ignore) {
    ////            ignore.printStackTrace();
    //        }
    //        try {
    //            schema = new String[]{"a", "b","c"};
    //            validateJSONObjectSchema(json, schema);
    //            fail("c/* is missing. expecting an AssertionFailedError.");
    //        } catch (AssertionFailedError ignore) {
    ////            ignore.printStackTrace();
    //        }
    //        schema = new String[]{"a", "b", "c/*"};
    //        validateJSONObjectSchema(json, schema);
    //
    //        JSONArray array = new JSONArray("[{\"slug\":\"art-design\",\"name\":\"Art &
    // Design\"},{\"slug\":\"books\",\"name\":\"Books\"}]");
    //        schema = new String[]{"slug", "name"};
    //        validateJSONArraySchema(array, schema);

    // Location

    //        schema = new
    // String[]{"url","country","woeid","placeType/name","placeType/code","name","countryCode"};
    //        url = "http://api.twitter.com/1.1/trends/available.json";
    //        validateJSONArraySchema(url, schema);
    // Place
    if (!Boolean.valueOf(System.getProperties().getProperty("twitter4j.test.schema"))) {
      // skipping schema validation
      return;
    }

    schema =
        new String[] {
          "slug", "name", "size",
        };
    url = "http://api.twitter.com/1.1/users/suggestions.json";
    List categories =
        CategoryJSONImpl.createCategoriesList(validateJSONArraySchema(url, schema), null, conf);
    Assert.assertEquals(20, categories.size());

    schema = new String[] {"slug", "name", "size", "categories/*", "users/*"};
    url = "http://api.twitter.com/1.1/users/suggestions/art-design.json";
    validateJSONObjectSchema(url, schema);

    schema =
        new String[] {
          "result/places/name",
          "result/places/street_address",
          "result/places/attributes/*",
          "result/places/country_code",
          "result/places/id",
          "result/places/country",
          "result/places/place_type",
          "result/places/url",
          "result/places/full_name",
          "result/places/bounding_box/*",
          "result/places/contained_within/place_type",
          "result/places/contained_within/attributes/*",
          "result/places/contained_within/street_address",
          "result/places/contained_within/url",
          "result/places/contained_within/bounding_box/type",
          "result/places/contained_within/bounding_box/coordinates/*",
          "result/places/contained_within/full_name",
          "result/places/contained_within/country_code",
          "result/places/contained_within/name",
          "result/places/contained_within/id",
          "result/places/contained_within/country",
          "query",
          "query/type",
          "query/url",
          "query/params",
          "query/params/granularity",
          "query/params/coordinates",
          "query/params/coordinates/type",
          "query/params/coordinates/coordinates",
          "query/params/coordinates/coordinates/*",
          "query/params/accuracy",
        };
    url = "http://api.twitter.com/1.1/geo/reverse_geocode.json?lat=37.78215&long=-122.40060";
    validateJSONObjectSchema(url, schema);

    schema =
        new String[] {
          "next_cursor",
          "next_cursor_str",
          "previous_cursor",
          "previous_cursor_str",
          "lists/id",
          "lists/id_str",
          "lists/member_count",
          "lists/description",
          "lists/name",
          "lists/subscriber_count",
          "lists/slug",
          "lists/user/*",
          "lists/uri",
          "lists/full_name",
          "lists/mode",
          "lists/following",
        };
    url = "http://api.twitter.com/1.1/twit4j2/lists.json";
    validateJSONObjectSchema(url, schema);

    schema =
        new String[] {
          "id",
          "id_str",
          "member_count",
          "description",
          "name",
          "subscriber_count",
          "slug",
          "user/*",
          "uri",
          "full_name",
          "mode",
          "following",
        };
    url = "http://api.twitter.com/1.1/twit4j2/lists/9499823.json";
    UserList userList = new UserListJSONImpl(validateJSONObjectSchema(url, schema));
    Assert.assertEquals("", userList.getDescription());
    Assert.assertEquals("@twit4j2/test", userList.getFullName());
    Assert.assertEquals(9499823, userList.getId());
    Assert.assertTrue(1 < userList.getMemberCount());
    Assert.assertEquals("test", userList.getName());
    Assert.assertEquals("test", userList.getSlug());
    Assert.assertEquals(0, userList.getSubscriberCount());
    Assert.assertEquals("/twit4j2/test", userList.getURI().toString());
    Assert.assertNotNull(userList.getUser());
    Assert.assertTrue(userList.isPublic());
    Assert.assertFalse(userList.isFollowing());

    schema =
        new String[] {
          "favorited",
          "in_reply_to_status_id",
          "in_reply_to_status_id_str",
          "created_at",
          "geo",
          "place",
          "source",
          "in_reply_to_screen_name",
          "in_reply_to_user_id",
          "in_reply_to_user_id_str",
          "coordinates",
          "truncated",
          "contributors",
          "id",
          "id_str",
          "text",
          "user/*",
          "retweeted",
          "retweet_count"
        };
    url = "http://api.twitter.com/1.1/statuses/show/2245071380.json";
    Status status = new StatusJSONImpl(validateJSONObjectSchema(url, schema));

    schema =
        new String[] {
          "profile_background_image_url",
          "created_at",
          "friends_count",
          "profile_link_color",
          "description",
          "contributors_enabled",
          "status/*",
          "following",
          "profile_background_tile",
          "favourites_count",
          "profile_sidebar_fill_color",
          "url",
          "profile_image_url",
          "geo_enabled",
          "notifications",
          "profile_sidebar_border_color",
          "location",
          "screen_name",
          "verified",
          "time_zone",
          "profile_background_color",
          "profile_use_background_image",
          "protected",
          "name",
          "profile_text_color",
          "followers_count",
          "id",
          "id_str",
          "lang",
          "statuses_count",
          "follow_request_sent",
          "utc_offset",
          "listed_count",
          "is_translator",
          "show_all_inline_media"
        };

    url = "http://api.twitter.com/1.1/users/show/yusukey.json";
    User user = new UserJSONImpl(validateJSONObjectSchema(url, schema));
  }
  public void postNotification(int id) {

    if (notificationItems.size() == 0) {
      return;
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setContentTitle(notificationTitle);
    mBuilder.setSmallIcon(R.drawable.ic_stat_icon);
    mBuilder.setLargeIcon(
        BitmapFactory.decodeResource(
            context.getResources(), R.drawable.ic_action_notification_dark));

    if (notificationItems.size() > 1) {
      // inbox style
      NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();

      try {
        inbox.setBigContentTitle(notificationTitle);
      } catch (Exception e) {

      }

      if (notificationItems.size() <= 5) {
        for (String s : notificationItems) {
          inbox.addLine(Html.fromHtml(s));
        }
      } else {
        for (int i = 0; i < 5; i++) {
          inbox.addLine(Html.fromHtml(notificationItems.get(i)));
        }

        int extra = notificationItems.size() - 5;
        if (extra > 1) {
          inbox.setSummaryText("+" + extra + " " + context.getString(R.string.items));
        } else {
          inbox.setSummaryText("+" + extra + " " + context.getString(R.string.item));
        }
      }

      mBuilder.setStyle(inbox);
      mBuilder.setContentText(notificationItems.size() + " " + context.getString(R.string.items));
    } else {
      // big text style
      NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
      bigText.bigText(Html.fromHtml(notificationItems.get(0)));
      bigText.setBigContentTitle(notificationTitle);

      mBuilder.setStyle(bigText);
      mBuilder.setContentText(Html.fromHtml(notificationItems.get(0)));
    }

    if (!useSecondAccount) {
      mBuilder.setContentIntent(
          PendingIntent.getActivity(context, 0, new Intent(context, RedirectToActivity.class), 0));
    }

    if (settings.vibrate) {
      mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
      try {
        mBuilder.setSound(Uri.parse(settings.ringtone));
      } catch (Exception e) {
        mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
      }
    }

    if (settings.led) {
      mBuilder.setLights(0xFFFFFF, 1000, 1000);
    }

    if (settings.wakeScreen) {
      PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
      final PowerManager.WakeLock wakeLock =
          pm.newWakeLock(
              (PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                  | PowerManager.FULL_WAKE_LOCK
                  | PowerManager.ACQUIRE_CAUSES_WAKEUP),
              "TAG");
      wakeLock.acquire(5000);
    }

    // Pebble notification
    if (sharedPrefs.getBoolean("pebble_notification", false)) {
      NotificationUtils.sendAlertToPebble(context, notificationTitle, notificationItems.get(0));
    }

    // Light Flow notification
    NotificationUtils.sendToLightFlow(context, notificationTitle, notificationItems.get(0));

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    notificationManager.notify(id, mBuilder.build());
  }