com.annimon.stream.Stream Java Examples

The following examples show how to use com.annimon.stream.Stream. 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
Source File: MapToIntTest.java    From Lightweight-Stream-API with 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 #2
Source File: OfNullableTest.java    From Lightweight-Stream-API with 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
Source File: JobController.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @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 #4
Source File: JobController.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: MapIndexedTest.java    From Lightweight-Stream-API with 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 #6
Source File: AdvancedInstallerFragment.java    From EdXposedManager with GNU General Public License v3.0 6 votes vote down vote up
@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
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: MapToIntTest.java    From Lightweight-Stream-API with 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 #9
Source File: AvatarSelectionBottomSheetDialogFragment.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: StickerPackPreviewRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: ReactionsLoader.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: MergeTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testMergeOnBothEmptyStreams() {
    Stream<Integer> emptyStream1 = Stream.<Integer>empty();
    Stream<Integer> emptyStream2 = Stream.<Integer>empty();
    Stream.merge(emptyStream1, emptyStream2, selectorFunction())
            .custom(StreamMatcher.<Integer>assertIsEmpty());
}
 
Example #13
Source File: ConcatTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcatOfFlatMap() {
    final Function<Integer, Stream<Integer>> flatmapFunc = new Function<Integer, Stream<Integer>>() {
        @Override
        public Stream<Integer> apply(Integer value) {
            return Stream.of(value, value);
        }
    };
    Stream<Integer> stream1 = Stream.range(1, 3).flatMap(flatmapFunc); // 1122
    Stream<Integer> stream2 = Stream.range(3, 5).flatMap(flatmapFunc); // 3344
    Stream.concat(stream1, stream2)
            .custom(assertElements(contains(
                    1, 1, 2, 2, 3, 3, 4, 4
            )));
}
 
Example #14
Source File: ConcatTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcat() {
    Stream<String> stream1 = Stream.of("a", "b", "c", "d");
    Stream<String> stream2 = Stream.of("e", "f", "g", "h");
    Stream.concat(stream1, stream2)
            .custom(assertElements(contains(
                    "a", "b", "c", "d",
                    "e", "f", "g", "h"
            )));
}
 
Example #15
Source File: FirestoreRepositoryImpl.java    From openwebnet-android with MIT License 5 votes vote down vote up
@Override
public Observable<List<Integer>> applyProfile(ProfileModel profile) {
    ProfileVersionModel version = profile.getVersion();

    List<Observable<?>> addAll = Lists.newArrayList(
        automationRepository.addAll(Stream.of(profile.getAutomations())
            .map(automationMap -> AutomationModel.newInstance(automationMap, version)).toList()),
        deviceRepository.addAll(Stream.of(profile.getDevices())
            .map(deviceMap -> DeviceModel.newInstance(deviceMap, version)).toList()),
        energyRepository.addAll(Stream.of(profile.getEnergies())
            .map(energyMap -> EnergyModel.newInstance(energyMap, version)).toList()),
        environmentRepository.addAll(Stream.of(profile.getEnvironments())
            .map(environmentMap -> EnvironmentModel.newInstance(environmentMap, version)).toList()),
        gatewayRepository.addAll(Stream.of(profile.getGateways())
            .map(gatewayMap -> GatewayModel.newInstance(gatewayMap, version)).toList()),
        ipcamRepository.addAll(Stream.of(profile.getIpcams())
            .map(ipcamMap -> IpcamModel.newInstance(ipcamMap, version)).toList()),
        lightRepository.addAll(Stream.of(profile.getLights())
            .map(lightMap -> LightModel.newInstance(lightMap, version)).toList()),
        scenarioRepository.addAll(Stream.of(profile.getScenarios())
            .map(scenarioMap -> ScenarioModel.newInstance(scenarioMap, version)).toList()),
        soundRepository.addAll(Stream.of(profile.getSounds())
            .map(soundMap -> SoundModel.newInstance(soundMap, version)).toList()),
        temperatureRepository.addAll(Stream.of(profile.getTemperatures())
            .map(temperatureMap -> TemperatureModel.newInstance(temperatureMap, version)).toList())
    );

    // count of each model
    return Observable.zip(addAll, results -> Stream.of(results)
        .map(object -> ((List<?>) object).size()).toList());
}
 
Example #16
Source File: RemoteDeleteUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: FloatingActionMenu.java    From Carbon with Apache License 2.0 5 votes vote down vote up
public void setMenu(final android.view.Menu menu) {
    List<Item> items = new ArrayList<>();
    for (int i = 0; i < menu.size(); i++) {
        if (menu.getItem(i).isVisible())
            items.add(new Item(menu.getItem(i)));
    }

    this.items = Stream.of(items).toArray(Item[]::new);
}
 
Example #18
Source File: ScanTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testScan() {
    Stream.of(1, 2, 3)
            .scan(Functions.addition())
            .custom(assertElements(contains(
                    1, 3, 6
            )));
}
 
Example #19
Source File: SkipTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipAndLimit() {
    Stream.range(0, 10)
            .skip(2)  // 23456789
            .limit(5) // 23456
            .custom(assertElements(contains(
                    2, 3, 4, 5, 6
            )));
}
 
