Example usage for org.apache.commons.lang3.mutable MutableObject setValue

List of usage examples for org.apache.commons.lang3.mutable MutableObject setValue

Introduction

In this page you can find the example usage for org.apache.commons.lang3.mutable MutableObject setValue.

Prototype

@Override
public void setValue(final T value) 

Source Link

Document

Sets the value.

Usage

From source file:com.romeikat.datamessie.core.base.task.scheduling.IntervalTaskSchedulingThreadTest.java

private void run(final int taskExecutionInterval, final long taskExecutionDuration, final boolean allowOverlap,
        final boolean throwException) throws Exception {

    final MutableInt numberOfTaskExecutions = new MutableInt(0);
    final MutableInt numberOfTaskTriggerings = new MutableInt(0);
    final Task task = Mockito.spy(new FooTask() {
        @Override/*www .j  ava2 s .  co  m*/
        public void execute(final TaskExecution taskExecution) throws Exception {
            if (throwException) {
                throw new Exception();
            }
            numberOfTaskExecutions.add(1);
            Thread.sleep(taskExecutionDuration);
        }
    });
    final String taskName = task.getName();

    // Schedule task for multiple execution
    final MutableObject<LocalDateTime> startOfLatestCompletedTask = new MutableObject<LocalDateTime>();
    final FooIntervalTaskSchedulingThread intervalTaskSchedulingThread = new FooIntervalTaskSchedulingThread(
            task, taskName, taskExecutionInterval, allowOverlap, taskManager) {
        @Override
        protected boolean shouldStopTaskExecution() {
            return numberOfTaskTriggerings.intValue() == NUMBER_OF_TASK_EXECUTIONS;
        }

        @Override
        protected void onAfterTriggeringTask(final TaskExecution latestTaskExecution) {
            startOfLatestCompletedTask.setValue(LocalDateTime.now());
            numberOfTaskTriggerings.add(1);
        }

        @Override
        protected LocalDateTime getActualStartOfLatestCompletedTask() {
            return startOfLatestCompletedTask.getValue();
        }
    };
    intervalTaskSchedulingThread.start();

    // Wait until all executions are finished
    final long additionalWaiting = TaskManager.DEFAULT_MANAGEMENT_INTERVAL + 1000;
    final long timePerTaskExecution = throwException ? taskExecutionInterval
            : taskExecutionInterval + taskExecutionDuration;
    final long waitUntilTaskExecutionShouldBeFinished = NUMBER_OF_TASK_EXECUTIONS * timePerTaskExecution
            + additionalWaiting;
    Thread.sleep(waitUntilTaskExecutionShouldBeFinished);

    // Check executions
    final int expectedNumberOfTaskTriggerings = NUMBER_OF_TASK_EXECUTIONS;
    assertEquals(expectedNumberOfTaskTriggerings, numberOfTaskTriggerings.intValue());
    final int expectedNumbeOfTaskExecutions = throwException ? 0 : NUMBER_OF_TASK_EXECUTIONS;
    assertEquals(expectedNumbeOfTaskExecutions, numberOfTaskExecutions.intValue());
}

From source file:be.shad.tsqb.test.SelectTests.java

/**
 * Distinct subquery value selection/*w w  w .  ja va 2 s. co m*/
 */
@Test
public void selectDistinctSubquery() {
    House house = query.from(House.class);

    TypeSafeSubQuery<Long> subquery = query.subquery(Long.class);
    House subhouse = subquery.from(House.class);
    subquery.where(subhouse.getId()).lt(house.getId());
    subquery.select(subquery.hqlFunction().count());

    @SuppressWarnings("unchecked")
    MutableObject<Long> dto = query.select(MutableObject.class);
    dto.setValue(query.hqlFunction().distinct(subquery).select());

    validate(
            "select distinct (select count(*) from House hobj2 where hobj2.id < hobj1.id) as value from House hobj1");
}

From source file:com.romeikat.datamessie.core.base.service.DocumentService.java

