Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

In this page you can find the example usage for java.util Set stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.aws.AWSEC2JCloudsProviderTest.java

@Test
public void testCreateInstanceWithSpotPrice() throws NumberFormatException, RunNodesException {

    Infrastructure infratructure = InfrastructureFixture.getInfrastructure("id-aws", "aws", "endPoint",
            "userName", "password");

    when(computeServiceCache.getComputeService(infratructure)).thenReturn(computeService);

    when(computeService.templateBuilder()).thenReturn(templateBuilder);

    Instance instance = InstanceFixture.getInstanceWithSpotPrice("instance-id", "instance-name", "image", "2",
            "512", "2", "77.154.227.148", "1.0.0.2", "running", "0.05f");

    when(templateBuilder.minRam(Integer.parseInt(instance.getHardware().getMinRam())))
            .thenReturn(templateBuilder);

    when(templateBuilder.minCores(Double.parseDouble(instance.getHardware().getMinCores())))
            .thenReturn(templateBuilder);

    when(templateBuilder.imageId(instance.getImage())).thenReturn(templateBuilder);

    when(templateBuilder.build()).thenReturn(template);

    Set nodes = Sets.newHashSet();
    NodeMetadataImpl node = mock(NodeMetadataImpl.class);
    when(node.getId()).thenReturn("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592");
    when(node.getName()).thenReturn("someName");
    Hardware hardware = mock(Hardware.class);
    when(hardware.getProcessors()).thenReturn(Lists.newArrayList());
    when(node.getHardware()).thenReturn(hardware);
    when(hardware.getType()).thenReturn(ComputeType.HARDWARE);
    when(node.getStatus()).thenReturn(Status.RUNNING);
    nodes.add(node);/*from w  w w.j  av  a2s  .  co m*/
    when(computeService.listNodes()).thenReturn(nodes);

    when(computeService.createNodesInGroup(instance.getTag(), Integer.parseInt(instance.getNumber()), template))
            .thenReturn(nodes);

    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getOptions()).thenReturn(templateOptions);

    when(templateOptions.runAsRoot(true)).thenReturn(templateOptions);

    when(templateOptions.as(AWSEC2TemplateOptions.class)).thenReturn(awsEC2TemplateOptions);

    // Tags
    when(tagManager.retrieveAllTags(any(Options.class))).thenReturn(Lists.newArrayList(connectorIaasTag));

    Set<Instance> created = jcloudsProvider.createInstance(infratructure, instance);

    assertThat(created.size(), is(1));

    assertThat(created.stream().findAny().get().getId(), is("RegionOne/1cde5a56-27a6-46ce-bdb7-8b01b8fe2592"));

    verify(computeService, times(1)).createNodesInGroup(instance.getTag(),
            Integer.parseInt(instance.getNumber()), template);

    verify(awsEC2TemplateOptions, times(1)).spotPrice(Float.valueOf(instance.getOptions().getSpotPrice()));

}

From source file:fr.landel.utils.assertor.utils.AssertorMap.java

private static <M extends Map<K, V>, K, V, T> boolean hasInOrder(final M map, final Iterable<T> objects,
        final boolean not, final EnumAnalysisMode analysisMode,
        final BiPredicate<Entry<K, V>, T> entriesEqualChecker, final Class<T> objectsClass) {

    int found = 0;

    final int size1 = map.size();
    final int size2 = IterableUtils.size(objects);

    if (size1 < size2) {
        return not;
    }/*from   w w w.  j  a  v  a  2 s. c  o m*/

    final Set<Entry<K, V>> entries1 = map.entrySet();
    final List<T> entries2 = IterableUtils.toList(objects);

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        for (Entry<K, V> entry1 : entries1) {
            if (found < size2) {
                if (entriesEqualChecker.test(entry1, entries2.get(found))) {
                    ++found;
                } else if (found > 0) {
                    found = 0;
                }
            }
        }
    } else {
        final AtomicInteger count = new AtomicInteger(0);

        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries1.parallelStream();
        } else {
            stream = entries1.stream();
        }

        stream.forEachOrdered(o -> {
            int inc = count.get();
            if (inc < size2) {
                if (entriesEqualChecker.test(o, entries2.get(inc))) {
                    count.incrementAndGet();
                } else if (inc > 0) {
                    count.set(0);
                }
            }
        });

        found = count.get();
    }

    return not ^ (found == size2);
}

