Java Code Examples for com.annimon.stream.Stream

The following examples show how to use com.annimon.stream.Stream. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@WorkerThread
private Optional<StickerManifestResult> getManifestRemote(@NonNull String packId, @NonNull String packKey) {
  try {
    byte[]                       packIdBytes    = Hex.stringToBytes(packId);
    byte[]                       packKeyBytes   = Hex.stringToBytes(packKey);
    SignalServiceStickerManifest remoteManifest = receiver.retrieveStickerManifest(packIdBytes, packKeyBytes);
    StickerManifest              localManifest  = new StickerManifest(packId,
                                                                      packKey,
                                                                      remoteManifest.getTitle(),
                                                                      remoteManifest.getAuthor(),
                                                                      toOptionalSticker(packId, packKey, remoteManifest.getCover()),
                                                                      Stream.of(remoteManifest.getStickers())
                                                                            .map(s -> toSticker(packId, packKey, s))
                                                                            .toList());

    return Optional.of(new StickerManifestResult(localManifest, false));
  } catch (IOException | InvalidMessageException e) {
    Log.w(TAG, "Failed to retrieve pack manifest.", e);
  }

  return Optional.absent();
}
 
Example 2
Source Project: Lightweight-Stream-API   Source File: OfNullableTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStreamOfNullableMap() {
    Map<Integer, String> t = null;
    assertThat(Stream.ofNullable(t), isEmpty());

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(1, 2);
    map.put(3, 4);
    Stream.ofNullable(map)
            .flatMap(new Function<Map.Entry<Integer, Integer>, Stream<Integer>>() {
                @Override
                public Stream<Integer> apply(Map.Entry<Integer, Integer> e) {
                    return Stream.of(e.getKey(), e.getValue());
                }
            })
            .custom(assertElements(contains(1, 2, 3, 4)));
}
 
Example 3
@WorkerThread
synchronized void submitNewJobChain(@NonNull List<List<Job>> chain) {
  chain = Stream.of(chain).filterNot(List::isEmpty).toList();

  if (chain.isEmpty()) {
    Log.w(TAG, "Tried to submit an empty job chain. Skipping.");
    return;
  }

  if (chainExceedsMaximumInstances(chain)) {
    Job solo = chain.get(0).get(0);
    jobTracker.onStateChange(solo, JobTracker.JobState.IGNORED);
    Log.w(TAG, JobLogger.format(solo, "Already at the max instance count of " + solo.getParameters().getMaxInstances() + ". Skipping."));
    return;
  }

  insertJobChain(chain);
  scheduleJobs(chain.get(0));
  triggerOnSubmit(chain);
  notifyAll();
}
 
Example 4
Source Project: Lightweight-Stream-API   Source File: MapToIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapToInt() {
    final ToIntFunction<String> stringToSquareInt = new ToIntFunction<String>() {
        @Override
        public int applyAsInt(String t) {
            final String str = t.substring(1, t.length() - 1);
            final int value = Integer.parseInt(str);
            return value * value;
        }
    };

    Stream.of("[2]", "[3]", "[4]", "[8]", "[25]")
            .mapToInt(stringToSquareInt)
            .custom(assertElements(arrayContaining(
                    4, 9, 16, 64, 625
            )));
}
 
Example 5
Source Project: Lightweight-Stream-API   Source File: MapToIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapToInt() {
    final ToIntFunction<String> stringToSquareInt = new ToIntFunction<String>() {
        @Override
        public int applyAsInt(String t) {
            final String str = t.substring(1, t.length() - 1);
            final int value = Integer.parseInt(str);
            return value * value;
        }
    };

    Stream.of("[2]", "[3]", "[4]", "[8]", "[25]")
            .mapToInt(stringToSquareInt)
            .custom(assertElements(arrayContaining(
                    4, 9, 16, 64, 625
            )));
}
 
Example 6
@Override
protected Boolean doInBackground(Void... params) {
    try {
        String originalJson = JSONUtils.getFileContent(JSONUtils.JSON_LINK);

        final JSONUtils.XposedJson xposedJson = new Gson().fromJson(originalJson, JSONUtils.XposedJson.class);

        tabs = Stream.of(xposedJson.tabs)
                .filter(value -> value.sdks.contains(Build.VERSION.SDK_INT)).toList();

        noZips = tabs.isEmpty();
        newApkVersion = xposedJson.apk.version;
        newApkLink = xposedJson.apk.link;
        newApkChangelog = xposedJson.apk.changelog;

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, "AdvancedInstallerFragment -> " + e.getMessage());
        return false;
    }
}
 
