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:energy.usef.core.service.business.CorePlanboardBusinessServiceTest.java

@SuppressWarnings("unchecked")
@Test//from  w ww . ja  va2  s. c  o m
public void testStoreCongestionPoints() throws IOException {
    StringWriter xmlWriter = new StringWriter();
    String commonReferenceQueryResponseFile = "energy/usef/core/service/business/common_reference_query_response_dso.xml";
    IOUtils.copy(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(commonReferenceQueryResponseFile), xmlWriter);
    CommonReferenceQueryResponse message = XMLUtil.xmlToMessage(xmlWriter.toString(),
            CommonReferenceQueryResponse.class);

    ConnectionGroup cg = new CongestionPointConnectionGroup();
    cg.setUsefIdentifier("ean.1111111111");

    PowerMockito.when(connectionGroupStateRepository
            .findActiveConnectionGroupStatesOfType(Matchers.any(LocalDate.class), Matchers.any(Class.class)))
            .then(invocation -> {
                ConnectionGroup connectionGroup3 = new CongestionPointConnectionGroup();
                connectionGroup3.setUsefIdentifier("ean.3333333333");
                Connection connection = new Connection();
                connection.setEntityAddress("ean.1000000005");
                ConnectionGroupState connectionGroupState = new ConnectionGroupState();
                connectionGroupState.setConnectionGroup(connectionGroup3);
                connectionGroupState.setConnection(connection);
                connectionGroupState.setValidFrom(((LocalDate) invocation.getArguments()[0]).minusDays(1));
                connectionGroupState.setValidUntil(((LocalDate) invocation.getArguments()[0]).plusDays(2));
                return Collections.singletonList(connectionGroupState);
            });
    PowerMockito
            .when(connectionGroupStateRepository.findEndingConnectionGroupStates(Matchers.any(LocalDate.class),
                    Matchers.eq(CongestionPointConnectionGroup.class)))
            .then(invocation -> IntStream.rangeClosed(1, 2).mapToObj(index -> {
                ConnectionGroupState connectionGroupState = new ConnectionGroupState();
                connectionGroupState.setValidFrom(((LocalDate) invocation.getArguments()[0]).minusDays(3));
                connectionGroupState.setValidUntil((LocalDate) invocation.getArguments()[0]);
                Connection connection = new Connection();
                connection.setEntityAddress("ean.100000000" + index);
                connectionGroupState.setConnection(connection);
                connectionGroupState.setConnectionGroup(cg);
                return connectionGroupState;
            }).collect(Collectors.toList()));
    PowerMockito.when(connectionRepository.findOrCreate(Matchers.any(String.class))).then(invocation -> {
        Connection connection = new Connection();
        connection.setEntityAddress((String) invocation.getArguments()[0]);
        return connection;
    });
    PowerMockito.when(congestionPointConnectionGroupRepository.findOrCreate(Matchers.any(String.class),
            Matchers.any(String.class))).then(invocation -> {
                CongestionPointConnectionGroup congestionPointConnectionGroup = new CongestionPointConnectionGroup();
                congestionPointConnectionGroup.setUsefIdentifier((String) invocation.getArguments()[0]);
                congestionPointConnectionGroup.setDsoDomain((String) invocation.getArguments()[1]);
                return congestionPointConnectionGroup;
            });
    PowerMockito.when(connectionGroupRepository.find(Matchers.any(String.class))).thenReturn(null);
    corePlanboardBusinessService.storeCommonReferenceQueryResponse(message,
            CommonReferenceEntityType.CONGESTION_POINT, DateTimeUtil.getCurrentDate().plusDays(7), 3);
    ArgumentCaptor<ConnectionGroupState> connectionGroupStateCaptor = ArgumentCaptor
            .forClass(ConnectionGroupState.class);
    Mockito.verify(connectionGroupStateRepository, Mockito.times(6))
            .persist(connectionGroupStateCaptor.capture());

    List<ConnectionGroupState> persistedConnectionGroupStates = connectionGroupStateCaptor.getAllValues();
    Assert.assertEquals(6, persistedConnectionGroupStates.size());
    for (ConnectionGroupState cgs : persistedConnectionGroupStates) {
        Assert.assertNotNull(cgs);
        Assert.assertNotNull(cgs.getConnection());
        Assert.assertNotNull(cgs.getConnectionGroup());
        Assert.assertTrue(cgs.getConnectionGroup() instanceof CongestionPointConnectionGroup);
    }
}

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