Example #20
Source File: OnCloseTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnClose() {
    final boolean[] state = new boolean[] { false };
    Stream<Integer> stream = Stream.of(0, 1, 2)
            .onClose(new Runnable() {
                @Override
                public void run() {
                    state[0] = true;
                }
            });
    stream.findFirst();
    stream.close();
    assertTrue(state[0]);
}
 
Example #21
Source File: OfNullableTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamOfNullableWithIterable() {
    assertThat(Stream.ofNullable((List<?>) null), isEmpty());

    assertThat(Stream.ofNullable(Arrays.asList(5, 10, 15)),
            elements(contains(5, 10, 15)));
}
 
Example #22
Source File: OfIteratorTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamOfIterator() {
    Stream.of(Functions.counterIterator())
            .limit(5)
            .custom(assertElements(contains(
                  0, 1, 2, 3, 4
            )));
}
 
Example #23
Source File: FilterIndexedTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test(expected = NoSuchElementException.class)
public void testFilterIndexedIteratorNextOnEmpty() {
    Stream.<Integer>empty()
            .filterIndexed(IndexedPredicate.Util.wrap(Functions.remainder(2)))
            .iterator()
            .next();
}
 
Example #24
Source File: FilterIndexedTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test(expected = NoSuchElementException.class)
public void testFilterIndexedIteratorNextOnEmpty() {
    Stream.<Integer>empty()
            .filterIndexed(IndexedPredicate.Util.wrap(Functions.remainder(2)))
            .iterator()
            .next();
}
 
Example #25
Source File: InAppScheduler.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void schedule(long delay, @NonNull List<Constraint> constraints) {
  if (delay > 0 && Stream.of(constraints).allMatch(Constraint::isMet)) {
    Log.i(TAG, "Scheduling a retry in " + delay + " ms.");
    handler.postDelayed(() -> {
      Log.i(TAG, "Triggering a job retry.");
      jobManager.wakeUp();
    }, delay);
  }
}
 
Example #26
Source File: DistinctTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctPreservesOrder() {
    Stream.of(1, 1, 2, 3, 5, 3, 2, 1, 1, -1)
            .distinct()
            .custom(assertElements(contains(
                    1, 2, 3, 5, -1
            )));
}
 
Example #27
Source File: RemoteDeleteSendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull List<Recipient> deliver(@NonNull Recipient conversationRecipient, @NonNull List<Recipient> destinations, long targetSentTimestamp)
    throws IOException, UntrustedIdentityException
{
  SignalServiceMessageSender             messageSender      = ApplicationDependencies.getSignalServiceMessageSender();
  List<SignalServiceAddress>             addresses          = Stream.of(destinations).map(t -> RecipientUtil.toSignalServiceAddress(context, t)).toList();
  List<Optional<UnidentifiedAccessPair>> unidentifiedAccess = Stream.of(destinations).map(recipient -> UnidentifiedAccessUtil.getAccessFor(context, recipient)).toList();
  SignalServiceDataMessage.Builder       dataMessage        = SignalServiceDataMessage.newBuilder()
                                                                                      .withTimestamp(System.currentTimeMillis())
                                                                                      .withRemoteDelete(new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp));

  if (conversationRecipient.isGroup()) {
    GroupUtil.setDataMessageGroupContext(context, dataMessage, conversationRecipient.requireGroupId().requirePush());
  }

  List<SendMessageResult> results = messageSender.sendMessage(addresses, unidentifiedAccess, false, dataMessage.build());

  Stream.of(results)
        .filter(r -> r.getIdentityFailure() != null)
        .map(SendMessageResult::getAddress)
        .map(a -> Recipient.externalPush(context, a))
        .forEach(r -> Log.w(TAG, "Identity failure for " + r.getId()));

  Stream.of(results)
        .filter(SendMessageResult::isUnregisteredFailure)
        .map(SendMessageResult::getAddress)
        .map(a -> Recipient.externalPush(context, a))
        .forEach(r -> Log.w(TAG, "Unregistered failure for " + r.getId()));

  return Stream.of(results)
               .filter(r -> r.getSuccess() != null || r.getIdentityFailure() != null || r.isUnregisteredFailure())
               .map(SendMessageResult::getAddress)
               .map(a -> Recipient.externalPush(context, a))
               .toList();
}
 
Example #28
Source File: SkipTest.java    From Lightweight-Stream-API with 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 #29
Source File: SortedTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testSorted() {
    Stream.of(6, 3, 9, 0, -7, 19)
            .sorted()
            .custom(assertElements(contains(
                    -7, 0, 3, 6, 9, 19
            )));
}
 
Example #30
Source File: MegaphoneRepository.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
private void init() {
  List<MegaphoneRecord> records = database.getAllAndDeleteMissing();
  Set<Event>            events  = Stream.of(records).map(MegaphoneRecord::getEvent).collect(Collectors.toSet());
  Set<Event>            missing = Stream.of(Megaphones.Event.values()).filterNot(events::contains).collect(Collectors.toSet());

  database.insert(missing);
  resetDatabaseCache();
}