Example 7
/**
 * @return The list of all dependent jobs that should also be failed.
 */
@WorkerThread
synchronized @NonNull List<Job> onFailure(@NonNull Job job) {
  List<Job> dependents = Stream.of(jobStorage.getDependencySpecsThatDependOnJob(job.getId()))
                               .map(DependencySpec::getJobId)
                               .map(jobStorage::getJobSpec)
                               .withoutNulls()
                               .map(jobSpec -> {
                                 List<ConstraintSpec> constraintSpecs = jobStorage.getConstraintSpecs(jobSpec.getId());
                                 return createJob(jobSpec, constraintSpecs);
                               })
                               .toList();

  List<Job> all = new ArrayList<>(dependents.size() + 1);
  all.add(job);
  all.addAll(dependents);

  jobStorage.deleteJobs(Stream.of(all).map(Job::getId).toList());
  Stream.of(all).forEach(j -> jobTracker.onStateChange(j, JobTracker.JobState.FAILURE));

  return dependents;
}
 
Example 8
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
  SignalExecutors.BOUNDED.execute(() -> {
    MessageRecord record = isMms ? DatabaseFactory.getMmsDatabase(appContext).readerFor(data).getNext()
                                 : DatabaseFactory.getSmsDatabase(appContext).readerFor(data).getNext();

    if (record == null) {
      internalLiveData.postValue(Collections.emptyList());
    } else {
      internalLiveData.postValue(Stream.of(record.getReactions())
                                       .map(reactionRecord -> new Reaction(Recipient.resolved(reactionRecord.getAuthor()),
                                                                           reactionRecord.getEmoji(),
                                                                           reactionRecord.getDateReceived()))
                                       .toList());
    }
  });
}
 
Example 9
Source Project: Lightweight-Stream-API   Source File: MapIndexedTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapIndexed() {
    Stream.rangeClosed(4, 8)
            .mapIndexed(new IndexedFunction<Integer, Integer>() {
                @Override
                public Integer apply(int index, Integer t) {
                    return index * t;
                }
            })
            .custom(assertElements(contains(
                   0,  // (0 * 4)
                   5,  // (1 * 5)
                   12, // (2 * 6)
                   21, // (3 * 7)
                   32  // (4 * 8)
            )));
}
 
Example 10
private static Optional<List<LinkPreview>> getLinkPreviews(Optional<List<Preview>> previews, @NonNull String message) {
  if (!previews.isPresent()) return Optional.absent();

  List<LinkPreview> linkPreviews = new ArrayList<>(previews.get().size());

  for (Preview preview : previews.get()) {
    Optional<Attachment> thumbnail     = PointerAttachment.forPointer(preview.getImage());
    Optional<String>     url           = Optional.fromNullable(preview.getUrl());
    Optional<String>     title         = Optional.fromNullable(preview.getTitle());
    boolean              hasContent    = !TextUtils.isEmpty(title.or("")) || thumbnail.isPresent();
    boolean              presentInBody = url.isPresent() && Stream.of(LinkPreviewUtil.findWhitelistedUrls(message)).map(Link::getUrl).collect(Collectors.toSet()).contains(url.get());
    boolean              validDomain   = url.isPresent() && LinkPreviewUtil.isWhitelistedLinkUrl(url.get());

    if (hasContent && presentInBody && validDomain) {
      LinkPreview linkPreview = new LinkPreview(url.get(), title.or(""), thumbnail);
      linkPreviews.add(linkPreview);
    } else {
      Log.w(TAG, String.format("Discarding an invalid link preview. hasContent: %b presentInBody: %b validDomain: %b", hasContent, presentInBody, validDomain));
    }
  }

  return Optional.of(linkPreviews);
}
 
