List of usage examples for java.util.stream StreamSupport stream
public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)
From source file:fr.landel.utils.assertor.utils.AssertorIterable.java
private static <I extends Iterable<T>, T> boolean hasInOrder(final I iterable1, final Iterable<T> iterable2, final boolean not, final EnumAnalysisMode analysisMode) { long found = 0; final int size1 = IterableUtils.size(iterable1); final int size2 = IterableUtils.size(iterable2); if (size1 < size2) { return not; } else if (size1 == size2) { return not ^ iterable1.equals(iterable2); }//from ww w. j a v a 2s .com if (EnumAnalysisMode.STANDARD.equals(analysisMode)) { final Iterator<T> iterator1 = iterable1.iterator(); Iterator<T> iterator2 = iterable2.iterator(); // not empty pre-check, so we call next directly T value2 = iterator2.next(); while (iterator1.hasNext() && found < size2) { if (Objects.equals(iterator1.next(), value2)) { ++found; if (iterator2.hasNext()) { value2 = iterator2.next(); } } else if (found > 0) { found = 0; iterator2 = iterable2.iterator(); value2 = iterator2.next(); } } } else { final AtomicInteger count = new AtomicInteger(0); final List<T> list2 = IterableUtils.toList(iterable2); StreamSupport.stream(iterable1.spliterator(), EnumAnalysisMode.PARALLEL.equals(analysisMode)) .forEachOrdered(o -> { int inc = count.get(); if (inc < size2) { if (Objects.equals(o, list2.get(inc))) { count.incrementAndGet(); } else if (inc > 0) { count.set(0); } } }); found = count.get(); } return not ^ (found == size2); }
From source file:org.obiba.agate.service.UserService.java
/** * Update user profile from a JSON representation. * * @param user/* ww w. j a v a 2 s . c o m*/ * @param profile * @throws JSONException */ public void updateUserProfile(User user, JSONObject profile) throws JSONException { Iterable<String> iterable = profile::keys; StreamSupport.stream(iterable.spliterator(), false).forEach(k -> { String value; try { value = profile.get(k) == null ? null : profile.get(k).toString(); if ("firstname".equals(k)) { user.setFirstName(value); } else if ("lastname".equals(k)) { user.setLastName(value); } else if ("email".equals(k)) { user.setEmail(value); } else if ("locale".equals(k)) { user.setPreferredLanguage(value); } else { user.getAttributes().put(k, value); } } catch (JSONException e) { log.warn("Unable to read profile value '{}'", k, e); } }); profile.keys(); save(user); }
From source file:io.apiman.manager.api.rest.impl.OrganizationResourceImpl.java
@Override public void deleteClient(@PathParam("organizationId") String organizationId, @PathParam("clientId") String clientId) throws OrganizationNotFoundException, NotAuthorizedException, EntityStillActiveException { try {//from w ww. j a v a 2s. c om if (!securityContext.hasPermission(PermissionType.clientAdmin, organizationId)) throw ExceptionFactory.notAuthorizedException(); storage.beginTx(); ClientBean client = storage.getClient(organizationId, clientId); if (client == null) { throw ExceptionFactory.clientNotFoundException(clientId); } Iterator<ClientVersionBean> clientVersions = storage.getAllClientVersions(organizationId, clientId); Iterable<ClientVersionBean> iterable = () -> clientVersions; List<ClientVersionBean> registeredElems = StreamSupport.stream(iterable.spliterator(), false) .filter(clientVersion -> clientVersion.getStatus() == ClientStatus.Registered).limit(5) .collect(toList()); if (!registeredElems.isEmpty()) { throw ExceptionFactory.entityStillActiveExceptionClientVersions(registeredElems); } storage.deleteClient(client); storage.commitTx(); log.debug("Deleted ClientApp: " + client.getName()); //$NON-NLS-1$ } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } }
From source file:enumj.Enumerator.java
/** * Returns a sequential {@code Stream} streaming over the current * enumerator.//from w w w . ja v a 2 s .c om * * @return the new {@link Stream}. * @see #asSpliterator() * @see #asSupplier() */ public default Stream<E> asStream() { Checks.ensureNonEnumerating(this); return StreamSupport.stream(asSpliterator(), false); }
From source file:com.ikanow.aleph2.shared.crud.mongodb.services.TestMongoDbCrudService.java
@Test public void multiObjectRetrieve() throws InterruptedException, ExecutionException { final MongoDbCrudService<TestBean, String> service = getTestService("multiObjectRetrieve", TestBean.class, String.class); final List<TestBean> l = IntStream.rangeClosed(0, 9).boxed() .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i) .with("test_string", "test_string" + i).with("test_long", (Long) (long) i).done().get()) .collect(Collectors.toList()); service.storeObjects(l);// w w w. ja v a 2 s .c om assertEquals(10, service._state.orig_coll.count()); service.optimizeQuery(Arrays.asList("test_string")).get(); // (The get() waits for completion) // For asserting vs strings where possible: final JacksonDBCollection<TestBean, String> mapper = service._state.coll; // 1) Simple retrieve, no fields specified - sort final QueryComponent<TestBean> query = CrudUtils.allOf(TestBean.class).rangeAbove("_id", "id4", true) .withPresent("test_long").orderBy(Tuples._2T("test_string", -1)); try (Cursor<TestBean> cursor = service.getObjectsBySpec(query).get()) { assertEquals(5, cursor.count()); final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false) .collect(Collectors.toList()); assertEquals(5, objs.size()); final DBObject first_obj = mapper.convertToDbObject(objs.get(0)); assertEquals("{ \"_id\" : \"id9\" , \"test_string\" : \"test_string9\" , \"test_long\" : 9}", first_obj.toString()); } catch (Exception e) { //(fail on close, normally carry on - but here error out) fail("getObjectsBySpec errored on close"); } // 2) Simple retrieve, field specified (exclusive) - sort and limit final QueryComponent<TestBean> query_2 = CrudUtils.allOf(TestBean.class).rangeAbove("_id", "id4", false) .withPresent("test_long").orderBy(Tuples._2T("test_long", 1)).limit(4); try (Cursor<TestBean> cursor = service.getObjectsBySpec(query_2, Arrays.asList("test_string"), false) .get()) { assertEquals(6, cursor.count()); // (count ignores limit) final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false) .collect(Collectors.toList()); assertEquals(4, objs.size()); final DBObject first_obj = mapper.convertToDbObject(objs.get(0)); assertEquals("{ \"_id\" : \"id4\" , \"test_long\" : 4}", first_obj.toString()); } catch (Exception e) { //(fail on close, normally carry on - but here error out) fail("getObjectsBySpec errored on close"); } // 3) Simple retrieve, no docs returned final QueryComponent<TestBean> query_3 = CrudUtils.allOf(TestBean.class).rangeAbove("_id", "id9", true) .withPresent("test_long").limit(4); try (Cursor<TestBean> cursor = service.getObjectsBySpec(query_3, Arrays.asList("test_string"), false) .get()) { final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false) .collect(Collectors.toList()); assertEquals(0, objs.size()); } catch (Exception e) { //(fail on close, normally carry on - but here error out) fail("getObjectsBySpec errored on close"); } }
From source file:com.simiacryptus.mindseye.lang.Tensor.java
/** * Coord stream stream.// www .ja v a2 s .c o m * * @param parallel the safe * @return the stream */ @Nonnull public Stream<Coordinate> coordStream(boolean parallel) { //ConcurrentHashSet<Object> distinctBuffer = new ConcurrentHashSet<>(); //assert distinctBuffer.add(coordinate.copy()) : String.format("Duplicate: %s in %s", coordinate, distinctBuffer); return StreamSupport.stream(Spliterators.spliterator(new Iterator<Coordinate>() { int cnt = 0; @Nonnull Coordinate coordinate = new Coordinate(); @Nonnull int[] val = new int[dimensions.length]; @Nonnull int[] safeCopy = new int[dimensions.length]; @Override public boolean hasNext() { return cnt < length(); } @Nonnull @Override public synchronized Coordinate next() { if (0 < cnt) { for (int i = 0; i < val.length; i++) { if (++val[i] >= dimensions[i]) { val[i] = 0; } else { break; } } } System.arraycopy(val, 0, safeCopy, 0, val.length); coordinate.setIndex(cnt++); coordinate.setCoords(safeCopy); return parallel ? coordinate.copy() : coordinate; } }, length(), Spliterator.ORDERED), parallel); }
From source file:org.opennms.netmgt.config.DiscoveryConfigFactory.java
/** * <p>getExcludingInterator</p> * * @param it a {@link java.util.Iterator} object. * @return a {@link java.util.Iterator} object. *///from www.ja v a 2 s.c o m @Override public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false) // Filter out excluded addresses .filter(item -> !isExcluded(item.getAddress())).iterator(); }
From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java
private Collection<PiCounterCellData> doReadCounterEntities(Collection<Entity> counterEntities, PiPipeconf pipeconf) {//from w w w .ja v a 2s . c o m if (counterEntities.size() == 0) { return Collections.emptyList(); } final ReadRequest request = ReadRequest.newBuilder().setDeviceId(p4DeviceId).addAllEntities(counterEntities) .build(); final Iterable<ReadResponse> responses; try { responses = () -> blockingStub.read(request); } catch (StatusRuntimeException e) { log.warn("Unable to read counter cells from {}: {}", deviceId, e.getMessage()); return Collections.emptyList(); } List<Entity> entities = StreamSupport.stream(responses.spliterator(), false) .map(ReadResponse::getEntitiesList).flatMap(List::stream).collect(Collectors.toList()); return CounterEntryCodec.decodeCounterEntities(entities, pipeconf); }
From source file:io.apiman.manager.api.rest.impl.OrganizationResourceImpl.java
@Override public void deleteApi(@PathParam("organizationId") String organizationId, @PathParam("apiId") String apiId) throws OrganizationNotFoundException, NotAuthorizedException, EntityStillActiveException { try {// w w w. j a v a2 s. c om if (!securityContext.hasPermission(PermissionType.apiAdmin, organizationId)) throw ExceptionFactory.notAuthorizedException(); storage.beginTx(); ApiBean api = storage.getApi(organizationId, apiId); if (api == null) { throw ExceptionFactory.apiNotFoundException(apiId); } Iterator<ApiVersionBean> apiVersions = storage.getAllApiVersions(organizationId, apiId); Iterable<ApiVersionBean> iterable = () -> apiVersions; List<ApiVersionBean> registeredElems = StreamSupport.stream(iterable.spliterator(), false) .filter(clientVersion -> clientVersion.getStatus() == ApiStatus.Published).limit(5) .collect(toList()); if (!registeredElems.isEmpty()) { throw ExceptionFactory.entityStillActiveExceptionApiVersions(registeredElems); } storage.deleteApi(api); storage.commitTx(); log.debug("Deleted API: " + api.getName()); //$NON-NLS-1$ } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } }
From source file:com.epam.ta.reportportal.core.project.impl.UpdateProjectHandler.java
/** * Validate candidates for unassign from projects, and update default * project if it required//from w w w . j ava 2 s .co m * * @param users * @param projectName */ private void processCandidateForUnaassign(Iterable<User> users, String projectName) { List<User> updated = StreamSupport.stream(users.spliterator(), false) .filter(it -> it.getDefaultProject().equals(projectName)).map(it -> { it.setDefaultProject(personalProjectName(it.getId())); return it; }).collect(toList()); userRepository.save(updated); }