protected static void replenishDocsForDeletion(MongoDbCrudService<TestBean, String> service) {

    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, false);/*from  w  ww  .  j av  a2 s  .  c  o m*/

    assertEquals(10, service._state.orig_coll.count());
}

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

@Test
public void testStoreConnections() throws IOException {
    StringWriter xmlWriter = new StringWriter();
    String commonReferenceQueryResponseFile = "energy/usef/core/service/business/common_reference_query_response.xml";
    IOUtils.copy(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(commonReferenceQueryResponseFile), xmlWriter);
    CommonReferenceQueryResponse message = XMLUtil.xmlToMessage(xmlWriter.toString(),
            CommonReferenceQueryResponse.class);

    ConnectionGroup brpConnectionGroup = new BrpConnectionGroup();
    brpConnectionGroup.setUsefIdentifier("brp1.usef-example.com");

    PowerMockito/*from w w  w. ja  v a  2s . co  m*/
            .when(connectionGroupStateRepository.findEndingConnectionGroupStates(Matchers.any(LocalDate.class),
                    Matchers.eq(BrpConnectionGroup.class)))
            .then(invocation -> IntStream.rangeClosed(1, 2).mapToObj(index -> {
                Connection connection = new Connection();
                connection.setEntityAddress("ean.10000000000" + index);
                return connection;
            }).map(connection -> {
                ConnectionGroupState connectionGroupState = new ConnectionGroupState();
                connectionGroupState.setConnection(connection);
                connectionGroupState.setConnectionGroup(brpConnectionGroup);
                connectionGroupState.setValidFrom(((LocalDate) invocation.getArguments()[0]).minusDays(3));
                connectionGroupState.setValidUntil((LocalDate) invocation.getArguments()[0]);
                return connectionGroupState;
            }).collect(Collectors.toList()));

    PowerMockito.when(connectionGroupStateRepository.findActiveConnectionGroupStatesOfType(
            Matchers.any(LocalDate.class), Matchers.eq(BrpConnectionGroup.class))).then(invocation -> {
                Connection connection = new Connection();
                connection.setEntityAddress("ean.100000000003");
                ConnectionGroupState connectionGroupState = new ConnectionGroupState();
                connectionGroupState.setConnection(connection);
                connectionGroupState.setConnectionGroup(brpConnectionGroup);
                connectionGroupState.setValidFrom(((LocalDate) invocation.getArguments()[0]).minusDays(1));
                connectionGroupState.setValidFrom(((LocalDate) invocation.getArguments()[0]).plusDays(2));
                return Collections.singletonList(connectionGroupState);
            });

    corePlanboardBusinessService.storeCommonReferenceQueryResponse(message, CommonReferenceEntityType.BRP,
            DateTimeUtil.getCurrentDate().plusDays(7), 3);
    Mockito.verify(connectionGroupStateRepository, Mockito.times(2))
            .persist(Matchers.any(ConnectionGroupState.class));
}

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

protected static void replenishDocsForDeletion_JSON(MongoDbCrudService<JsonNode, String> service) {

    final List<JsonNode> 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())
            .map(b -> BeanTemplateUtils.toJson(b)).collect(Collectors.toList());

    service.storeObjects(l, false);// www .j  a va 2s  .c o  m

    assertEquals(10, service._state.orig_coll.count());
}

From source file:com.ikanow.aleph2.logging.service.TestLoggingService.java