public void deprocessDocumentsOfSource(final StatelessSession statelessSession,
        final TaskExecution taskExecution, final long sourceId, final DocumentProcessingState targetState)
        throws TaskCancelledException {
    // Initialize
    final TaskExecutionWork work = taskExecution.reportWorkStart(
            String.format("Deprocessing documents of source %s to state %s", sourceId, targetState.getName()));
    final StatisticsRebuildingSparseTable statisticsToBeRebuilt = new StatisticsRebuildingSparseTable();

    // Determine minimum downloaded date
    final LocalDate minDownloadedDate = getMinDownloadedDate(statelessSession);

    // Process all download dates one after another, starting with the minimum downloaded date
    final MutableObject<LocalDate> downloadedDate = new MutableObject<LocalDate>(minDownloadedDate);
    while (downloadedDate.getValue() != null) {
        // Deprocess
        deprocessDocumentsOfSourceAndDownloadDate(statelessSession, taskExecution, sourceId, targetState,
                statisticsToBeRebuilt, downloadedDate.getValue());

        // Prepare for next iteration
        final LocalDate nextDownloadedDate = getNextDownloadedDate(downloadedDate.getValue());
        downloadedDate.setValue(nextDownloadedDate);
    }//  w w  w  .  j a  v  a 2 s .  c  o  m

    // Rebuild statistics
    final IStatisticsManager statisticsManager = sharedBeanProvider.getSharedBean(IStatisticsManager.class);
    if (statisticsManager != null) {
        statisticsManager.rebuildStatistics(statisticsToBeRebuilt);
    }

    // Done
    taskExecution.reportWorkEnd(work);
}

From source file:io.restassured.itest.java.HttpClientConfigITest.java

@Test
public void http_client_config_allows_specifying_that_the_http_client_instance_is_reused_in_multiple_requests() {
    final MutableObject<HttpClient> client1 = new MutableObject<HttpClient>();
    final MutableObject<HttpClient> client2 = new MutableObject<HttpClient>();

    RestAssured.config = RestAssuredConfig.newConfig()
            .httpClient(HttpClientConfig.httpClientConfig().reuseHttpClientInstance());

    // When/*w w  w  .j ava 2  s .com*/
    try {
        given().param("url", "/hello").filter(new Filter() {
            public Response filter(FilterableRequestSpecification requestSpec,
                    FilterableResponseSpecification responseSpec, FilterContext ctx) {
                client1.setValue(requestSpec.getHttpClient());
                return ctx.next(requestSpec, responseSpec);
            }
        }).expect().body("hello", equalTo("Hello Scalatra")).when().get("/redirect");

        given().header("name", "value").filter((requestSpec, responseSpec, ctx) -> {
            client2.setValue(requestSpec.getHttpClient());
            return ctx.next(requestSpec, responseSpec);
        }).when().post("/reflect");
    } finally {
        RestAssured.reset();
    }

    assertThat(client1.getValue(), sameInstance(client2.getValue()));
}

From source file:io.restassured.itest.java.HttpClientConfigITest.java

@Test
public void local_http_client_config_doesnt_reuse_static_http_client_instance_when_local_config_specifies_reuse() {
    final MutableObject<HttpClient> client1 = new MutableObject<HttpClient>();
    final MutableObject<HttpClient> client2 = new MutableObject<HttpClient>();

    RestAssured.config = RestAssuredConfig.newConfig()
            .httpClient(HttpClientConfig.httpClientConfig().reuseHttpClientInstance());

    // When//from w w  w.  j  a  va 2  s .c  om
    try {
        given().param("url", "/hello").filter(new Filter() {
            public Response filter(FilterableRequestSpecification requestSpec,
                    FilterableResponseSpecification responseSpec, FilterContext ctx) {
                client1.setValue(requestSpec.getHttpClient());
                return ctx.next(requestSpec, responseSpec);
            }
        }).expect().body("hello", equalTo("Hello Scalatra")).when().get("/redirect");

        given().config(RestAssuredConfig.newConfig()
                .httpClient(HttpClientConfig.httpClientConfig().reuseHttpClientInstance()))
                .header("name", "value").filter(new Filter() {
                    public Response filter(FilterableRequestSpecification requestSpec,
                            FilterableResponseSpecification responseSpec, FilterContext ctx) {
                        client2.setValue(requestSpec.getHttpClient());
                        return ctx.next(requestSpec, responseSpec);
                    }
                }).when().post("/reflect");
    } finally {
        RestAssured.reset();
    }

    assertThat(client1.getValue(), not(sameInstance(client2.getValue())));
}