Example 11
public static DialogFragment create(boolean includeClear, boolean includeCamera, short requestCode, boolean isGroup) {
  DialogFragment        fragment         = new AvatarSelectionBottomSheetDialogFragment();
  List<SelectionOption> selectionOptions = new ArrayList<>(3);
  Bundle                args             = new Bundle();

  if (includeCamera) {
    selectionOptions.add(SelectionOption.CAPTURE);
  }

  selectionOptions.add(SelectionOption.GALLERY);

  if (includeClear) {
    selectionOptions.add(SelectionOption.DELETE);
  }

  String[] options = Stream.of(selectionOptions)
                           .map(SelectionOption::getCode)
                           .toArray(String[]::new);

  args.putStringArray(ARG_OPTIONS, options);
  args.putShort(ARG_REQUEST_CODE, requestCode);
  args.putBoolean(ARG_IS_GROUP, isGroup);
  fragment.setArguments(args);

  return fragment;
}
 
Example 12
Source Project: Lightweight-Stream-API   Source File: CollectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCollectWithSupplierAndAccumulator() {
    String text = Stream.of("a", "b", "c", "def", "", "g")
            .collect(Functions.stringBuilderSupplier(), Functions.joiningAccumulator())
            .toString();
    assertEquals("abcdefg", text);
}
 
Example 13
Source Project: Hentoid   Source File: Preferences.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Site> getActiveSites() {
    String siteCodesStr = sharedPreferences.getString(Key.ACTIVE_SITES, Default.ACTIVE_SITES) + "";
    if (siteCodesStr.isEmpty()) return Collections.emptyList();

    List<String> siteCodes = Arrays.asList(siteCodesStr.split(","));
    return Stream.of(siteCodes).map(s -> Site.searchByCode(Long.valueOf(s))).toList();
}
 
Example 14
@TargetApi(26)
@WorkerThread
public static synchronized void ensureCustomChannelConsistency(@NonNull Context context) {
  if (!supported()) {
    return;
  }
  Log.d(TAG, "ensureCustomChannelConsistency()");

  NotificationManager notificationManager = ServiceUtil.getNotificationManager(context);
  RecipientDatabase   db                  = DatabaseFactory.getRecipientDatabase(context);
  List<Recipient>     customRecipients    = new ArrayList<>();
  Set<String>         customChannelIds    = new HashSet<>();

  try (RecipientDatabase.RecipientReader reader = db.getRecipientsWithNotificationChannels()) {
    Recipient recipient;
    while ((recipient = reader.getNext()) != null) {
      customRecipients.add(recipient);
      customChannelIds.add(recipient.getNotificationChannel());
    }
  }

  Set<String> existingChannelIds  = Stream.of(notificationManager.getNotificationChannels()).map(NotificationChannel::getId).collect(Collectors.toSet());

  for (NotificationChannel existingChannel : notificationManager.getNotificationChannels()) {
    if (existingChannel.getId().startsWith(CONTACT_PREFIX) && !customChannelIds.contains(existingChannel.getId())) {
      Log.i(TAG, "Consistency: Deleting channel '"+ existingChannel.getId() + "' because the DB has no record of it.");
      notificationManager.deleteNotificationChannel(existingChannel.getId());
    } else if (existingChannel.getId().startsWith(MESSAGES_PREFIX) && !existingChannel.getId().equals(getMessagesChannel(context))) {
      Log.i(TAG, "Consistency: Deleting channel '"+ existingChannel.getId() + "' because it's out of date.");
      notificationManager.deleteNotificationChannel(existingChannel.getId());
    }
  }

  for (Recipient customRecipient : customRecipients) {
    if (!existingChannelIds.contains(customRecipient.getNotificationChannel())) {
      Log.i(TAG, "Consistency: Removing custom channel '"+ customRecipient.getNotificationChannel() + "' because the system doesn't have it.");
      db.setNotificationChannel(customRecipient.getId(), null);
    }
  }
}
 
Example 15
Source Project: Lightweight-Stream-API   Source File: StreamMatcher.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> Function<Stream<T>, Void> assertHasElements() {
    return new Function<Stream<T>, Void>() {

        @Override
        public Void apply(Stream<T> t) {
            assertThat(t, hasElements());
            return null;
        }
    };
}
 
Example 16
Source Project: Lightweight-Stream-API   Source File: TakeWhileTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTakeWhile() {
    Stream.of(2, 4, 6, 7, 8, 10, 11)
            .takeWhile(Functions.remainder(2))
            .custom(assertElements(contains(
                    2, 4, 6
            )));
}
 