From source file:ddf.catalog.data.impl.MetacardTypeImpl.java

/**
 * Creates a {@code MetacardTypeImpl} with the provided {@code name} and {@link
 * AttributeDescriptor}s./*from  www. ja v a  2  s .c o  m*/
 *
 * @param name the name of this {@code MetacardTypeImpl}
 * @param descriptors the set of descriptors for this {@code MetacardTypeImpl}
 */
public MetacardTypeImpl(String name, Set<AttributeDescriptor> descriptors) {
    /*
     * If any defensive logic is added to this constructor, then that logic should be reflected
     * in the deserialization (readObject()) of this object so that the integrity of a
     * serialized object is maintained. For instance, if a null check is added in the
     * constructor, the same check should be added in the readObject() method.
     */
    this.name = name;
    if (descriptors != null) {
        descriptors.stream().filter(Objects::nonNull)
                .forEach(descriptor -> this.descriptors.put(descriptor.getName(), descriptor));
    }
    validateDescriptors();
}

From source file:gr.cti.android.experimentation.controller.ui.RestRankingController.java

@ResponseBody
@Deprecated/*from w  ww .j a  va  2s  .c o  m*/
@RequestMapping(value = "/statistics", method = RequestMethod.GET)
public String getRankings(@RequestParam(required = false, defaultValue = "0") final int deviceId) {

    final long resultsTotal = resultRepository.countByDeviceId(deviceId);
    final long resultsToday = resultRepository.countByDeviceIdAndTimestampAfter(deviceId,
            new DateTime().withMillisOfDay(0).getMillis());
    final Set<Result> experimentsTotal = new HashSet<>();
    final Set<Integer> experimentIdsTotal = new HashSet<>();
    experimentsTotal.addAll(resultRepository.findDistinctExperimentIdByDeviceId(deviceId));
    final Set<Result> experimentsToday = new HashSet<>();
    final Set<Integer> experimentsIdsToday = new HashSet<>();
    experimentsToday.addAll(resultRepository.findDistinctExperimentIdByDeviceIdAndTimestampAfter(deviceId,
            new DateTime().withMillisOfDay(0).getMillis()));

    experimentIdsTotal
            .addAll(experimentsTotal.stream().map(Result::getExperimentId).collect(Collectors.toList()));
    experimentsIdsToday
            .addAll(experimentsToday.stream().map(Result::getExperimentId).collect(Collectors.toList()));
    final JSONObject obj = new JSONObject();
    try {
        obj.put("resultsTotal", resultsTotal);
        obj.put("resultsToday", resultsToday);
        obj.put("experimentsTotal", experimentIdsTotal.size());
        obj.put("experimentsToday", experimentsIdsToday.size());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj.toString();
}

From source file:fr.landel.utils.assertor.utils.AssertorMap.java

private static <K, V> boolean match(final Map<K, V> map, final Predicate<Entry<K, V>> predicate,
        final boolean all, final EnumAnalysisMode analysisMode) {

    final Set<Entry<K, V>> entries = map.entrySet();

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        if (all) {
            for (final Entry<K, V> entry : entries) {
                if (!predicate.test(entry)) {
                    return false;
                }/*from  w  w w . j  a  v  a2 s  .  c  o m*/
            }
            return true;
        } else {
            for (final Entry<K, V> entry : entries) {
                if (predicate.test(entry)) {
                    return true;
                }
            }
            return false;
        }
    } else {
        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries.parallelStream();
        } else {
            stream = entries.stream();
        }
        if (all) {
            return stream.allMatch(predicate);
        } else {
            return stream.anyMatch(predicate);
        }
    }
}

From source file:alfio.manager.SpecialPriceManager.java

