コード例 #1
0
 public static void main(String[] args) throws TwitterException, IOException {
   Twitter twitter = TwitterFactory.getSingleton();
   JLanguageTool langTool = new JLanguageTool(new AmericanEnglish());
   List<String> twts = new ArrayList<String>();
   for (String arg : args) {
     Query query = new Query(arg);
     QueryResult result;
     int counter = 0;
     do {
       result = twitter.search(query);
       List<Status> tweets = result.getTweets();
       for (Status tweet : tweets) {
         if (isEligible(tweet)) {
           System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
           System.out.println(tweet.getLang());
           twts.add(tweet.getText());
           counter++;
         }
       }
     } while ((query = result.nextQuery()) != null && counter < 5);
   }
   for (String str : twts) {
     List<RuleMatch> matches = langTool.check(str);
     for (RuleMatch match : matches) {
       System.out.println(
           "Potential error at line "
               + match.getLine()
               + ", column "
               + match.getColumn()
               + ": "
               + match.getMessage());
       System.out.println("Suggested correction: " + match.getSuggestedReplacements());
     }
   }
 }
コード例 #2
0
 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());
 }
コード例 #3
0
 public List<User> getFollowing(int num) {
   try {
     List<User> b = new ArrayList<User>();
     for (twitter4j.User u : twitter.getFriendsList(twitter.verifyCredentials().getId(), -1)) {
       b.add(new TwitterUser(u));
     }
     return b;
   } catch (TwitterException e) {
     e.printStackTrace();
     return null;
   }
 }
コード例 #4
0
  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;
  }
コード例 #5
0
  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);
  }
コード例 #6
0
  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
 private static List<List<List<Double>>> getPlaceCoordinates(GeoLocation[][] geoLocations) {
   List<List<List<Double>>> listListListBoundingBox = new ArrayList<>();
   for (GeoLocation[] geoLocation1 : geoLocations) {
     List<List<Double>> listListBoundingBox = new ArrayList<>();
     for (GeoLocation geoLocation2 : geoLocation1) {
       List<Double> listBoundingBox = new ArrayList<>();
       listBoundingBox.add(geoLocation2.getLatitude());
       listBoundingBox.add(geoLocation2.getLongitude());
       listListBoundingBox.add(listBoundingBox);
     }
     listListListBoundingBox.add(listListBoundingBox);
   }
   return listListListBoundingBox;
 }
コード例 #8
0
        /**
         * Called when the user's friends list has arrived
         *
         * @param users The user's friends (by Twitter definition)
         */
        @Override
        public void gotFriendsList(PagableResponseList<User> users) {
          SoomlaUtils.LogDebug(TAG, "getContacts/onComplete " + users.size());

          List<UserProfile> userProfiles = new ArrayList<UserProfile>();
          for (User profile : users) {
            userProfiles.add(createUserProfile(profile));
          }
          if (users.hasNext()) {
            lastContactCursor = users.getNextCursor();
          }
          RefContactsListener.success(userProfiles, users.hasNext());
          clearListener(ACTION_GET_CONTACTS);
        }
コード例 #9
0
    public List<User> getFollowers() {
      try {
        List<User> ls = new ArrayList<User>();

        for (twitter4j.User u : twitter.getFollowersList(user.getId(), -1)) {
          ls.add(new TwitterUser(u));
        }

        return ls;
      } catch (TwitterException e) {
        e.printStackTrace();
        return null;
      }
    }
コード例 #10
0
 public void testDirectMessagesAsJSON() throws Exception {
   HttpClientImpl http = new HttpClientImpl();
   List<DirectMessage> directMessages =
       DirectMessageJSONImpl.createDirectMessageList(
           http.get("http://twitter4j.org/en/testcases/direct_messages.json"), conf);
   DirectMessage dm = directMessages.get(0);
   Assert.assertEquals(new java.util.Date(1248177356000l), dm.getCreatedAt());
   Assert.assertEquals(6358482, dm.getRecipient().getId());
   Assert.assertEquals(246928323, dm.getId());
   Assert.assertEquals(6358482, dm.getRecipientId());
   Assert.assertEquals("twit4j", dm.getRecipientScreenName());
   Assert.assertEquals(6377362, dm.getSender().getId());
   Assert.assertEquals(6377362, dm.getSenderId());
   Assert.assertEquals("twit4j2", dm.getSenderScreenName());
   Assert.assertEquals("Tue Jul 21 20:55:39 KST 2009:directmessage test", dm.getText());
   assertDeserializedFormIsEqual(directMessages);
 }
