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

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

Introduction

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

Prototype

public MutableObject() 

Source Link

Document

Constructs a new MutableObject with the default value of null.

Usage

From source file:com.wolvereness.overmapped.asm.ByteClass.java

public ByteClass(final String name, final InputStream data) throws IOException {
    Validate.notNull(name, "File name cannot be null");
    Validate.notNull(data, "InputStream cannot be null");
    Validate.isTrue(name.toLowerCase().endsWith(FILE_POSTFIX), "File name must be a class file");

    this.token = name.substring(0, name.length() - FILE_POSTFIX.length());

    final MutableObject<String> parent = new MutableObject<String>();
    final ImmutableList.Builder<String> interfaces = ImmutableList.builder();
    final ImmutableList.Builder<Signature> localSignatures = ImmutableList.builder();

    try {//from  w ww  . j av  a2  s  . co m
        this.reader = new ClassReader(ByteStreams.toByteArray(data));
    } finally {
        try {
            data.close();
        } catch (final IOException ex) {
        }
    }
    reader.accept(new ClassParser(token, interfaces, parent, localSignatures), ClassReader.SKIP_CODE);

    this.parent = parent.getValue();
    this.interfaces = interfaces.build();
    this.localSignatures = localSignatures.build();
}

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

@Test
public void accept_headers_are_overwritten_from_request_spec_by_default() {
    RequestSpecification spec = new RequestSpecBuilder().setAccept(ContentType.JSON).build();

    final MutableObject<List<String>> headers = new MutableObject<List<String>>();

    RestAssured.given().accept("text/jux").spec(spec).body("{ \"message\" : \"hello world\"}")
            .filter(new Filter() {
                public Response filter(FilterableRequestSpecification requestSpec,
                        FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    headers.setValue(requestSpec.getHeaders().getValues("Accept"));
                    return ctx.next(requestSpec, responseSpec);
                }//w  w  w .  ja  v a  2s. c o  m
            }).when().post("/jsonBodyAcceptHeader").then().body(equalTo("hello world"));

    assertThat(headers.getValue(), contains("application/json, application/javascript, text/javascript"));
}

From source file:com.jayway.restassured.itest.java.AcceptHeaderITest.java

@Test
public void accept_headers_are_overwritten_from_request_spec_by_default() {
    RequestSpecification spec = new RequestSpecBuilder().setAccept(JSON).build();

    final MutableObject<List<String>> headers = new MutableObject<List<String>>();

    given().accept("text/jux").spec(spec).body("{ \"message\" : \"hello world\"}").filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                FilterableResponseSpecification responseSpec, FilterContext ctx) {
            headers.setValue(requestSpec.getHeaders().getValues("Accept"));
            return ctx.next(requestSpec, responseSpec);
        }/*from  ww w  . java2 s .c  om*/
    }).when().post("/jsonBodyAcceptHeader").then().body(equalTo("hello world"));

    assertThat(headers.getValue(), contains("application/json, application/javascript, text/javascript"));
}

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