@SuppressWarnings("unchecked")
@Test/*from www. ja v a  2s .c  o  m*/
public void test_logRules() throws InterruptedException, ExecutionException {
    final String subsystem_name = "logging_test7";
    final int num_messages_to_log = 50;
    final DataBucketBean test_bucket = getTestBucket("test7", Optional.of(Level.ALL.toString()),
            Optional.empty());
    final IBucketLogger user_logger = logging_service.getLogger(test_bucket);
    final IBucketLogger system_logger = logging_service.getSystemLogger(test_bucket);
    final IBucketLogger external_logger = logging_service.getExternalLogger(subsystem_name);
    //log a few messages
    IntStream.rangeClosed(1, num_messages_to_log).boxed().forEach(i -> {
        //NOTE HAVE TO DO TIME RULE FIRST, BECAUSE IT WILL GET UPDATED EVERY OTHER SUCCESSFUL LOG MESSAGE
        //rule: to log every 30s, should only log the first time, then test should finish before 2nd one is allowed
        //should result in 1 message each
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message1 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1", Arrays.asList(LoggingRules.logEveryMilliseconds(500000)), Optional.empty(),
                LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message1 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1", Arrays.asList(LoggingRules.logEveryMilliseconds(500000)), Optional.empty(),
                LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message1 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1", Arrays.asList(LoggingRules.logEveryMilliseconds(500000)), Optional.empty(),
                LoggingMergeFunctions.replaceMessage());

        //rule: log every 5 messages
        //should result in num_messages_to_log/5 each aka 10 each
        //NOTE count field has to go on its own key, because count is being increased for every successful message in any of the tests
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message2 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key2", Arrays.asList(LoggingRules.logEveryCount(5)), Optional.empty(),
                LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message2 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key2", Arrays.asList(LoggingRules.logEveryCount(5)), Optional.empty(),
                LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message2 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key2", Arrays.asList(LoggingRules.logEveryCount(5)), Optional.empty(),
                LoggingMergeFunctions.replaceMessage());

        //rule: log if max over threshold
        //should result in 44 message over each
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message3 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(6.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message3 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(6.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message3 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(6.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());

        //rule: log if min under threshold
        //should result in 1 under each
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message4 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.of(2.0), Optional.empty())),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message4 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.of(2.0), Optional.empty())),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message4 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.of(2.0), Optional.empty())),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());

        //rule: log if min/max outside thresholds
        //should result in 1 message under, 44 over each (45 each)
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message5 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.of(2.0), Optional.of(6.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message5 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.of(2.0), Optional.of(6.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message5 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.of(2.0), Optional.of(6.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());

        //test multi rules rule: log every 2 messages, or if max over threshold of 45
        //should result in 22 messages + 5 messages (27 each) was 202 got 302
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message6 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(LoggingRules.logEveryCount(2),
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(45.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message6 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(LoggingRules.logEveryCount(2),
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(45.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message6 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key1",
                Arrays.asList(LoggingRules.logEveryCount(2),
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(45.0))),
                Optional.empty(), LoggingMergeFunctions.replaceMessage());

        //test output formatter, doesn't do anything special, adds 44 messages each
        user_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message7 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key3",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(6.0))),
                Optional.of((b) -> {
                    return BeanTemplateUtils.clone(b).with(BasicMessageBean::message, "gestapo!").done();
                }), LoggingMergeFunctions.replaceMessage());
        system_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message7 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key3",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(6.0))),
                Optional.of((b) -> {
                    return BeanTemplateUtils.clone(b).with(BasicMessageBean::message, "gestapo!").done();
                }), LoggingMergeFunctions.replaceMessage());
        external_logger.log(Level.ERROR,
                ErrorUtils.lazyBuildMessage(true, () -> subsystem_name, () -> "test_message7 " + i, () -> null,
                        () -> "no error", () -> ImmutableMap.of(VALUE_FIELD, (double) i)),
                "key3",
                Arrays.asList(
                        LoggingRules.logOutsideThreshold(VALUE_FIELD, Optional.empty(), Optional.of(6.0))),
                Optional.of((b) -> {
                    return BeanTemplateUtils.clone(b).with(BasicMessageBean::message, "gestapo!").done();
                }), LoggingMergeFunctions.replaceMessage());
    });

    user_logger.flush();
    system_logger.flush();
    external_logger.flush();

    //check its in ES, wait 10s max for the index to refresh
    final DataBucketBean logging_test_bucket = BucketUtils.convertDataBucketBeanToLogging(test_bucket);
    final IDataWriteService<JsonNode> logging_crud = search_index_service.getDataService().get()
            .getWritableDataService(JsonNode.class, logging_test_bucket, Optional.empty(), Optional.empty())
            .get();
    waitForResults(logging_crud, 10, (1 + 10 + 44 + 1 + 45 + 27 + 44) * 2);
    assertEquals((1 + 10 + 44 + 1 + 45 + 27 + 44) * 2, logging_crud.countObjects().get().longValue());

    final DataBucketBean logging_external_test_bucket = BucketUtils
            .convertDataBucketBeanToLogging(BeanTemplateUtils.clone(test_bucket)
                    .with(DataBucketBean::full_name, "/external/" + subsystem_name + "/").done());
    final IDataWriteService<BasicMessageBean> logging_crud_external = search_index_service.getDataService()
            .get().getWritableDataService(BasicMessageBean.class, logging_external_test_bucket,
                    Optional.empty(), Optional.empty())
            .get();
    waitForResults(logging_crud_external, 10, 1 + (num_messages_to_log / 5) + 44 + 1 + 45 + 27 + 44);
    assertEquals(1 + (num_messages_to_log / 5) + 44 + 1 + 45 + 27 + 44,
            logging_crud_external.countObjects().get().longValue());

    //cleanup
    logging_crud.deleteDatastore().get();
}

From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java