コード例 #11
0
  public void insertFollowers(List<User> users) {
    try {
      String noti =
          ActivityDataSource.getInstance(context).insertNewFollowers(users, currentAccount);
      notificationItems.add(noti);
    } catch (Throwable t) {

    }
  }
コード例 #12
0
  public void insertMentions(List<Status> mentions) {
    try {
      List<String> notis =
          ActivityDataSource.getInstance(context).insertMentions(mentions, currentAccount);
      notificationItems.addAll(notis);
    } catch (Throwable t) {

    }
  }
コード例 #13
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);
        }
コード例 #14
0
 public void testStatusAsJSON() throws Exception {
   // single Status
   HttpClientImpl http = new HttpClientImpl();
   List<Status> statuses =
       StatusJSONImpl.createStatusList(
           http.get("http://twitter4j.org/en/testcases/statuses/public_timeline.json"), conf);
   Status status = statuses.get(0);
   Assert.assertEquals(new Date(1259041785000l), status.getCreatedAt());
   Assert.assertEquals(6000554383l, status.getId());
   Assert.assertEquals("G_Shock22", status.getInReplyToScreenName());
   Assert.assertEquals(6000444309l, status.getInReplyToStatusId());
   Assert.assertEquals(20159829, status.getInReplyToUserId());
   Assert.assertNull(status.getGeoLocation());
   Assert.assertEquals("web", status.getSource());
   Assert.assertEquals(
       "@G_Shock22 I smelled a roast session coming when yu said that shyt about @2koolNicia lol....",
       status.getText());
   Assert.assertEquals(23459577, status.getUser().getId());
   Assert.assertFalse(status.isRetweet());
   assertDeserializedFormIsEqual(statuses);
 }
コード例 #15
0
  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;
  }
コード例 #16
0
  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.");
  }
コード例 #17
0
  public boolean tryInsertFavorites(Status status) {
    try {
      String noti =
          ActivityDataSource.getInstance(context).insertFavoriters(status, currentAccount);

      if (noti != null) {
        notificationItems.add(noti);
        return true;
      } else {
        return false;
      }
    } catch (Throwable t) {
      return false;
    }
  }
コード例 #18
0
  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));
  }