From source file:io.restassured.itest.java.HttpClientConfigITest.java

@Test
public void local_http_client_config_reuse_reuse_static_http_client_instance_when_local_config_changes_other_configs_than_http_client_config() {
    final MutableObject<HttpClient> client1 = new MutableObject<HttpClient>();
    final MutableObject<HttpClient> client2 = new MutableObject<HttpClient>();

    RestAssured.config = RestAssuredConfig.newConfig()
            .httpClient(HttpClientConfig.httpClientConfig().reuseHttpClientInstance());

    // When/* ww  w .  j  ava 2 s  .  c  om*/
    try {
        given().param("url", "/hello").filter(new Filter() {
            public Response filter(FilterableRequestSpecification requestSpec,
                    FilterableResponseSpecification responseSpec, FilterContext ctx) {
                client1.setValue(requestSpec.getHttpClient());
                return ctx.next(requestSpec, responseSpec);
            }
        }).expect().body("hello", equalTo("Hello Scalatra")).when().get("/redirect");

        given().
        // Here we only change the decoder config
                config(RestAssured.config.decoderConfig(DecoderConfig.decoderConfig().with()
                        .contentDecoders(DecoderConfig.ContentDecoder.DEFLATE)))
                .filter(new Filter() {
                    public Response filter(FilterableRequestSpecification requestSpec,
                            FilterableResponseSpecification responseSpec, FilterContext ctx) {
                        client2.setValue(requestSpec.getHttpClient());
                        return ctx.next(requestSpec, responseSpec);
                    }
                }).expect().body("Accept-Encoding", contains("deflate")).when().get("/headersWithValues");
    } finally {
        RestAssured.reset();
    }

    assertThat(client1.getValue(), sameInstance(client2.getValue()));
}

From source file:io.restassured.itest.java.HttpClientConfigITest.java

@Test
public void httpClientIsConfigurableFromAStaticHttpClientConfigWithOtherConfigurations() {
    // Given//from   w  w w .ja  va2  s .  c  om
    final MutableObject<HttpClient> client = new MutableObject<>();
    RestAssured.config = RestAssuredConfig.newConfig()
            .httpClient(HttpClientConfig.httpClientConfig().setParam(HANDLE_REDIRECTS, true).and()
                    .setParam(MAX_REDIRECTS, 0).and().httpClientFactory(SystemDefaultHttpClient::new));

    // When
    try {
        given().param("url", "/hello").filter(new Filter() {
            public Response filter(FilterableRequestSpecification requestSpec,
                    FilterableResponseSpecification responseSpec, FilterContext ctx) {
                client.setValue(requestSpec.getHttpClient());
                return ctx.next(requestSpec, responseSpec);
            }
        }).expect().body("hello", equalTo("Hello Scalatra")).when().get("/redirect");
    } finally {
        RestAssured.reset();
    }

    // Then
    assertThat(client.getValue(), instanceOf(SystemDefaultHttpClient.class));
}

From source file:fr.duminy.jbackup.core.JBackupImplTest.java

private void testBackup(ProgressListener listener) throws Throwable {
    final BackupConfiguration config = createConfiguration();
    final Task mockBackupTask = mock(Task.class);
    final MutableObject<TaskListener> actualTaskListener = new MutableObject<>();
    JBackupImpl jBackup = spy(new JBackupImpl() {
        @Override//from  w  w w. ja  v  a  2 s  . c o  m
        Task createBackupTask(BackupConfiguration config, TaskListener listener, Cancellable cancellable) {
            actualTaskListener.setValue(listener);
            return mockBackupTask;
        }
    });

    try {
        if (listener != null) {
            jBackup.addProgressListener(config.getName(), listener);
        }
        Future<Void> future = jBackup.backup(config);
        waitResult(future);
    } finally {
        jBackup.shutdown(null);
    }

    verify(jBackup, times(1)).backup(eq(config)); // called above
    verify(jBackup, times(1)).shutdown(isNull(TerminationListener.class)); // called above
    verify(jBackup, times(1)).createBackupTask(eq(config), eq(actualTaskListener.getValue()),
            notNull(Cancellable.class));
    verify(mockBackupTask, times(1)).call();
    if (listener != null) {
        verify(jBackup, times(1)).addProgressListener(eq(config.getName()), eq(listener));
    }
    verifyNoMoreInteractions(mockBackupTask, jBackup);
}