private List<String> checkCodeAssignment(Set<SendCodeModification> input, int categoryId, Event event,
        String username) {//from w w w  .  j a  v a  2  s.c o m
    final TicketCategory category = checkOwnership(categoryId, event, username);
    List<String> availableCodes = new ArrayList<>(
            specialPriceRepository.findActiveByCategoryId(category.getId()).stream()
                    .filter(SpecialPrice::notSent).map(SpecialPrice::getCode).collect(toList()));
    Validate.isTrue(input.size() <= availableCodes.size(),
            "Requested codes: " + input.size() + ", available: " + availableCodes.size() + ".");
    List<String> requestedCodes = input.stream().filter(IS_CODE_PRESENT).map(SendCodeModification::getCode)
            .collect(toList());
    Validate.isTrue(requestedCodes.stream().distinct().count() == requestedCodes.size(),
            "Cannot assign the same code twice. Please fix the input file.");
    Validate.isTrue(requestedCodes.stream().allMatch(availableCodes::contains),
            "some requested codes don't exist.");
    return availableCodes;
}

From source file:org.openlmis.fulfillment.web.ProofOfDeliveryController.java

/**
 * Get all proofs of delivery.//from   w  w w.j a  v  a 2 s. c o m
 *
 * @return proofs of delivery.
 */
@RequestMapping(value = "/proofsOfDelivery", method = RequestMethod.GET)
@ResponseBody
public Page<ProofOfDeliveryDto> getAllProofsOfDelivery(@RequestParam(required = false) UUID orderId,
        @RequestParam(required = false) UUID shipmentId, Pageable pageable) {
    XLOGGER.entry(shipmentId, pageable);
    Profiler profiler = new Profiler("GET_PODS");
    profiler.setLogger(XLOGGER);

    List<ProofOfDelivery> content;

    if (null == shipmentId && null == orderId) {
        profiler.start("GET_ALL_PODS");
        content = proofOfDeliveryRepository.findAll();
    } else if (null != shipmentId) {
        profiler.start("FIND_PODS_BY_SHIPMENT_ID");
        content = proofOfDeliveryRepository.findByShipmentId(shipmentId);
    } else {
        profiler.start("FIND_PODS_BY_ORDER_ID");
        content = proofOfDeliveryRepository.findByOrderId(orderId);
    }

    UserDto user = authenticationHelper.getCurrentUser();

    if (null != user) {
        profiler.start(CHECK_PERMISSION);
        PermissionStrings.Handler handler = permissionService.getPermissionStrings(user.getId());
        Set<PermissionStringDto> permissionStrings = handler.get();

        content.removeIf(proofOfDelivery -> {
            UUID receivingFacilityId = proofOfDelivery.getReceivingFacilityId();
            UUID supplyingFacilityId = proofOfDelivery.getSupplyingFacilityId();
            UUID programId = proofOfDelivery.getProgramId();

            return permissionStrings.stream()
                    .noneMatch(elem -> elem.match(PODS_MANAGE, receivingFacilityId, programId)
                            || elem.match(PODS_VIEW, receivingFacilityId, programId)
                            || elem.match(SHIPMENTS_EDIT, supplyingFacilityId, null));
        });
    }

    profiler.start("BUILD_DTOS");
    List<ProofOfDeliveryDto> dto = dtoBuilder.build(content);

    profiler.start("BUILD_DTO_PAGE");
    Page<ProofOfDeliveryDto> dtoPage = Pagination.getPage(dto, pageable);

    profiler.stop().log();
    XLOGGER.exit(dtoPage);

    return dtoPage;
}

From source file:com.addthis.hydra.job.alert.JobAlertRunner.java

/**
 * Returns alerts for the given job id. Does not look up aliases for a job id. If job id is an alias, will
 * return any alerts that are configured on the alias, but will not look up alerts on the actual job id.
 *///  w  w  w . j  a  v  a2 s.  co m
public Set<AbstractJobAlert> getAlertsForJob(String jobId) {
    Set<String> alertIds = ImmutableSet.copyOf(jobToAlertsMap.get(jobId));
    return alertIds.stream().map(alertMap::get).collect(Collectors.toSet());
}

