List of usage examples for java.lang Iterable spliterator
default Spliterator<T> spliterator()
From source file:org.eclipse.hawkbit.repository.jpa.TargetManagementTest.java
@Test @WithUser(allSpPermissions = true)//from w ww . j ava 2s . co m @Description("Create multiple targets as bulk operation and delete them in bulk.") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 101), @Expect(type = TargetUpdatedEvent.class, count = 100), @Expect(type = TargetDeletedEvent.class, count = 51) }) public void bulkTargetCreationAndDelete() throws Exception { final String myCtrlID = "myCtrlID"; List<Target> firstList = testdataFactory.createTargets(100, myCtrlID, "first description"); final Target extra = testdataFactory.createTarget("myCtrlID-00081XX"); final Iterable<JpaTarget> allFound = targetRepository.findAll(); assertThat(Long.valueOf(firstList.size())).as("List size of targets") .isEqualTo(firstList.spliterator().getExactSizeIfKnown()); assertThat(Long.valueOf(firstList.size() + 1)).as("LastModifiedAt compared with saved lastModifiedAt") .isEqualTo(allFound.spliterator().getExactSizeIfKnown()); // change the objects and save to again to trigger a change on // lastModifiedAt firstList = firstList.stream() .map(t -> targetManagement.update( entityFactory.target().update(t.getControllerId()).name(t.getName().concat("\tchanged")))) .collect(Collectors.toList()); // verify that all entries are found _founds: for (final Target foundTarget : allFound) { for (final Target changedTarget : firstList) { if (changedTarget.getControllerId().equals(foundTarget.getControllerId())) { assertThat(changedTarget.getDescription()) .as("Description of changed target compared with description saved target") .isEqualTo(foundTarget.getDescription()); assertThat(changedTarget.getName()) .as("Name of changed target starts with name of saved target") .startsWith(foundTarget.getName()); assertThat(changedTarget.getName()).as("Name of changed target ends with 'changed'") .endsWith("changed"); assertThat(changedTarget.getCreatedAt()).as("CreatedAt compared with saved createdAt") .isEqualTo(foundTarget.getCreatedAt()); assertThat(changedTarget.getLastModifiedAt()).as("LastModifiedAt compared with saved createdAt") .isNotEqualTo(changedTarget.getCreatedAt()); continue _founds; } } if (!foundTarget.getControllerId().equals(extra.getControllerId())) { fail("The controllerId of the found target is not equal to the controllerId of the saved target"); } } targetManagement.deleteByControllerID(extra.getControllerId()); final int numberToDelete = 50; final Collection<Target> targetsToDelete = firstList.subList(0, numberToDelete); final Target[] deletedTargets = Iterables.toArray(targetsToDelete, Target.class); final List<Long> targetsIdsToDelete = targetsToDelete.stream().map(Target::getId) .collect(Collectors.toList()); targetManagement.delete(targetsIdsToDelete); final List<Target> targetsLeft = targetManagement.findAll(PageRequest.of(0, 200)).getContent(); assertThat(firstList.spliterator().getExactSizeIfKnown() - numberToDelete).as("Size of split list") .isEqualTo(targetsLeft.spliterator().getExactSizeIfKnown()); assertThat(targetsLeft).as("Not all undeleted found").doesNotContain(deletedTargets); }
From source file:org.eclipse.sw360.licenseinfo.parsers.AbstractCLIParser.java
private Stream<Node> streamFromNodeList(NodeList nodes) { Iterator<Node> iter = new NodeListIterator(nodes); Iterable<Node> iterable = () -> iter; return StreamSupport.stream(iterable.spliterator(), false); }
From source file:org.fcrepo.apix.jena.Util.java
/** * Perform a sparql query against a model. * * @param sparql A sparql CONSTRUCT query * @param model the model// w w w . ja v a 2 s.co m * @return Stream of matching triples. */ public static Stream<Triple> query(final String sparql, final Model model) { final Iterable<Triple> i = () -> QueryExecutionFactory.create(QueryFactory.create(sparql), model) .execConstructTriples(); return StreamSupport.stream(i.spliterator(), false); }
From source file:org.jboss.set.aphrodite.issue.trackers.jira.JiraIssueTracker.java
private List<LinkIssuesInput> calculateNewLinks(Issue issue, com.atlassian.jira.rest.client.api.domain.Issue jiraIssue) { // When jiraIssueLinks is null, this means that issue links have been disabled, so return an empty list Iterable<IssueLink> jiraIssueLinks = jiraIssue.getIssueLinks(); if (jiraIssueLinks == null) return new ArrayList<>(); // Process the existing IssueLinks and retrieve their Issue keys List<IssueLink> tmp = StreamSupport.stream(jiraIssueLinks.spliterator(), false) .collect(Collectors.toList()); List<String> inbound = getExistingIssueLinkKeys(tmp, Direction.INBOUND); List<String> outbound = getExistingIssueLinkKeys(tmp, Direction.OUTBOUND); return Stream.concat( createIssueLinks(issue, inbound, e -> new LinkIssuesInput(e, jiraIssue.getKey(), "Dependency")), createIssueLinks(issue, outbound, e -> new LinkIssuesInput(jiraIssue.getKey(), e, "Dependency"))) .collect(Collectors.toList()); }
From source file:org.neo4j.helpers.json.document.impl.DocumentRelationBuilderByKey.java
@Override public Relationship buildRelation(Node parent, Node child, DocumentRelationContext context) { String documentKey = context.getDocumentKey(); if (StringUtils.isBlank(documentKey)) { return null; }//from w w w. j ava2 s . c o m RelationshipType relationType = RelationshipType.withName(documentKey); //check if already exists Iterable<Relationship> relationships = child.getRelationships(Direction.INCOMING, relationType); //find only relation between parent and child node List<Relationship> rels = StreamSupport.stream(relationships.spliterator(), false) .filter(rel -> rel.getStartNode().getId() == parent.getId()).collect(Collectors.toList()); Relationship relationship; if (rels.isEmpty()) { relationship = parent.createRelationshipTo(child, relationType); if (log.isDebugEnabled()) log.debug("Create new Relation " + relationship); } else { relationship = rels.get(0); if (log.isDebugEnabled()) log.debug("Update Relation " + relationship); } return relationship; }
From source file:org.neo4j.helpers.json.document.impl.DocumentRelationBuilderTypeArrayKey.java
@Override public Relationship buildRelation(Node parent, Node child, DocumentRelationContext context) { String relationName = buildRelationName(parent, child, context); RelationshipType type = RelationshipType.withName(relationName); //check if already exists Iterable<Relationship> relationships = child.getRelationships(Direction.INCOMING, type); Relationship relationship;//from ww w .j a v a2s.com //find only relation between parent and child node List<Relationship> rels = StreamSupport.stream(relationships.spliterator(), false) .filter(rel -> rel.getStartNode().getId() == parent.getId()).collect(Collectors.toList()); if (rels.isEmpty()) { relationship = parent.createRelationshipTo(child, type); if (log.isDebugEnabled()) log.debug("Create new Relation " + relationship); } else { relationship = rels.get(0); if (log.isDebugEnabled()) log.debug("Update Relation " + relationship); } //manage array of keys String[] keys = new String[0]; //create property if doesn't exists (new relation) if (relationship.getAllProperties().containsKey(DOC_KEYS)) { keys = (String[]) relationship.getProperty(DOC_KEYS); } //set document key into property String documentKey = context.getDocumentKey(); if (!ArrayUtils.contains(keys, documentKey)) { keys = ArrayUtils.add(keys, documentKey); relationship.setProperty(DOC_KEYS, keys); } return relationship; }
From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicRepository.java
protected Stream<State> findAll(String ctsQuery, String... selects) { String query = ctsQuery;/*from w ww . j a va 2s . co m*/ if (selects.length > 0) { query = "import module namespace extract = 'http://nuxeo.com/extract' at '/ext/nuxeo/extract.xqy';\n" + "let $paths := (" + Arrays.stream(selects).map(MarkLogicHelper::serializeKey) .map(select -> "\"" + MarkLogicHelper.DOCUMENT_ROOT_PATH + "/" + select + "\"") .collect(Collectors.joining(",\n")) + ")let $namespaces := ()\n" + "for $i in " + query + " return extract:extract-nodes($i, $paths, $namespaces)"; } if (log.isTraceEnabled()) { logQuery(query); } // Run query boolean completedAbruptly = true; Session session = xccContentSource.newSession(); try { // As we can get a lot of results don't buffer the result RequestOptions options = new RequestOptions(); options.setCacheResult(false); AdhocQuery request = session.newAdhocQuery(query, options); // We give 0 as characteristics because it's the value used by Iterable#spliterator() and according to // StreamSupport.stream(Supplier, int, boolean) documentation, characteristics must be equal to // supplier.get().characteristics() Supplier<Spliterator<ResultItem>> spliteratorSupplier = () -> { try { // ResultSequence will be closed by Session close (closed by stream closed) ResultSequence rs = session.submitRequest(request); Iterable<ResultItem> items = rs::iterator; return items.spliterator(); } catch (RequestException e) { throw new NuxeoException("An exception happened during xcc call", e); } }; Stream<State> stream = StreamSupport.stream(spliteratorSupplier, 0, false).onClose(session::close) .map(ResultItem::getItem).map(XdmItem::asInputStream) .map(MarkLogicStateDeserializer::deserialize); // the stream takes responsibility for closing the session completedAbruptly = false; return stream; } finally { if (completedAbruptly) { session.close(); } } }
From source file:org.obiba.agate.service.UserService.java
/** * Update user profile from a JSON representation. * * @param user/* w w w . jav a2s . 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:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java
private Collection<PiTableEntry> doDumpTable(PiTableId piTableId, PiPipeconf pipeconf) { log.debug("Dumping table {} from {} (pipeconf {})...", piTableId, deviceId, pipeconf.id()); P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf); int tableId;/* w w w. jav a 2 s.c o m*/ try { tableId = browser.tables().getByName(piTableId.id()).getPreamble().getId(); } catch (P4InfoBrowser.NotFoundException e) { log.warn("Unable to dump table: {}", e.getMessage()); return Collections.emptyList(); } ReadRequest requestMsg = ReadRequest.newBuilder().setDeviceId(p4DeviceId).addEntities( Entity.newBuilder().setTableEntry(TableEntry.newBuilder().setTableId(tableId).build()).build()) .build(); Iterator<ReadResponse> responses; try { responses = blockingStub.read(requestMsg); } catch (StatusRuntimeException e) { log.warn("Unable to dump table {} from {}: {}", piTableId, deviceId, e.getMessage()); return Collections.emptyList(); } Iterable<ReadResponse> responseIterable = () -> responses; List<TableEntry> tableEntryMsgs = StreamSupport.stream(responseIterable.spliterator(), false) .map(ReadResponse::getEntitiesList).flatMap(List::stream) .filter(entity -> entity.getEntityCase() == TABLE_ENTRY).map(Entity::getTableEntry) .collect(Collectors.toList()); log.debug("Retrieved {} entries from table {} on {}...", tableEntryMsgs.size(), piTableId, deviceId); return TableEntryEncoder.decode(tableEntryMsgs, pipeconf); }
From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java
private Collection<PiCounterCellData> doReadCounterEntities(Collection<Entity> counterEntities, PiPipeconf pipeconf) {// w w w.j ava2s .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); }