From source file:fr.duminy.jbackup.core.JBackupImplTest.java

@Test
public void testBackup_withCancellable() throws Throwable {
    // prepare test
    final BackupConfiguration config = createConfiguration();
    final MutableBoolean taskStarted = new MutableBoolean(false);
    final Task mockBackupTask = createAlwaysWaitingTask(Task.class, taskStarted);
    final MutableObject<Cancellable> actualCancellable = new MutableObject<>();
    final MutableObject<TaskListener> actualListener = new MutableObject<>();
    JBackupImpl jBackup = spy(new JBackupImpl() {
        @Override/* ww w  .ja v a  2  s  .c o  m*/
        Task createBackupTask(BackupConfiguration config, TaskListener listener, Cancellable cancellable) {
            actualListener.setValue(listener);
            actualCancellable.setValue(cancellable);
            return mockBackupTask;
        }
    });

    // test
    try {
        Future<Void> future = jBackup.backup(config);

        // wait task is actually started
        waitTaskStarted(taskStarted, actualCancellable);

        assertThat(actualCancellable.getValue()).as("cancellable").isNotNull();
        assertThat(actualCancellable.getValue().isCancelled()).as("cancelled").isFalse();

        future.cancel(true);
        assertThat(actualCancellable.getValue().isCancelled()).as("cancelled").isTrue();
    } finally {
        jBackup.shutdown(null);
    }

    // assertions
    InOrder inOrder = inOrder(mockBackupTask, jBackup);
    inOrder.verify(jBackup, times(1)).backup(eq(config)); // called above
    inOrder.verify(jBackup, times(1)).createBackupTask(eq(config), eq(actualListener.getValue()),
            eq(actualCancellable.getValue()));
    inOrder.verify(mockBackupTask, times(1)).call();
    inOrder.verify(jBackup, times(1)).shutdown(isNull(TerminationListener.class)); // called above
    inOrder.verifyNoMoreInteractions();
}

From source file:fr.duminy.jbackup.core.JBackupImplTest.java

private void testRestore(ProgressListener listener) throws Throwable {
    final Path archive = tempFolder.newFolder().toPath().resolve("archive.zip");
    final Path targetDirectory = tempFolder.newFolder().toPath();
    final BackupConfiguration config = createConfiguration();
    final Task mockRestoreTask = mock(Task.class);
    final MutableObject<TaskListener> actualTaskListener = new MutableObject<>();
    JBackupImpl jBackup = spy(new JBackupImpl() {
        @Override// w w w. ja va 2  s .co  m
        Task createRestoreTask(BackupConfiguration config, Path archive, Path targetDirectory,
                TaskListener taskListener, Cancellable cancellable) {
            actualTaskListener.setValue(taskListener);
            return mockRestoreTask;
        }
    });

    try {
        if (listener != null) {
            jBackup.addProgressListener(config.getName(), listener);
        }
        Future<Void> future = jBackup.restore(config, archive, targetDirectory);
        waitResult(future);
    } finally {
        jBackup.shutdown(null);
    }

    verify(jBackup, times(1)).restore(eq(config), eq(archive), eq(targetDirectory)); // called above
    verify(jBackup, times(1)).shutdown(isNull(TerminationListener.class)); // called above
    verify(jBackup, times(1)).createRestoreTask(eq(config), eq(archive), eq(targetDirectory),
            eq(actualTaskListener.getValue()), notNull(Cancellable.class));
    verify(mockRestoreTask, times(1)).call();
    if (listener != null) {
        verify(jBackup, times(1)).addProgressListener(eq(config.getName()), eq(listener));
    }
    verifyNoMoreInteractions(mockRestoreTask, jBackup);
}