From source file:com.synopsys.detect.doctor.DoctorApplication.java

@Override
public void run(final ApplicationArguments applicationArguments) throws Exception {
    PropertyMap<DoctorProperty> doctorPropertyPropertyMap = new PropertyMap<>();
    SpringPropertySource springPropertySource = new SpringPropertySource(configurableEnvironment);
    DoctorConfiguration doctorConfiguration = new DoctorConfiguration(springPropertySource,
            doctorPropertyPropertyMap);/*  w  w  w .  j  a v  a  2 s .c o m*/

    DoctorArgumentStateParser argumentStateParser = new DoctorArgumentStateParser();
    DoctorArgumentState state = argumentStateParser.parseArgs(applicationArguments.getSourceArgs());

    doctorConfiguration.init();

    DoctorRun doctorRun = DoctorRun.createDefault();

    logger.info("Doctor begin: " + doctorRun.getRunId());

    DoctorDirectoryManager doctorDirectoryManager = new DoctorDirectoryManager(doctorRun);

    logger.info("Doctor ready.");

    Optional<DetectRunInfo> detectRunInfo = Optional.empty();

    File diagnosticZip = new File(doctorConfiguration.getProperty(DoctorProperty.DETECT_DIAGNOSTIC_FILE));
    if (diagnosticZip.exists()) {
        logger.info("A diagnostic zip was found: " + diagnosticZip.getAbsolutePath());
        DiagnosticParser diagnosticParser = new DiagnosticParser();
        detectRunInfo = Optional
                .of(diagnosticParser.processDiagnosticZip(doctorDirectoryManager, diagnosticZip));
    } else {
        logger.info("No diagnostic zip provided, looking for the pieces.");
        File log = new File(doctorConfiguration.getProperty(DoctorProperty.DETECT_LOG_FILE));

        logger.info("Looking for log file at: " + log.getAbsolutePath());
        if (log.exists()) {
            logger.info("Found log file.");
            // detectRunInfo = Optional.of(new DetectRunInfo(log));
        } else {
            logger.info("No log file found.");
        }
    }

    if (detectRunInfo.isPresent()) {

        DetectLogParser logParser = new DetectLogParser();

        logger.info("Doctor can proceed, necessary pieces located.");

        File log = detectRunInfo.get().getLogFile();

        DetectLogParseResult result = logParser.parse(log);

        logger.info("Detect log parsed.");

        String extractionId = doctorConfiguration.getProperty(DoctorProperty.DETECT_EXTRACTION_ID);

        Set<String> extractions = new HashSet<>();

        LoggedDetectExtraction extraction = null;
        for (LoggedDetectExtraction possibleExtraction : result.loggedConfiguration.extractions) {
            extractions.add(possibleExtraction.extractionIdentifier);
            if (possibleExtraction.extractionIdentifier.equals(extractionId)) {
                extraction = possibleExtraction;
            }
        }

        if (StringUtils.isBlank(extractionId)) {
            quit("Doctor needs an extraction to work with, options are: "
                    + extractions.stream().collect(Collectors.joining(",")));
        }

        if (extraction == null) {
            quit("No extraction found for given id: " + extractionId);
        }

        logger.info("Found extraction with id: " + extractionId);
        logger.info("Doctor will attempt to diagnose!");

        logger.info("We begin by rebuilding the configuration.");
        Map<String, String> propertyMap = new HashMap<>();
        result.loggedConfiguration.loggedPropertyList.stream().forEach(it -> propertyMap.put(it.key, it.value));
        RehydratedPropertySource rehydratedPropertySource = new RehydratedPropertySource(propertyMap);
        DetectConfiguration detectConfiguration = new DetectConfiguration(
                new DetectPropertySource(rehydratedPropertySource), new DetectPropertyMap());

        ExtractionHandler extractionHandler = new ExtractionHandler();
        extractionHandler.processExtraction(extraction, detectRunInfo.get(), detectConfiguration);

    } else {
        quit("Neccessary pieces not found for doctor to proceed.");
    }

}