Example usage for java.lang Iterable spliterator

List of usage examples for java.lang Iterable spliterator

Introduction

In this page you can find the example usage for java.lang Iterable spliterator.

Prototype

default Spliterator<T> spliterator() 

Source Link

Document

Creates a Spliterator over the elements described by this Iterable .

Usage

From source file:com.yoshio3.services.StorageService.java

public void deleteAll(String containerName) {
    try {/*from  ww  w.  j  a  va  2  s.  com*/
        CloudBlobContainer container = blobClient.getContainerReference(containerName);
        Iterable<ListBlobItem> items = container.listBlobs();
        Spliterator<ListBlobItem> spliterator = items.spliterator();
        Stream<ListBlobItem> stream = StreamSupport.stream(spliterator, false);

        stream.filter(item -> item instanceof CloudBlob).map(item -> (CloudBlob) item).forEach(blob -> {
            try {
                String name = blob.getName();

                CloudBlockBlob delFile;
                delFile = container.getBlockBlobReference(name);
                // Delete the blob.
                delFile.deleteIfExists();
            } catch (URISyntaxException | StorageException ex) {
                LOGGER.log(Level.SEVERE, null, ex);
            }
        });
    } catch (URISyntaxException | StorageException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

From source file:edu.pitt.dbmi.ccd.anno.vocabulary.attribute.AttributeResourceAssembler.java

/**
 * convert Attributes to AttributeResources
 *
 * @param attributes entities/*ww  w.  java  2s . c o m*/
 * @return List of resources
 */
@Override
public List<AttributeResource> toResources(Iterable<? extends Attribute> attributes) {
    // Assert attributes is not empty
    Assert.isTrue(attributes.iterator().hasNext());
    return StreamSupport.stream(attributes.spliterator(), false).map(this::toResource)
            .collect(Collectors.toList());
}

From source file:edu.pitt.dbmi.ccd.anno.user.UserResourceAssembler.java

/**
 * Convert UserAccounts + Persons to UserResources
 *
 * @param accounts entities//from ww  w  .  j a v  a2  s. com
 * @return List of resources
 */
@Override
public List<UserResource> toResources(Iterable<? extends UserAccount> accounts)
        throws IllegalArgumentException {
    // Assert accounts is not empty
    Assert.isTrue(accounts.iterator().hasNext());
    return StreamSupport.stream(accounts.spliterator(), false).map(this::toResource)
            .collect(Collectors.toList());
}

From source file:edu.pitt.dbmi.ccd.anno.data.AnnotationTargetResourceAssembler.java

/**
 * convert AnnotationTargets to AnnotationTargetResources
 *
 * @param targets entities/*from  w  ww  . j ava  2  s  . c  o  m*/
 * @return List of resources
 */
@Override
public List<AnnotationTargetResource> toResources(Iterable<? extends AnnotationTarget> targets)
        throws IllegalArgumentException {
    // Assert targets is not empty
    Assert.isTrue(targets.iterator().hasNext());
    return StreamSupport.stream(targets.spliterator(), false).map(this::toResource)
            .collect(Collectors.toList());
}

From source file:gov.gtas.controller.CaseDispositionController.java

@RequestMapping(method = RequestMethod.GET, value = "/getRuleCats")
public List<RuleCat> getRuleCats() throws Exception {

    List<RuleCat> _tempRuleCatList = new ArrayList<RuleCat>();
    Iterable<RuleCat> _tempIterable = ruleCatService.findAll();
    if (_tempIterable != null) {
        _tempRuleCatList = StreamSupport.stream(_tempIterable.spliterator(), false)
                .collect(Collectors.toList());
    }/*  w  w  w.  ja va 2 s  . c  om*/
    for (RuleCat _tempRuleCat : _tempRuleCatList) {
        //_tempRuleCat.setHitsDispositions(null);
    }
    return _tempRuleCatList;
}

From source file:edu.pitt.dbmi.ccd.anno.vocabulary.VocabularyResourceAssembler.java

/**
 * convert Vocabularies to VocabularyResources
 *
 * @param vocabularies entities/*w ww  .j  a v  a  2  s.com*/
 * @return List of resources
 */
@Override
public List<VocabularyResource> toResources(Iterable<? extends Vocabulary> vocabularies)
        throws IllegalArgumentException {
    // Assert vocabularies is not empty
    Assert.isTrue(vocabularies.iterator().hasNext());
    return StreamSupport.stream(vocabularies.spliterator(), false).map(this::toResource)
            .collect(Collectors.toList());
}

From source file:TypeServiceTest.java

@Test
public void testCreateBackup() {
    typeService.save("type-test.xml", storedType());
    simulateWait();/*from  ww  w. java2  s  .c om*/
    typeService.save("type-test.xml", storedType());

    try (DirectoryStream<Path> s = Files.newDirectoryStream(fileSystemProvider.getFileSystem().getPath("/"))) {
        Iterable<Path> iterable = () -> s.iterator();

        Assert.assertEquals(2L, StreamSupport.stream(iterable.spliterator(), false)
                .filter(p -> p.getFileName().toString().startsWith("type-test")).count());
    } catch (IOException ex) {
        log.fatal(ex);
    }
}

From source file:edu.cmu.cs.lti.discoursedb.io.prosolo.blog.converter.BlogConverter.java

@Override
public void run(String... args) throws Exception {
    if (args.length < 3) {
        logger.error(//from   w ww.  j  a v  a2  s  .  co m
                "USAGE: BlogConverterApplication <DiscourseName> <DataSetName> <blogDump> <userMapping (optional)> <dumpIsWrappedInJsonArray (optional, default=false)>");
        throw new RuntimeException("Incorrect number of launch parameters.");

    }
    final String discourseName = args[0];

    final String dataSetName = args[1];
    if (dataSourceService.dataSourceExists(dataSetName)) {
        logger.warn("Dataset " + dataSetName + " has already been imported into DiscourseDB. Terminating...");
        return;
    }

    final String forumDumpFileName = args[2];
    File blogDumpFile = new File(forumDumpFileName);
    if (!blogDumpFile.exists() || !blogDumpFile.isFile() || !blogDumpFile.canRead()) {
        logger.error("Forum dump file does not exist or is not readable.");
        throw new RuntimeException("Can't read file " + forumDumpFileName);
    }

    //parse the optional fourth and fifth parameter
    String userMappingFileName = null;
    String jsonarray = null;
    if (args.length == 4) {
        if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("false")) {
            jsonarray = args[3];
        } else {
            userMappingFileName = args[3];
        }
    } else {
        if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("false")) {
            jsonarray = args[3];
            userMappingFileName = args[4];
        } else {
            jsonarray = args[4];
            userMappingFileName = args[3];
        }
    }

    //read the blog author to edX user mapping, if available
    if (userMappingFileName != null) {
        logger.trace("Reading user mapping from " + userMappingFileName);
        File userMappingFile = new File(userMappingFileName);
        if (!userMappingFile.exists() || !userMappingFile.isFile() || !userMappingFile.canRead()) {
            logger.error("User mappiong file does not exist or is not readable.");
            throw new RuntimeException("Can't read file " + userMappingFileName);
        }
        List<String> lines = FileUtils.readLines(userMappingFile);
        lines.remove(0); //remove header
        for (String line : lines) {
            String[] blogToedx = line.split(MAPPING_SEPARATOR);
            //if the current line contained a valid mapping, add it to the map
            if (blogToedx.length == 2 && blogToedx[0] != null && !blogToedx[0].isEmpty() && blogToedx[1] != null
                    && !blogToedx[1].isEmpty()) {
                blogToedxMap.put(blogToedx[0], blogToedx[1]);
            }
        }
    }

    if (jsonarray != null && jsonarray.equalsIgnoreCase(("true"))) {
        logger.trace("Set reader to expect a json array rather than regular json input.");
        this.dumpWrappedInJsonArray = true;
    }

    /*
     * Map data to DiscourseDB
     */

    logger.info("Mapping blog posts and comments to DiscourseDB");
    try (InputStream in = new FileInputStream(blogDumpFile)) {
        if (dumpWrappedInJsonArray) {
            //if the json dump is wrapped in a top-level array
            @SuppressWarnings("unchecked")
            List<ProsoloBlogPost> posts = (List<ProsoloBlogPost>) new ObjectMapper()
                    .readValues(new JsonFactory().createParser(in), new TypeReference<List<ProsoloBlogPost>>() {
                    }).next();
            posts.stream().forEach(p -> converterService.mapPost(p, discourseName, dataSetName, blogToedxMap));
        } else {
            //if the json dump is NOT wrapped in a top-level array
            Iterator<ProsoloBlogPost> pit = new ObjectMapper().readValues(new JsonFactory().createParser(in),
                    ProsoloBlogPost.class);
            Iterable<ProsoloBlogPost> iterable = () -> pit;
            StreamSupport.stream(iterable.spliterator(), false)
                    .forEach(p -> converterService.mapPost(p, discourseName, dataSetName, blogToedxMap));
        }
    }

    logger.info("All done.");
}