コード例 #19
0
  private static Record buildEntities(Schema schemaEntities, Status status) {
    GenericRecordBuilder builderEntities = new GenericRecordBuilder(schemaEntities);

    if (status.getHashtagEntities().length > 0) {
      Schema schemaHashtagObject = schemaEntities.getField("hashtags").schema().getElementType();
      List<GenericRecord> listHashtagObjects = new ArrayList<>();
      for (HashtagEntity hashtagEntity : status.getHashtagEntities()) {
        GenericRecordBuilder builderHashtagObject = new GenericRecordBuilder(schemaHashtagObject);
        builderHashtagObject.set("text", hashtagEntity.getText());
        builderHashtagObject.set("start", hashtagEntity.getStart());
        builderHashtagObject.set("end", hashtagEntity.getEnd());
        listHashtagObjects.add(builderHashtagObject.build());
      }
      builderEntities.set("hashtags", listHashtagObjects);
    } else builderEntities.set("hashtags", Collections.emptyList());

    if (status.getSymbolEntities().length > 0) {
      Schema schemaSymbolObject = schemaEntities.getField("symbols").schema().getElementType();
      List<GenericRecord> listSymbolObject = new ArrayList<>();
      for (SymbolEntity symbolEntity : status.getSymbolEntities()) {
        GenericRecordBuilder builderSymbolObject = new GenericRecordBuilder(schemaSymbolObject);
        builderSymbolObject.set("text", symbolEntity.getText());
        builderSymbolObject.set("start", symbolEntity.getStart());
        builderSymbolObject.set("end", symbolEntity.getEnd());
        listSymbolObject.add(builderSymbolObject.build());
      }
      builderEntities.set("symbols", listSymbolObject);
    } else builderEntities.set("symbols", Collections.emptyList());

    if (status.getMediaEntities().length > 0) {
      Schema schemaMediaObject = schemaEntities.getField("media").schema().getElementType();
      List<GenericRecord> listMediaObject = new ArrayList<>();
      for (MediaEntity mediaEntity : status.getMediaEntities()) {
        GenericRecordBuilder builderMediaObject = new GenericRecordBuilder(schemaMediaObject);
        builderMediaObject.set("url", mediaEntity.getURL());
        builderMediaObject.set("display_url", mediaEntity.getDisplayURL());
        builderMediaObject.set("expanded_url", mediaEntity.getExpandedURL());
        builderMediaObject.set("id", mediaEntity.getId());
        builderMediaObject.set("media_url", mediaEntity.getMediaURL());
        builderMediaObject.set("media_url_https", mediaEntity.getMediaURLHttps());
        builderMediaObject.set("type", mediaEntity.getType());
        builderMediaObject.set("text", mediaEntity.getText());
        builderMediaObject.set("start", mediaEntity.getStart());
        builderMediaObject.set("end", mediaEntity.getEnd());

        Schema schemaSize = schemaMediaObject.getField("sizes").schema().getValueType();
        GenericRecordBuilder builderSize = new GenericRecordBuilder(schemaSize);
        Map<String, GenericRecord> mapSizes = new HashMap<>(4);
        for (int key : mediaEntity.getSizes().keySet()) {
          Size size = mediaEntity.getSizes().get(key);
          builderSize.set("h", size.getHeight());
          builderSize.set("w", size.getWidth());
          builderSize.set("resize", size.getResize());
          mapSizes.put(Integer.toString(key), builderSize.build());
        }
        builderMediaObject.set("sizes", mapSizes);
        listMediaObject.add(builderMediaObject.build());
      }
      builderEntities.set("media", listMediaObject);
    } else builderEntities.set("media", Collections.emptyList());

    if (status.getURLEntities().length > 0) {
      Schema schemaURLObject = schemaEntities.getField("urls").schema().getElementType();
      List<GenericRecord> listURLObject1 = new ArrayList<>();
      for (URLEntity urlEntity : status.getURLEntities())
        listURLObject1.add(buildURLEntity(schemaURLObject, urlEntity));
      builderEntities.set("urls", listURLObject1);
    } else builderEntities.set("urls", Collections.emptyList());

    if (status.getUserMentionEntities().length > 0) {
      Schema schemaUserMentionObject =
          schemaEntities.getField("user_mentions").schema().getElementType();
      List<GenericRecord> listUserMentionObject = new ArrayList<>();
      for (UserMentionEntity userMentionEntity : status.getUserMentionEntities()) {
        GenericRecordBuilder builderUserMentionObject =
            new GenericRecordBuilder(schemaUserMentionObject);
        builderUserMentionObject.set("name", userMentionEntity.getName());
        builderUserMentionObject.set("screen_name", userMentionEntity.getScreenName());
        builderUserMentionObject.set("text", userMentionEntity.getText());
        builderUserMentionObject.set("id", userMentionEntity.getId());
        builderUserMentionObject.set("start", userMentionEntity.getStart());
        builderUserMentionObject.set("end", userMentionEntity.getEnd());
        listUserMentionObject.add(builderUserMentionObject.build());
      }
      builderEntities.set("user_mentions", listUserMentionObject);
    } else builderEntities.set("user_mentions", Collections.emptyList());

    if (status.getExtendedMediaEntities().length > 0) {
      Schema schemaExtendedMediaObject =
          schemaEntities.getField("extended_entities").schema().getElementType();
      List<GenericRecord> listExtendedMediaObject = new ArrayList<>();
      for (ExtendedMediaEntity extendedMediaEntity : status.getExtendedMediaEntities()) {
        GenericRecordBuilder builderExtendedMediaObject =
            new GenericRecordBuilder(schemaExtendedMediaObject);
        builderExtendedMediaObject.set("url", extendedMediaEntity.getURL());
        builderExtendedMediaObject.set("display_url", extendedMediaEntity.getDisplayURL());
        builderExtendedMediaObject.set("expanded_url", extendedMediaEntity.getExpandedURL());
        builderExtendedMediaObject.set("id", extendedMediaEntity.getId());
        builderExtendedMediaObject.set("media_url", extendedMediaEntity.getMediaURL());
        builderExtendedMediaObject.set("media_url_https", extendedMediaEntity.getMediaURLHttps());
        builderExtendedMediaObject.set("type", extendedMediaEntity.getType());
        builderExtendedMediaObject.set("text", extendedMediaEntity.getText());
        builderExtendedMediaObject.set("start", extendedMediaEntity.getStart());
        builderExtendedMediaObject.set("end", extendedMediaEntity.getEnd());

        Schema schemaSize = schemaExtendedMediaObject.getField("sizes").schema().getValueType();
        GenericRecordBuilder builderSize = new GenericRecordBuilder(schemaSize);
        Map<String, GenericRecord> mapSizes = new HashMap<>(4);
        for (int key : extendedMediaEntity.getSizes().keySet()) {
          Size size = extendedMediaEntity.getSizes().get(key);
          builderSize.set("h", size.getHeight());
          builderSize.set("w", size.getWidth());
          builderSize.set("resize", size.getResize());
          mapSizes.put(Integer.toString(key), builderSize.build());
        }
        builderExtendedMediaObject.set("sizes", mapSizes);

        Schema schemaVideoInfo = schemaExtendedMediaObject.getField("video_info").schema();
        GenericRecordBuilder builderVideoInfo = new GenericRecordBuilder(schemaVideoInfo);
        builderVideoInfo.set("h", extendedMediaEntity.getVideoAspectRatioHeight());
        builderVideoInfo.set("w", extendedMediaEntity.getVideoAspectRatioWidth());
        builderVideoInfo.set("duration_millis", extendedMediaEntity.getVideoDurationMillis());

        Schema schemaVideoVariants = schemaVideoInfo.getField("variants").schema().getElementType();
        List<GenericRecord> listVideoVariants = new ArrayList<>();
        for (Variant extendedVideoVariant : extendedMediaEntity.getVideoVariants()) {
          GenericRecordBuilder builderVideoVariant = new GenericRecordBuilder(schemaVideoVariants);
          builderVideoVariant.set("bitrate", extendedVideoVariant.getBitrate());
          builderVideoVariant.set("content_type", extendedVideoVariant.getContentType());
          builderVideoVariant.set("url", extendedVideoVariant.getUrl());
          listVideoVariants.add(builderVideoVariant.build());
        }
        builderVideoInfo.set("variants", listVideoVariants);
        builderExtendedMediaObject.set("video_info", builderVideoInfo.build());

        listExtendedMediaObject.add(builderExtendedMediaObject.build());
      }
      builderEntities.set("extended_entities", listExtendedMediaObject);
    } else builderEntities.set("extended_entities", Collections.emptyList());
    return builderEntities.build();
  }