Example 17
@Test
public void testDropWhileIndexedWithStartAndStep() {
    Stream.of(1, 2, 3, 4, -5, -6, -7)
            .dropWhileIndexed(2, 2, new IndexedPredicate<Integer>() {
                @Override
                public boolean test(int index, Integer value) {
                    return (index + value) < 10;
                }
            })
            .custom(assertElements(contains(
                    4, -5, -6, -7
            )));
}
 
Example 18
public Collection<ContactData> getContactsWithPush(Context context) {
  final ContentResolver resolver = context.getContentResolver();
  final String[] inProjection    = new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME};

  final List<String>           registeredAddresses = Stream.of(DatabaseFactory.getRecipientDatabase(context).getRegistered())
                                                            .map(Recipient::resolved)
                                                            .filter(r -> r.getE164().isPresent())
                                                            .map(Recipient::requireE164)
                                                            .toList();
  final Collection<ContactData> lookupData          = new ArrayList<>(registeredAddresses.size());

  for (String registeredAddress : registeredAddresses) {
    Uri    uri          = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(registeredAddress));
    Cursor lookupCursor = resolver.query(uri, inProjection, null, null, null);

    try {
      if (lookupCursor != null && lookupCursor.moveToFirst()) {
        final ContactData contactData = new ContactData(lookupCursor.getLong(0), lookupCursor.getString(1));
        contactData.numbers.add(new NumberData("TextSecure", registeredAddress));
        lookupData.add(contactData);
      }
    } finally {
      if (lookupCursor != null)
        lookupCursor.close();
    }
  }

  return lookupData;
}
 
Example 19
Source Project: Lightweight-Stream-API   Source File: SampleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSampleWithStep1() {
    Stream.of(      1, 2, 3, 1, 2, 3, 1, 2, 3)
            .sample(1)
            .custom(assertElements(contains(
                    1, 2, 3, 1, 2, 3, 1, 2, 3
            )));
}
 
Example 20
public static void showHome(BottomNavigationView navigationView) {
    removeAll(navigationView);
    Stream.of(
            map.get(R.id.navigation_blog_post),
            map.get(R.id.navigation_project),
            map.get(R.id.navigation_box)
    ).forEach(menu ->
            navigationView.getMenu().add(R.id.navigationDrawer, menu.id, menu.order, menu.stringId).setIcon(menu.iconRes));
}
 
Example 21
Source Project: Lightweight-Stream-API   Source File: WithoutNullsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWithoutNulls() {
    Stream.range(0, 10)
            .map(new Function<Integer, String>() {
                @Override
                public String apply(Integer integer) {
                    return integer % 3 == 0 ? null : integer.toString();
                }
            })
            .withoutNulls()
            .custom(assertElements(contains(
                    "1", "2", "4", "5", "7", "8"
            )));
}
 
Example 22
Source Project: Lightweight-Stream-API   Source File: FlatMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFlatMap() {
    Stream.rangeClosed(2, 4)
            .flatMap(new Function<Integer, Stream<String>>() {

                @Override
                public Stream<String> apply(final Integer i) {
                    return Stream.rangeClosed(2, 4)
                            .filter(Functions.remainder(2))
                            .map(new Function<Integer, String>() {

                                @Override
                                public String apply(Integer p) {
                                    return String.format("%d * %d = %d", i, p, (i*p));
                                }
                            });
                }
            })
            .custom(assertElements(contains(
                    "2 * 2 = 4",
                    "2 * 4 = 8",
                    "3 * 2 = 6",
                    "3 * 4 = 12",
                    "4 * 2 = 8",
                    "4 * 4 = 16"
            )));
}
 
Example 23
Source Project: Lightweight-Stream-API   Source File: SkipTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipMoreThanCountAndLimit() {
    Stream.range(0, 10)
            .skip(15)
            .limit(8)
            .custom(StreamMatcher.<Integer>assertIsEmpty());
}
 
Example 24
public static IssueRequestModel clone(@NonNull Issue issue, boolean toClose) {
    IssueRequestModel model = new IssueRequestModel();
    if (issue.getLabels() != null) {
        model.setLabels(Stream.of(issue.getLabels()).filter(value -> value.getName() != null)
                .map(Label::getName).collect(Collectors.toList()));
    }
    model.setAssignee(issue.getAssignee() != null ? issue.getAssignee().getLogin() : null);
    model.setBody(issue.getBody());
    model.setMilestone(issue.getMilestone() != null ? issue.getMilestone().getNumber() : null);
    model.setState(toClose ? issue.getState().equalsIgnoreCase(IssueState.CLOSED)
            ? IssueState.OPEN : IssueState.CLOSED : issue.getState());
    model.setTitle(issue.getTitle());
    return model;
}
 