@Test
public void singleObjectRetrieve_autoIds() throws InterruptedException, ExecutionException {
    final ElasticsearchCrudService<TestBean> service = getTestService("singleObjectRetrieve_autoIds",
            TestBean.class);

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

    for (TestBean t : l) {
        service.storeObject(t).get();/*from   w ww.  j a  va  2 s .c  o  m*/
    }
    assertEquals(10, service.countObjects().get().intValue());

    final Future<Optional<TestBean>> obj1 = service
            .getObjectBySpec(CrudUtils.allOf(TestBean.class).when("test_string", "test_string1"));
    assertTrue("Object with auto id is found", obj1.get().isPresent());
    assertTrue("Obj with auto id has an id", null != obj1.get().get()._id);

}

From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java

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

    final ElasticsearchCrudService<TestBean> service = getTestService("singleObjectRetrieve", TestBean.class);

    final List<TestBean> l = IntStream.rangeClosed(1, 10).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());

    for (TestBean t : l) {
        service.storeObject(t).get();/*ww w.  jav  a2s  .c o  m*/
    }

    assertEquals(10, service.countObjects().get().intValue());

    service.optimizeQuery(Arrays.asList("test_string")).get(); // (The get() waits for completion)

    // 1) Get object by _id, exists

    final Future<Optional<TestBean>> obj1 = service.getObjectById("id1");

    //DEBUG
    //sysOut(mapper.convertToDbObject(obj1.get().get()).toString());

    assertEquals("{\"_id\":\"id1\",\"test_string\":\"test_string1\",\"test_long\":1}",
            BeanTemplateUtils.toJson(obj1.get().get()).toString());

    // 2) Get object by _id, exists, subset of fields

    // 2a) inclusive:

    final Future<Optional<TestBean>> obj2a = service.getObjectById("id2", Arrays.asList("_id", "test_string"),
            true);

    //DEBUG
    //sysOut(mapper.convertToDbObject(obj2a.get().get()).toString());

    assertEquals("{\"_id\":\"id2\",\"test_string\":\"test_string2\"}",
            BeanTemplateUtils.toJson(obj2a.get().get()).toString());

    // 2b) exclusive:

    final Future<Optional<TestBean>> obj2b = service.getObjectById("id3", Arrays.asList("_id", "test_string"),
            false);

    //DEBUG
    //sysOut(mapper.convertToDbObject(obj2b.get().get()).toString());

    assertEquals("{\"_id\":\"id3\",\"test_long\":3}", BeanTemplateUtils.toJson(obj2b.get().get()).toString());

    // 3) Get object by _id, doesn't exist

    final Future<Optional<TestBean>> obj3 = service.getObjectById("id100", Arrays.asList("_id", "test_string"),
            false);

    assertEquals(false, obj3.get().isPresent());

    // 4) Get object by spec, exists

    final QueryComponent<TestBean> query = CrudUtils.allOf(TestBean.class).when("_id", "id4")
            .withAny("test_string", Arrays.asList("test_string1", "test_string4")).withPresent("test_long");

    final Future<Optional<TestBean>> obj4 = service.getObjectBySpec(query);

    assertEquals("{\"_id\":\"id4\",\"test_string\":\"test_string4\",\"test_long\":4}",
            BeanTemplateUtils.toJson(obj4.get().get()).toString());

    // 5) Get object by spec, exists, subset of fields

    final Future<Optional<TestBean>> obj5 = service.getObjectBySpec(query, Arrays.asList("_id", "test_string"),
            true);

    assertEquals("{\"_id\":\"id4\",\"test_string\":\"test_string4\"}",
            BeanTemplateUtils.toJson(obj5.get().get()).toString());

    // 6) Get object by spec, doesn't exist

    final QueryComponent<TestBean> query6 = CrudUtils.allOf(TestBean.class).when("_id", "id3")
            .withAny("test_string", Arrays.asList("test_string1", "test_string4")).withPresent("test_long");

    final Future<Optional<TestBean>> obj6 = service.getObjectBySpec(query6, Arrays.asList("_id", "test_string"),
            false);
    assertEquals(false, obj6.get().isPresent());
}