@Test
public void httpClientIsConfigurableFromANonStaticHttpClientConfig() {
    // Given//from  ww  w  . j  a  v  a  2s .  c o m
    final MutableObject<HttpClient> client = new MutableObject<>();

    // When
    given().config(RestAssuredConfig.newConfig()
            .httpClient(HttpClientConfig.httpClientConfig().httpClientFactory(SystemDefaultHttpClient::new)))
            .filter(new Filter() {
                public Response filter(FilterableRequestSpecification requestSpec,
                        FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    client.setValue(requestSpec.getHttpClient());
                    return new ResponseBuilder().setStatusCode(200).setContentType("application/json")
                            .setBody("{ \"message\" : \"hello\"}").build();
                }
            }).expect().body("message", equalTo("hello")).when().get("/something");

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

From source file:com.spotify.reaper.unit.service.SegmentRunnerTest.java

@Test
public void timeoutTest() throws InterruptedException, ReaperException, ExecutionException {
    final AppContext context = new AppContext();
    context.storage = new MemoryStorage();
    RepairUnit cf = context.storage/*from w w w .  j a va  2  s .  c o m*/
            .addRepairUnit(new RepairUnit.Builder("reaper", "reaper", Sets.newHashSet("reaper")));
    RepairRun run = context.storage.addRepairRun(
            new RepairRun.Builder("reaper", cf.getId(), DateTime.now(), 0.5, 1, RepairParallelism.PARALLEL));
    context.storage.addRepairSegments(Collections.singleton(
            new RepairSegment.Builder(run.getId(), new RingRange(BigInteger.ONE, BigInteger.ZERO), cf.getId())),
            run.getId());
    final long segmentId = context.storage.getNextFreeSegment(run.getId()).get().getId();

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final MutableObject<Future<?>> future = new MutableObject<>();

    context.jmxConnectionFactory = new JmxConnectionFactory() {
        @Override
        public JmxProxy connect(final Optional<RepairStatusHandler> handler, String host) {
            JmxProxy jmx = mock(JmxProxy.class);
            when(jmx.getClusterName()).thenReturn("reaper");
            when(jmx.isConnectionAlive()).thenReturn(true);
            when(jmx.tokenRangeToEndpoint(anyString(), any(RingRange.class)))
                    .thenReturn(Lists.newArrayList(""));
            when(jmx.triggerRepair(any(BigInteger.class), any(BigInteger.class), anyString(),
                    Matchers.<RepairParallelism>any(), Sets.newHashSet(anyString())))
                            .then(new Answer<Integer>() {
                                @Override
                                public Integer answer(InvocationOnMock invocation) {
                                    assertEquals(RepairSegment.State.NOT_STARTED,
                                            context.storage.getRepairSegment(segmentId).get().getState());
                                    future.setValue(executor.submit(new Thread() {
                                        @Override
                                        public void run() {
                                            handler.get().handle(1, ActiveRepairService.Status.STARTED,
                                                    "Repair command 1 has started");
                                            assertEquals(RepairSegment.State.RUNNING, context.storage
                                                    .getRepairSegment(segmentId).get().getState());
                                        }
                                    }));
                                    return 1;
                                }
                            });

            return jmx;
        }
    };
    RepairRunner rr = mock(RepairRunner.class);
    RepairUnit ru = mock(RepairUnit.class);
    SegmentRunner sr = new SegmentRunner(context, segmentId, Collections.singleton(""), 100, 0.5,
            RepairParallelism.PARALLEL, "reaper", ru, rr);
    sr.run();

    future.getValue().get();
    executor.shutdown();

    assertEquals(RepairSegment.State.NOT_STARTED, context.storage.getRepairSegment(segmentId).get().getState());
    assertEquals(1, context.storage.getRepairSegment(segmentId).get().getFailCount());
}

From source file:com.jayway.restassured.itest.java.HttpClientConfigITest.java

@Test
public void httpClientIsConfigurableFromANonStaticHttpClientConfig() {
    // Given//from   w ww  . j  ava 2 s. c  o m
    final MutableObject<HttpClient> client = new MutableObject<>();

    // When
    given().config(newConfig()
            .httpClient(HttpClientConfig.httpClientConfig().httpClientFactory(SystemDefaultHttpClient::new)))
            .filter(new Filter() {
                public Response filter(FilterableRequestSpecification requestSpec,
                        FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    client.setValue(requestSpec.getHttpClient());
                    return new ResponseBuilder().setStatusCode(200).setContentType("application/json")
                            .setBody("{ \"message\" : \"hello\"}").build();
                }
            }).expect().body("message", equalTo("hello")).when().get("/something");

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

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/*w w w .ja v  a 2  s . c  om*/
        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:com.norconex.collector.http.crawler.BasicFeaturesTest.java

@Test
public void testKeepDownload() throws IOException {
    HttpCollector collector = newHttpCollector1Crawler("/test/a$dir/blah?case=keepDownloads");
    HttpCrawler crawler = (HttpCrawler) collector.getCrawlers()[0];
    crawler.getCrawlerConfig().setMaxDepth(0);
    crawler.getCrawlerConfig().setKeepDownloads(true);
    //        String url = crawler.getCrawlerConfig().getStartURLs()[0];
    collector.start(false);/*w ww. j  a  v  a  2 s .c  o  m*/

    File downloadDir = new File(crawler.getCrawlerConfig().getWorkDir(), "downloads");
    final Mutable<File> downloadedFile = new MutableObject<>();
    FileUtil.visitAllFiles(downloadDir, new IFileVisitor() {
        @Override
        public void visit(File file) {
            if (downloadedFile.getValue() != null) {
                return;
            }
            if (file.toString().contains("downloads")) {
                downloadedFile.setValue(file);
            }
        }
    });
    String content = FileUtils.readFileToString(downloadedFile.getValue());
    Assert.assertTrue("Invalid or missing download file.", content
            .contains("<b>This</b> file <i>must</i> be saved as is, " + "with this <span>formatting</span>"));
}

From source file:gov.va.isaac.workflow.engine.RemoteSynchronizer.java

/**
 * Request a remote synchronization. This call blocks until the operation is complete,
 * or the thread is interrupted.// ww  w .j  a va  2  s .  c  om
 * 
 * @throws InterruptedException
 */
public SynchronizeResult blockingSynchronize() throws InterruptedException {
    log.info("Queuing a blocking sync request");
    final MutableObject<SynchronizeResult> result = new MutableObject<SynchronizeResult>();
    final CountDownLatch cdl = new CountDownLatch(1);
    Consumer<SynchronizeResult> callback = new Consumer<SynchronizeResult>() {
        @Override
        public void accept(SynchronizeResult t) {
            result.setValue(t);
            cdl.countDown();
        }
    };

    synchronize(callback);
    cdl.await();
    return result.getValue();
}

From source file:com.jayway.restassured.itest.java.AcceptHeaderITest.java

@Test
public void accept_headers_are_merged_from_request_spec_and_request_when_configured_to() {
    RequestSpecification spec = new RequestSpecBuilder().setAccept("text/jux").build();

    final MutableObject<List<String>> headers = new MutableObject<List<String>>();

    given().config(RestAssuredConfig.config().headerConfig(headerConfig().mergeHeadersWithName("Accept")))
            .accept(JSON).spec(spec).body("{ \"message\" : \"hello world\"}").filter(new Filter() {
                public Response filter(FilterableRequestSpecification requestSpec,
                        FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    headers.setValue(requestSpec.getHeaders().getValues("Accept"));
                    return ctx.next(requestSpec, responseSpec);
                }/*from  w  w  w. j av a  2  s  .  co m*/
            }).when().post("/jsonBodyAcceptHeader").then().body(equalTo("hello world"));

    assertThat(headers.getValue(),
            contains("application/json, application/javascript, text/javascript", "text/jux"));
}