Example 25
@Override
public void onRun() throws Exception {
  if (!TextSecurePreferences.isTypingIndicatorsEnabled(context)) {
    return;
  }

  Log.d(TAG, "Sending typing " + (typing ? "started" : "stopped") + " for thread " + threadId);

  Recipient recipient = DatabaseFactory.getThreadDatabase(context).getRecipientForThreadId(threadId);

  if (recipient == null) {
    Log.w(TAG, "Tried to send a typing indicator to a non-existent thread.");
    return;
  }

  if (recipient.isBlocked()) {
    Log.w(TAG, "Not sending typing indicators to blocked recipients.");
  }

  List<Recipient>  recipients = Collections.singletonList(recipient);
  Optional<byte[]> groupId    = Optional.absent();

  if (recipient.isGroup()) {
    recipients = DatabaseFactory.getGroupDatabase(context).getGroupMembers(recipient.requireGroupId(), GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
    groupId    = Optional.of(recipient.requireGroupId().getDecodedId());
  }

  recipients = Stream.of(recipients).map(Recipient::resolve).toList();

  SignalServiceMessageSender             messageSender      = ApplicationDependencies.getSignalServiceMessageSender();
  List<SignalServiceAddress>             addresses          = Stream.of(recipients).map(r -> RecipientUtil.toSignalServiceAddress(context, r)).toList();
  List<Optional<UnidentifiedAccessPair>> unidentifiedAccess = Stream.of(recipients).map(r -> UnidentifiedAccessUtil.getAccessFor(context, r)).toList();
  SignalServiceTypingMessage             typingMessage      = new SignalServiceTypingMessage(typing ? Action.STARTED : Action.STOPPED, System.currentTimeMillis(), groupId);

  messageSender.sendTyping(addresses, unidentifiedAccess, typingMessage);
}
 
Example 26
public static @NonNull LeaveGroupJob create(@NonNull Recipient group) {
  List<RecipientId> members = Stream.of(group.resolve().getParticipants()).map(Recipient::getId).toList();
  members.remove(Recipient.self().getId());

  return new LeaveGroupJob(group.getGroupId().get().requirePush(),
                           group.resolve().getDisplayName(ApplicationDependencies.getApplication()),
                           members,
                           members,
                           new Parameters.Builder()
                                         .setQueue(group.getId().toQueueKey())
                                         .addConstraint(NetworkConstraint.KEY)
                                         .setLifespan(TimeUnit.DAYS.toMillis(1))
                                         .setMaxAttempts(Parameters.UNLIMITED)
                                         .build());
}
 
Example 27
@Test
public void testTakeWhileIndexedWithStartAndStep() {
    Stream.of(1, 2, 3,  4, -5, -6, -7)
            .takeWhileIndexed(2, 2, new IndexedPredicate<Integer>() {
                @Override
                public boolean test(int index, Integer value) {
                    return index + value < 8;
                }
            })
            .custom(assertElements(contains(
                    1, 2
            )));
}
 
Example 28
Source Project: Lightweight-Stream-API   Source File: CustomTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomIntermediateOperator_Reverse() {
    Stream.range(0, 10)
            .custom(new CustomOperators.Reverse<Integer>())
            .custom(assertElements(contains(
                  9, 8, 7, 6, 5, 4, 3, 2, 1, 0
            )));
}
 
Example 29
Source Project: Lightweight-Stream-API   Source File: MinTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMin() {
    Optional<Integer> min = Stream.of(6, 3, 9, 0, -7, 19)
            .min(Functions.naturalOrder());

    assertThat(min, isPresent());
    assertNotNull(min.get());
    assertEquals(-7, (int) min.get());
}
 
Example 30
public static boolean isValidSend(@NonNull Collection<MessageRecord> targetMessages, long currentTime) {
  // TODO [greyson] [remote-delete] Update with server timestamp when available for outgoing messages
  return Stream.of(targetMessages)
               .allMatch(message -> message.isOutgoing()      &&
                                    !message.isRemoteDelete() &&
                                    !message.isPending()      &&
                                   (currentTime - message.getDateSent()) < SEND_THRESHOLD);
}