コード例 #20
0
  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());
  }
コード例 #21
0
  private static JSONObject validateJSONObjectSchema(JSONObject json, String[] knownNames)
      throws JSONException {
    boolean debug = false;
    Map<String, String[]> schemaMap = new HashMap<String, String[]>();
    List<String> names = new ArrayList<String>();
    if (debug) {
      System.out.println("validating:" + json);
    }
    for (int i = 0; i < knownNames.length; i++) {
      if (debug) {
        System.out.println("knownName[" + i + "]:" + knownNames[i]);
      }
      String knownName = knownNames[i];
      int index;
      if (-1 != (index = knownName.indexOf("/"))) {
        String parent = knownName.substring(0, index);
        String child = knownName.substring(index + 1);
        String[] array = schemaMap.get(parent);
        if (null == array) {
          schemaMap.put(parent, new String[] {child});
        } else {
          String[] newArray = new String[array.length + 1];
          System.arraycopy(array, 0, newArray, 0, array.length);
          newArray[newArray.length - 1] = child;
          schemaMap.put(parent, newArray);
        }
        names.add(parent);
      } else {
        names.add(knownName);
      }
    }

    Iterator ite = json.keys();
    while (ite.hasNext()) {
      String name = (String) ite.next();
      boolean found = false;
      if (debug) {
        System.out.println("name:" + name);
      }
      for (String elementName : names) {
        if (debug) {
          System.out.println("elementname:" + elementName);
        }
        Object obj = json.get(name);
        if (obj instanceof JSONObject || obj instanceof JSONArray) {
          String[] children = schemaMap.get(name);
          if (null == children) {
            Assert.fail(
                elementName + ":" + name + " is not supposed to have any child but has:" + obj);
          } else if (!children[0].equals("*")) {
            validateJSONSchema(obj, children);
          }
        }
        if (elementName.equals(name)) {
          found = true;
          break;
        }
      }
      if (!found) {
        Assert.fail("unknown element:[" + name + "] in " + json);
      }
    }
    return json;
  }
