Example usage for java.util.stream IntStream rangeClosed

List of usage examples for java.util.stream IntStream rangeClosed

Introduction

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

Prototype

public static IntStream rangeClosed(int startInclusive, int endInclusive) 

Source Link

Document

Returns a sequential ordered IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1 .

Usage

From source file:com.carlomicieli.jtrains.value.objects.DeliveryDate.java

/**
 * Returns the list of {@code DeliveryDate}.
 * <p>//  www. j  a  va2 s . c  o  m
 * This methods provides two different years ranges:
 * <ul>
 * <li>since {@code endYearWithQuarters} back to {@code startYearWithQuarters}
 * the years are listed with quarter information;
 * <li>since {@code endYearWithoutQuarters} back to {@code startYearWithoutQuarters}
 * the years are listed without quarter information.
 * </ul>
 * </p>
 *
 * @param startYearWithoutQuarters the first year without quarters
 * @param endYearWithoutQuarters   the last year without quarters
 * @param startYearWithQuarters    the first year with quarters
 * @param endYearWithQuarters      the last year with quarters
 * @return the {@code DeliveryDate} list
 */
public static Stream<DeliveryDate> range(int startYearWithoutQuarters, int endYearWithoutQuarters,
        int startYearWithQuarters, int endYearWithQuarters) {

    Assert.isTrue(startYearWithoutQuarters <= endYearWithoutQuarters,
            "DeliveryDate: startYearWithoutQuarters <= endYearWithoutQuarters");
    Assert.isTrue(startYearWithQuarters <= endYearWithQuarters,
            "DeliveryDate: startYearWithQuarters <= endYearWithQuarters");

    Function<Integer, Stream<DeliveryDate>> deliveryDatesForYear = year -> quarters()
            .mapToObj(qtr -> DeliveryDate.of(year, qtr));

    return Stream.concat(
            IntStream.rangeClosed(startYearWithQuarters, endYearWithQuarters).boxed()
                    .flatMap(deliveryDatesForYear),
            IntStream.rangeClosed(startYearWithoutQuarters, endYearWithoutQuarters).mapToObj(DeliveryDate::of))
            .sorted(deliveryDateComparator().reversed());
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.vm.AzureVMsProvider.java

private List<Creatable<VirtualMachine>> prepareCreatableVirtualMachines(Azure azureService,
        Optional<Options> options, Region region, ResourceGroup resourceGroup, String instanceTag,
        Instance instance, VirtualMachineCustomImage image, Optional<Boolean> optionalStaticPublicIP) {

    // Prepare a new virtual private network (same for all VMs)
    Optional<String> optionalPrivateNetworkCIDR = options.map(Options::getPrivateNetworkCIDR);
    Creatable<Network> creatableVirtualNetwork = azureProviderNetworkingUtils.prepareVirtualNetwork(
            azureService, region, resourceGroup, createUniqueVirtualNetworkName(instanceTag),
            optionalPrivateNetworkCIDR.orElse(defaultPrivateNetworkCidr));

    // Get existing virtual private network if specified
    Optional<Network> optionalVirtualNetwork = options.map(Options::getSubnetId)
            .map(subnetId -> azureProviderUtils.searchVirtualNetworkByName(azureService, subnetId).get());

    // Prepare a new  security group (same for all VMs)
    Creatable<NetworkSecurityGroup> creatableNetworkSecurityGroup = azureProviderNetworkingUtils
            .prepareProactiveNetworkSecurityGroup(azureService, region, resourceGroup,
                    createUniqueSecurityGroupName(instance.getTag()));

    // Get existing security group if specified
    Optional<NetworkSecurityGroup> optionalNetworkSecurityGroup = options.map(Options::getSecurityGroupNames)
            .map(secGrpNames -> secGrpNames.get(0)).map(secGrpName -> azureProviderUtils
                    .searchNetworkSecurityGroupByName(azureService, secGrpName).get());

    // Get existing public IP address if specified
    Optional<PublicIpAddress> optionalPublicIpAddress = options.map(Options::getPublicIpAddress)
            .map(publicIpAddress -> azureProviderUtils.searchPublicIpAddressByIp(azureService, publicIpAddress)
                    .get());// w  ww . j  a  v a  2s  .  com

    return IntStream
            .rangeClosed(1,
                    Integer.valueOf(Optional.ofNullable(instance.getNumber()).orElse(SINGLE_INSTANCE_NUMBER)))
            .mapToObj(instanceNumber -> {
                // Create a new public IP address (one per VM)
                String publicIPAddressName = createUniquePublicIPName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<PublicIpAddress> creatablePublicIpAddress = azureProviderNetworkingUtils
                        .preparePublicIPAddress(azureService, region, resourceGroup, publicIPAddressName,
                                optionalStaticPublicIP.orElse(DEFAULT_STATIC_PUBLIC_IP));

                // Prepare a new network interface (one per VM)
                String networkInterfaceName = createUniqueNetworkInterfaceName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<NetworkInterface> creatableNetworkInterface = azureProviderNetworkingUtils
                        .prepareNetworkInterface(azureService, region, resourceGroup, networkInterfaceName,
                                creatableVirtualNetwork, optionalVirtualNetwork.orElse(null),
                                creatableNetworkSecurityGroup, optionalNetworkSecurityGroup.orElse(null),
                                creatablePublicIpAddress,
                                instanceNumber == 1 ? optionalPublicIpAddress.orElse(null) : null);

                return prepareVirtualMachine(instance, azureService, resourceGroup, region,
                        createUniqueInstanceTag(instanceTag, instanceNumber), image, creatableNetworkInterface);
            }).collect(Collectors.toList());
}

From source file:io.yields.math.concepts.operator.SmoothnessTest.java

private static List<Tuple> createTuples(int polynomialOrder, RandomSequence<Double> generator,
        int nrOfElements) {
    return IntStream.rangeClosed(0, nrOfElements).mapToObj(index -> {
        double x = (generator.next() - .5);
        double y = Math.pow(x, polynomialOrder);
        return new Tuple(x, y);
    }).collect(Collectors.toList());
}

From source file:com.carlomicieli.jtrains.value.objects.DeliveryDate.java

private static IntStream quarters() {
    return IntStream.rangeClosed(1, 4);
}

From source file:es.uvigo.ei.sing.adops.datatypes.Project.java

public void addSequences(File fastaFile) throws IllegalArgumentException {
    try {// www.  j a va  2s .co m
        final int numSequences = this.listSequenceNames().size();

        writeSequences(this.originalFastaFile, loadAndCheckSequences(fastaFile), true);

        this.createNamesFile();

        final String inputSequences = IntStream.rangeClosed(1, numSequences).mapToObj(Integer::toString)
                .collect(Collectors.joining(" "));

        for (ProjectExperiment experiment : this.getExperiments()) {
            final Configuration configuration = experiment.getConfiguration();

            if (configuration.getInputSequences().isEmpty()) {
                configuration.setInputSequences(inputSequences);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalArgumentException(
                String.format("File %s is not a valid Fasta file", fastaFile.getAbsolutePath()), e);
    }

}

From source file:energy.usef.core.service.business.CorePlanboardBusinessServiceTest.java

@Before
public void init() {
    SequenceGeneratorService sequenceGeneratorService = new SequenceGeneratorService();
    corePlanboardBusinessService = new CorePlanboardBusinessService();
    Whitebox.setInternalState(corePlanboardBusinessService, sequenceGeneratorService);
    Whitebox.setInternalState(corePlanboardBusinessService, ptuContainerRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, ptuFlexOfferRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, ptuFlexOrderRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, ptuPrognosisRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, ptuFlexRequestRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, planboardMessageRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, connectionGroupRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, brpConnectionGroupRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, agrConnectionGroupRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, congestionPointConnectionGroupRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, connectionGroupStateRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, connectionRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, ptuStateRepository);
    Whitebox.setInternalState(corePlanboardBusinessService, config);

    PowerMockito.when(config.getIntegerProperty(Matchers.eq(ConfigParam.PTU_DURATION))).thenReturn(15);
    PowerMockito.when(ptuContainerRepository.findPtuContainersMap(Matchers.any(LocalDate.class)))
            .then(invocation -> IntStream.rangeClosed(1, 96).mapToObj(index -> {
                PtuContainer ptu = new PtuContainer();
                ptu.setPtuIndex(index);/*from   w  w  w .j a  v  a  2 s.c o  m*/
                ptu.setPtuDate((LocalDate) invocation.getArguments()[0]);
                return ptu;
            }).collect(Collectors.toMap(PtuContainer::getPtuIndex, Function.identity())));
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.AzureProvider.java

@Override
public Set<Instance> createInstance(Infrastructure infrastructure, Instance instance) {

    Azure azureService = azureServiceCache.getService(infrastructure);
    String instanceTag = Optional.ofNullable(instance.getTag()).orElseThrow(
            () -> new RuntimeException("ERROR missing instance tag/name from instance: '" + instance + "'"));

    // Check for Image by name first and then by id
    String imageNameOrId = Optional.ofNullable(instance.getImage()).orElseThrow(
            () -> new RuntimeException("ERROR missing Image name/id from instance: '" + instance + "'"));
    VirtualMachineCustomImage image = getImageByName(azureService, imageNameOrId)
            .orElseGet(() -> getImageById(azureService, imageNameOrId).orElseThrow(() -> new RuntimeException(
                    "ERROR unable to find custom Image: '" + instance.getImage() + "'")));

    // Get the options (Optional by design)
    Optional<Options> options = Optional.ofNullable(instance.getOptions());

    // Try to retrieve the resourceGroup from provided name, otherwise get it from image
    ResourceGroup resourceGroup = azureProviderUtils
            .searchResourceGroupByName(azureService,
                    options.map(Options::getResourceGroup).orElseGet(image::resourceGroupName))
            .orElseThrow(() -> new RuntimeException(
                    "ERROR unable to find a suitable resourceGroup from instance: '" + instance + "'"));

    // Try to get region from provided name, otherwise get it from image
    Region region = options.map(presentOptions -> Region.findByLabelOrName(presentOptions.getRegion()))
            .orElseGet(image::region);//from   w ww  . java  2 s  . c  o m

    // Prepare a new virtual private network (same for all VMs)
    Optional<String> optionalPrivateNetworkCIDR = options.map(Options::getPrivateNetworkCIDR);
    Creatable<Network> creatableVirtualNetwork = azureProviderUtils.prepareVirtualNetwork(azureService, region,
            resourceGroup, createUniqueVirtualNetworkName(instanceTag),
            optionalPrivateNetworkCIDR.orElse(DEFAULT_PRIVATE_NETWORK_CIDR));

    // Prepare a new  security group (same for all VMs)
    Creatable<NetworkSecurityGroup> creatableNetworkSecurityGroup = azureProviderUtils
            .prepareSSHNetworkSecurityGroup(azureService, region, resourceGroup,
                    createUniqueSecurityGroupName(instance.getTag()));

    // Prepare the VM(s)
    Optional<Boolean> optionalStaticPublicIP = options.map(Options::getStaticPublicIP);
    List<Creatable<VirtualMachine>> creatableVirtualMachines = IntStream
            .rangeClosed(1,
                    Integer.valueOf(Optional.ofNullable(instance.getNumber()).orElse(SINGLE_INSTANCE_NUMBER)))
            .mapToObj(instanceNumber -> {
                // Create a new public IP address (one per VM)
                String publicIPAddressName = createUniquePublicIPName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<PublicIpAddress> creatablePublicIPAddress = azureProviderUtils.preparePublicIPAddress(
                        azureService, region, resourceGroup, publicIPAddressName,
                        optionalStaticPublicIP.orElse(DEFAULT_STATIC_PUBLIC_IP));

                // Prepare a new network interface (one per VM)
                String networkInterfaceName = createUniqueNetworkInterfaceName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<NetworkInterface> creatableNetworkInterface = azureProviderUtils
                        .prepareNetworkInterfaceFromScratch(azureService, region, resourceGroup,
                                networkInterfaceName, creatableVirtualNetwork, creatableNetworkSecurityGroup,
                                creatablePublicIPAddress);

                return prepareVirtualMachine(instance, azureService, resourceGroup, region,
                        createUniqueInstanceTag(instanceTag, instanceNumber), image, creatableNetworkInterface);
            }).collect(Collectors.toList());

    // Create all VMs in parallel and collect IDs
    return azureService.virtualMachines().create(creatableVirtualMachines).values().stream()
            .map(vm -> instance.withTag(vm.name()).withId(vm.vmId()).withNumber(SINGLE_INSTANCE_NUMBER))
            .collect(Collectors.toSet());
}

From source file:io.github.retz.inttest.RetzIntTest.java

@Test
public void scheduleAppTest() throws Exception {
    URI uri = new URI("http://" + RETZ_HOST + ":" + RETZ_PORT);

    try (Client client = Client.newBuilder(uri).setAuthenticator(config.getAuthenticator()).build()) {
        loadSimpleApp(client, "echo2");

        List<EchoJob> finishedJobs = new LinkedList<>();
        List<Integer> argvList = IntStream.rangeClosed(0, 32).boxed().collect(Collectors.toList());
        argvList.addAll(Arrays.asList(42, 63, 64, 127, 128, 151, 192, 255));
        int jobNum = argvList.size();
        List<EchoJob> echoJobs = scheduleEchoJobs(client, "echo2", "echo.sh ", argvList);

        assertThat(echoJobs.size(), is(jobNum));

        for (int i = 0; i < 16; i++) {
            List<EchoJob> toRemove = toRemove(client, echoJobs, true);

            if (!toRemove.isEmpty()) {
                i = 0;// w  ww. j a  va  2s  .  c  o m
            }
            echoJobs.removeAll(toRemove);
            finishedJobs.addAll(toRemove);
            if (echoJobs.isEmpty()) {
                break;
            }
            Thread.sleep(1000);

            System.err.println(TimestampHelper.now() + ": Finished=" + ClientHelper.finished(client).size()
                    + ", Running=" + ClientHelper.running(client).size() + ", Scheduled="
                    + ClientHelper.queue(client).size());
            for (Job finished : ClientHelper.finished(client)) {
                assertThat(finished.retry(), is(0));
            }
        }
        assertThat(finishedJobs.size(), is(jobNum));

        assertThat(ClientHelper.finished(client).size(), greaterThanOrEqualTo(jobNum));
        assertThat(ClientHelper.running(client).size(), is(0));
        assertThat(ClientHelper.queue(client).size(), is(0));

        UnloadAppResponse unloadRes = (UnloadAppResponse) client.unload("echo2");
        assertThat(unloadRes.status(), is("ok"));
    }
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Expands the ranges.<br>//from  w  w  w.  ja  va  2s.  com
 * Example:
 * <ul>
 * <li>1-4 -> 1,2,3,4</li>
 * <li>1-4,6-8 -> 1,2,3,4,6,7,8</li>
 * </ul>
 *
 * @param ranges the ranges to expand
 * @return the expanded ranges.
 */
private static Optional<Stream<Integer>> expandRanges(List<String[]> ranges) { // TODO maybe as Integer[]
    return ranges.stream().map(
            eachRange -> IntStream.rangeClosed(Integer.valueOf(eachRange[0]), Integer.valueOf(eachRange[1])))
            .map(eachExpandedRange -> eachExpandedRange.mapToObj(Integer::valueOf)).reduce(Stream::concat);
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.TestMongoDbCrudService.java

@Test
public void testCreateMultipleObjects() throws InterruptedException, ExecutionException {

    final MongoDbCrudService<TestBean, String> service = getTestService("testCreateMultipleObjects",
            TestBean.class, String.class);

    // 1) Insertion without ids

    assertEquals(0, service._state.orig_coll.count());

    final List<TestBean> l = IntStream.rangeClosed(1, 10).boxed().map(
            i -> BeanTemplateUtils.build(TestBean.class).with("test_string", "test_string" + i).done().get())
            .collect(Collectors.toList());

    final Future<Tuple2<Supplier<List<Object>>, Supplier<Long>>> result = service.storeObjects(l);

    assertEquals(10, service._state.orig_coll.count());
    assertEquals((Long) (long) 10, result.get()._2().get());

    final List<Object> ids = result.get()._1().get();
    IntStream.rangeClosed(1, 10).boxed().map(i -> Tuples._2T(i, ids.get(i - 1))).forEach(io -> {
        final DBObject val = service._state.orig_coll.findOne(io._2());
        assertNotEquals(null, val);
        assertEquals("test_string" + io._1(), val.get("test_string"));
    });/*from  ww w  .j  ava  2 s . co  m*/

    // 2) Insertion with ids

    service._state.orig_coll.drop();

    final List<TestBean> l2 = IntStream.rangeClosed(51, 100).boxed().map(i -> BeanTemplateUtils
            .build(TestBean.class).with("_id", "id" + i).with("test_string", "test_string" + i).done().get())
            .collect(Collectors.toList());

    final Future<Tuple2<Supplier<List<Object>>, Supplier<Long>>> result_2 = service.storeObjects(l2);

    assertEquals(50, service._state.orig_coll.count());
    assertEquals((Long) (long) 50, result_2.get()._2().get());

    // 3) Check storeObjects(..., true) will succeed

    final List<TestBean> l3 = IntStream.rangeClosed(41, 110).boxed().map(i -> BeanTemplateUtils
            .build(TestBean.class).with("_id", "id" + i).with("test_string", "test_string" + i).done().get())
            .collect(Collectors.toList());

    final Future<Tuple2<Supplier<List<Object>>, Supplier<Long>>> result_3 = service.storeObjects(l3, true);

    assertEquals(70, service._state.orig_coll.count());
    assertEquals((Long) (long) 70, result_3.get()._2().get());

    // 4) Insertion with dups - fail and continue

    final List<TestBean> l4 = IntStream.rangeClosed(21, 120).boxed().map(i -> BeanTemplateUtils
            .build(TestBean.class).with("_id", "id" + i).with("test_string", "test_string" + i).done().get())
            .collect(Collectors.toList());

    final Future<Tuple2<Supplier<List<Object>>, Supplier<Long>>> result_4 = service.storeObjects(l4);

    try {
        assertEquals(100, service._state.orig_coll.count());
        assertEquals(100L, (long) result_4.get()._2().get());

        // Fongo and Mongo behave differently here:
        if (null != this._real_mongodb_connection) {
            fail("Should have thrown exception on duplicate insert, even though docs have been inserted");
        }
    } catch (Exception e) {
    }
}