From source file:com.epam.ta.reportportal.events.handler.TicketActivitySubscriber.java

@EventListener
public void onTicketAttached(TicketAttachedEvent event) {
    List<Activity> activities = new ArrayList<>();
    String separator = ",";
    Iterable<TestItem> testItems = event.getBefore();
    Map<String, Activity.FieldValues> results = StreamSupport.stream(testItems.spliterator(), false)
            .filter(item -> null != item.getIssue())
            .collect(Collectors.toMap(TestItem::getId, item -> Activity.FieldValues.newOne()
                    .withOldValue(issuesIdsToString(item.getIssue().getExternalSystemIssues(), separator))));

    Iterable<TestItem> updated = event.getAfter();

    for (TestItem testItem : updated) {
        if (null == testItem.getIssue())
            continue;
        Activity.FieldValues fieldValues = results.get(testItem.getId());
        fieldValues.withNewValue(issuesIdsToString(testItem.getIssue().getExternalSystemIssues(), separator));

        Activity activity = activityBuilder.get().addProjectRef(event.getProject()).addActionType(ATTACH_ISSUE)
                .addLoggedObjectRef(testItem.getId()).addObjectType(TestItem.TEST_ITEM)
                .addUserRef(event.getPostedBy()).addHistory(ImmutableMap.<String, Activity.FieldValues>builder()
                        .put(TICKET_ID, fieldValues).build())
                .build();//ww  w  . j  a v a  2s.co  m
        activities.add(activity);
    }
    activityRepository.save(activities);
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.manifest.PatchManifestTask.java

private Object parsedManifestArtifact(@Nonnull Stage stage, Map task) {
    Artifact manifestArtifact = artifactResolver.getBoundArtifactForId(stage,
            task.get("manifestArtifactId").toString());

    if (manifestArtifact == null) {
        throw new IllegalArgumentException(
                "No artifact could be bound to '" + task.get("manifestArtifactId") + "'");
    }/*ww w  . j  av a  2s.com*/

    log.info("Using {} as the manifest to be patched", manifestArtifact);

    manifestArtifact.setArtifactAccount((String) task.get("manifestArtifactAccount"));
    return retrySupport.retry(() -> {
        try {
            Response manifestText = oort.fetchArtifact(manifestArtifact);

            Iterable<Object> rawManifests = yamlParser.get().loadAll(manifestText.getBody().in());
            List<Map> manifests = StreamSupport.stream(rawManifests.spliterator(), false).map(m -> {
                try {
                    return Collections.singletonList(objectMapper.convertValue(m, Map.class));
                } catch (Exception e) {
                    return (List<Map>) objectMapper.convertValue(m, List.class);
                }
            }).flatMap(Collection::stream).collect(Collectors.toList());

            Map<String, Object> manifestWrapper = new HashMap<>();
            manifestWrapper.put("manifests", manifests);

            manifestWrapper = contextParameterProcessor.process(manifestWrapper,
                    contextParameterProcessor.buildExecutionContext(stage, true), true);

            if (manifestWrapper.containsKey("expressionEvaluationSummary")) {
                throw new IllegalStateException("Failure evaluating manifest expressions: "
                        + manifestWrapper.get("expressionEvaluationSummary"));
            }
            List<Map> manifestsAsList = (List<Map>) manifestWrapper.get("manifests");
            return manifestsAsList.get(0);
        } catch (Exception e) {
            log.warn("Failure fetching/parsing manifests from {}", manifestArtifact, e);
            // forces a retry
            throw new IllegalStateException(e);
        }
    }, 10, 200, true);
}