コード例 #22
0
  public void testPlaceAsJSON() throws Exception {
    List<Place> places =
        PlaceJSONImpl.createPlaceList(
            getJSONObjectFromClassPath("/dao/reverse-geocode.json")
                .getJSONObject("result")
                .getJSONArray("places"),
            null,
            conf);
    Place place = places.get(0);
    Assert.assertEquals("SoMa", place.getName());
    Assert.assertEquals("US", place.getCountryCode());
    Assert.assertEquals("2b6ff8c22edd9576", place.getId());
    Assert.assertEquals("", place.getCountry());
    Assert.assertEquals("neighborhood", place.getPlaceType());
    Assert.assertEquals("http://api.twitter.com/1/geo/id/2b6ff8c22edd9576.json", place.getURL());
    Assert.assertEquals("SoMa, San Francisco", place.getFullName());
    Assert.assertEquals("Polygon", place.getBoundingBoxType());
    GeoLocation[][] boundingBox = place.getBoundingBoxCoordinates();
    Assert.assertEquals(1, boundingBox.length);
    Assert.assertEquals(4, boundingBox[0].length);
    Assert.assertEquals(37.76893497, boundingBox[0][0].getLatitude());
    Assert.assertEquals(-122.42284884, boundingBox[0][0].getLongitude());
    Assert.assertEquals(37.76893497, boundingBox[0][1].getLatitude());
    Assert.assertEquals(-122.3964, boundingBox[0][1].getLongitude());
    Assert.assertEquals(37.78752897, boundingBox[0][2].getLatitude());
    Assert.assertEquals(-122.3964, boundingBox[0][2].getLongitude());
    Assert.assertEquals(37.78752897, boundingBox[0][3].getLatitude());
    Assert.assertEquals(-122.42284884, boundingBox[0][3].getLongitude());
    Assert.assertNull(place.getGeometryType());
    Assert.assertNull(place.getGeometryCoordinates());

    Place[] containedWithinArray = place.getContainedWithIn();
    Assert.assertEquals(1, containedWithinArray.length);
    Place containedWithin = containedWithinArray[0];
    Assert.assertNull(containedWithin.getContainedWithIn());
    Assert.assertEquals("San Francisco", containedWithin.getName());
    Assert.assertEquals("US", containedWithin.getCountryCode());
    Assert.assertEquals("5a110d312052166f", containedWithin.getId());
    Assert.assertEquals("", containedWithin.getCountry());
    Assert.assertEquals("city", containedWithin.getPlaceType());
    Assert.assertEquals(
        "http://api.twitter.com/1/geo/id/5a110d312052166f.json", containedWithin.getURL());
    Assert.assertEquals("San Francisco", containedWithin.getFullName());
    boundingBox = containedWithin.getBoundingBoxCoordinates();
    Assert.assertEquals("Polygon", place.getBoundingBoxType());
    Assert.assertEquals(1, boundingBox.length);
    Assert.assertEquals(4, boundingBox[0].length);
    Assert.assertEquals(37.70813196, boundingBox[0][0].getLatitude());
    Assert.assertEquals(-122.51368188, boundingBox[0][0].getLongitude());
    Assert.assertEquals(37.70813196, boundingBox[0][1].getLatitude());
    Assert.assertEquals(-122.35845384, boundingBox[0][1].getLongitude());
    Assert.assertEquals(37.83245301, boundingBox[0][2].getLatitude());
    Assert.assertEquals(-122.35845384, boundingBox[0][2].getLongitude());
    Assert.assertEquals(37.83245301, boundingBox[0][3].getLatitude());
    Assert.assertEquals(-122.51368188, boundingBox[0][3].getLongitude());

    Assert.assertNull(place.getGeometryType());
    Assert.assertNull(place.getGeometryCoordinates());

    place = new PlaceJSONImpl(getJSONObjectFromClassPath("/dao/5a110d312052166f.json"), null);
    Assert.assertNotNull(place.getGeometryType());
    Assert.assertNotNull(place.getGeometryCoordinates());

    // Test that a geo object with geometry type "Point" works.
    place = new PlaceJSONImpl(getJSONObjectFromClassPath("/dao/3c6797665e2d42eb.json"), null);
    Assert.assertEquals(place.getGeometryType(), "Point");
    Assert.assertNotNull(place.getGeometryCoordinates());

    place = new PlaceJSONImpl(getJSONObjectFromClassPath("/dao/c3f37afa9efcf94b.json"), null);
    // MultiPolygon is not supported by twitter4j yet, so we set geometryType to null
    Assert.assertNull(place.getGeometryType());
    Assert.assertNull(place.getGeometryCoordinates());
  }