From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java

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

    final ElasticsearchCrudService<TestBean> service = getTestService("multiObjectRetrieve", TestBean.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).get();//from   www. j  a v  a 2 s  . c  o m

    assertEquals(10, service.countObjects().get().intValue());

    service.optimizeQuery(Arrays.asList("test_string")).get(); // (The get() waits for completion)

    // 1) Simple retrieve, no fields specified - sort

    final QueryComponent<TestBean> query = CrudUtils.allOf(TestBean.class)
            .rangeAbove("test_string", "test_string4", 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 JsonNode first_obj = BeanTemplateUtils.toJson(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("test_string", "test_string4", 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 JsonNode first_obj = BeanTemplateUtils.toJson(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("test_string", "test_string9", 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");
    }

    // 4) Test on an index that doens't exists, check the same

    final ElasticsearchCrudService<TestBean> service2 = getTestService("multiObjectRetrieve_missing",
            TestBean.class, false, Optional.empty());

    final QueryComponent<TestBean> query_4 = CrudUtils.allOf(TestBean.class)
            .rangeAbove("test_string", "test_string9", true).withPresent("test_long").limit(4);

    try (Cursor<TestBean> cursor = service2.getObjectsBySpec(query_4, 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:energy.usef.core.service.business.CorePlanboardBusinessServiceTest.java

@Test
public void testFindLastPrognosesLocalDatePrognosisTypeStringDocumentStatus() throws Exception {
    final LocalDate period = new LocalDate(2015, 1, 1);
    final String usefIdentifier = "brp1.usef-example.com";

    Mockito.when(ptuPrognosisRepository.findLastPrognoses(Matchers.any(LocalDate.class),
            Matchers.eq(Optional.of(energy.usef.core.model.PrognosisType.A_PLAN)), Matchers.any(Optional.class),
            Matchers.eq(Optional.of(DocumentStatus.ACCEPTED))))
            .then(call -> IntStream.rangeClosed(1, 96).mapToObj(index -> {
                PtuPrognosis ptuPrognosis = new PtuPrognosis();
                PtuContainer ptuContainer = new PtuContainer((LocalDate) call.getArguments()[0], index);
                ptuPrognosis.setType(energy.usef.core.model.PrognosisType.A_PLAN);
                ptuPrognosis.setConnectionGroup(new BrpConnectionGroup(usefIdentifier));
                ptuPrognosis.setPtuContainer(ptuContainer);
                return ptuPrognosis;
            }).collect(Collectors.toList()));

    // invocation
    List<PtuPrognosis> lastPrognoses = corePlanboardBusinessService.findLastPrognoses(period,
            energy.usef.core.model.PrognosisType.A_PLAN, usefIdentifier, DocumentStatus.ACCEPTED);
    // assertions
    Assert.assertNotNull(lastPrognoses);
    Assert.assertEquals(96, lastPrognoses.size());
    Mockito.verify(ptuPrognosisRepository, Mockito.times(1)).findLastPrognoses(Matchers.eq(period),
            Matchers.eq(Optional.of(energy.usef.core.model.PrognosisType.A_PLAN)),
            Matchers.eq(Optional.of(usefIdentifier)), Matchers.eq(Optional.of(DocumentStatus.ACCEPTED)));

}

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

@Test
public void testFindLastPrognosesLocalDatePrognosisTypeString() throws Exception {
    final LocalDate period = new LocalDate(2015, 1, 1);
    final String usefIdentifier = "brp1.usef-example.com";

    Mockito.when(ptuPrognosisRepository.findLastPrognoses(Matchers.any(LocalDate.class),
            Matchers.eq(Optional.of(energy.usef.core.model.PrognosisType.A_PLAN)), Matchers.any(Optional.class),
            Matchers.eq(Optional.empty()))).then(call -> IntStream.rangeClosed(1, 96).mapToObj(index -> {
                PtuPrognosis ptuPrognosis = new PtuPrognosis();
                PtuContainer ptuContainer = new PtuContainer((LocalDate) call.getArguments()[0], index);
                ptuPrognosis.setType(energy.usef.core.model.PrognosisType.A_PLAN);
                ptuPrognosis.setConnectionGroup(new BrpConnectionGroup(usefIdentifier));
                ptuPrognosis.setPtuContainer(ptuContainer);
                return ptuPrognosis;
            }).collect(Collectors.toList()));

    // invocation
    List<PtuPrognosis> lastPrognoses = corePlanboardBusinessService.findLastPrognoses(period,
            energy.usef.core.model.PrognosisType.A_PLAN, usefIdentifier);
    // assertions
    Assert.assertNotNull(lastPrognoses);
    Assert.assertEquals(96, lastPrognoses.size());
    Mockito.verify(ptuPrognosisRepository, Mockito.times(1)).findLastPrognoses(Matchers.eq(period),
            Matchers.eq(Optional.of(energy.usef.core.model.PrognosisType.A_PLAN)),
            Matchers.eq(Optional.of(usefIdentifier)), Matchers.eq(Optional.empty()));
}