Example usage for java.util.concurrent.atomic AtomicReference get

List of usage examples for java.util.concurrent.atomic AtomicReference get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference get.

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@Test
public void testInit() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    URI uri = new URI("ws://localhost:" + port + "/composite");
    WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    stompClient.connect(new StompMessageHandler() {

        private StompSession stompSession;

        @Override//from  w w  w.  j  a v  a 2 s . c om
        public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) {
            this.stompSession = stompSession;
            this.stompSession.subscribe("/user/queue/device", null);

            try {
                this.stompSession.send("/app/init", "");
            } catch (Throwable t) {
                failure.set(t);
                latch.countDown();
            }
        }

        @Override
        public void handleMessage(Message<byte[]> message) {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
            if (!"/user/queue/device".equals(headers.getDestination())) {
                failure.set(new IllegalStateException("Unexpected message: " + message));
            }
            logger.debug("Got " + new String((byte[]) message.getPayload()));
            try {
                String json = parseMessageJson(message);
                new JsonPathExpectationsHelper("type").assertValue(json, "init");
                new JsonPathExpectationsHelper("uuid").exists(json);
            } catch (Throwable t) {
                failure.set(t);
            } finally {
                this.stompSession.disconnect();
                latch.countDown();
            }
        }

        @Override
        public void handleError(Message<byte[]> message) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload());
            logger.error(error);
            failure.set(new Exception(error));
        }

        @Override
        public void handleReceipt(String receiptId) {
        }

        @Override
        public void afterDisconnected() {
        }
    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Init response not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }
}

From source file:no.barentswatch.fiskinfo.BaseActivity.java

/**
 * Attempts to authenticate the given credentials with BarentsWatch. Will
 * set userIsAuthenticated to true if authentication is successful.
 * /*from ww  w .  jav  a  2 s  . co m*/
 * @param username
 *            the username to use for authentication
 * @param password
 *            the password to use for authentication
 */
// TODO: Change from hardcoded variables to using the actual username and
// password
public void authenticateUserCredentials(final String username, final String password) throws Exception {
    final AtomicReference<String> responseAsString = new AtomicReference<String>();
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                System.out.println("user: " + username + ", " + password);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                try {
                    HttpPost httpPost = new HttpPost("https://www.barentswatch.no/api/token");
                    httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                    postParameters.add(new BasicNameValuePair("grant_type", "password"));
                    postParameters.add(new BasicNameValuePair("username", username));
                    postParameters.add(new BasicNameValuePair("password", password));
                    httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

                    CloseableHttpResponse response = httpclient.execute(httpPost);
                    try {
                        responseAsString.set(EntityUtils.toString(response.getEntity()));
                    } finally {
                        response.close();
                    }

                } finally {
                    httpclient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    String barentswatchResponse = responseAsString.get();
    JSONObject barentsWatchResponseToken = new JSONObject(barentswatchResponse);

    saveUserCredentialsToSharedPreferences(barentsWatchResponseToken, username, password);
    getAuthenticationCredientialsFromSharedPrefrences();

    setAuthentication(true);
    loadView(MyPageActivity.class);
}

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@Test
public void testStop() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<>();

    URI uri = new URI("ws://localhost:" + port + "/composite");
    WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    stompClient.connect(new StompMessageHandler() {

        private StompSession stompSession;

        @Override//from   w  w w . j  a  va2s.co  m
        public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) {
            this.stompSession = stompSession;
            String topicUuid = simulateJoinEvent();

            this.stompSession.subscribe("/user/queue/device", null);
            this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null);

            try {
                HashMap<String, Object> stop = new HashMap<String, Object>();
                stop.put("type", "stop");
                this.stompSession.send(String.format("/app/%s", topicUuid), stop);

            } catch (Throwable t) {
                failure.set(t);
                latch.countDown();
            }
        }

        @Override
        public void handleMessage(Message<byte[]> message) {
            try {
                String json = parseMessageJson(message);
                new JsonPathExpectationsHelper("type").exists(json);
                new JsonPathExpectationsHelper("type").assertValue(json, "stop");
                new JsonPathExpectationsHelper("serverTime").exists(json);
            } catch (Throwable t) {
                failure.set(t);
            } finally {
                this.stompSession.disconnect();
                latch.countDown();
            }
        }

        @Override
        public void handleError(Message<byte[]> message) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload());
            logger.error(error);
            failure.set(new Exception(error));
        }

        @Override
        public void handleReceipt(String receiptId) {
        }

        @Override
        public void afterDisconnected() {
        }

    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Stop response not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }

}

From source file:com.microsoft.tfs.client.clc.commands.Command.java

/**
 * Displays a {@link GetEvent}.//  ww  w.  ja  v a2 s.c  o  m
 *
 * @param e
 *        the event to display (must not be <code>null</code>)
 * @param targetName
 *        the target name to use (may be <code>null</code> to use an item
 *        name from the event)
 */
private void displayGetEvent(final GetEvent e, final String targetName) {
    final AtomicReference<String> errorHolder = new AtomicReference<String>();
    final String message = e.getMessage(targetName, errorHolder);

    if (e.getStatus() == OperationStatus.CONFLICT || e.getStatus() == OperationStatus.SOURCE_WRITABLE
            || e.getStatus() == OperationStatus.TARGET_LOCAL_PENDING
            || e.getStatus() == OperationStatus.TARGET_WRITABLE
            || e.getStatus() == OperationStatus.SOURCE_DIRECTORY_NOT_EMPTY
            || e.getStatus() == OperationStatus.TARGET_IS_DIRECTORY
            || e.getStatus() == OperationStatus.UNABLE_TO_REFRESH) {
        getDisplay().printErrorLine(errorHolder.get());
        setExitCode(ExitCode.PARTIAL_SUCCESS);
    } else if (e.getStatus() == OperationStatus.GETTING || e.getStatus() == OperationStatus.REPLACING
            || e.getStatus() == OperationStatus.DELETING) {
        getDisplay().printLine(message);
    }
}

From source file:io.galeb.router.tests.handlers.PathGlobHandlerTest.java

@Test
public void checkMatch() {
    final AtomicReference<String> result = new AtomicReference<>("default");

    HttpHandler defaultHandler = mock(HttpHandler.class);
    PathGlobHandler pathGlobHandler = new PathGlobHandler();
    pathGlobHandler.setDefaultHandler(defaultHandler);

    pathGlobHandler.addPath("/x", 0, exchange -> result.set("x"));
    pathGlobHandler.addPath("/y", 0, exchange -> result.set("y"));
    pathGlobHandler.addPath("/z", 0, exchange -> result.set("z"));
    pathGlobHandler.addPath("/w", 0, exchange -> result.set("w"));
    pathGlobHandler.addPath("/1", 1, exchange -> result.set("1"));
    pathGlobHandler.addPath("/2", 2, exchange -> result.set("2"));
    pathGlobHandler.addPath("/3", 3, exchange -> result.set("3"));
    pathGlobHandler.addPath("/4", 4, exchange -> result.set("4"));
    pathGlobHandler.addPath("/5*", 4, exchange -> result.set("5"));
    pathGlobHandler.addPath("/6/*", Integer.MAX_VALUE - 1, exchange -> result.set("6"));
    pathGlobHandler.addPath("/7/*.json", Integer.MAX_VALUE - 1, exchange -> result.set("7"));
    pathGlobHandler.addPath("/", Integer.MAX_VALUE, exchange -> result.set("slash"));

    ServerConnection serverConnection = mock(ServerConnection.class);
    try {/* w  w w .j  av  a 2 s  .  c  o  m*/
        HttpServerExchange exchangeNotMatch = new HttpServerExchange(serverConnection);
        exchangeNotMatch.setRelativePath(UUID.randomUUID().toString());
        HttpServerExchange exchangeX = new HttpServerExchange(serverConnection);
        exchangeX.setRelativePath("/x");
        HttpServerExchange exchangeY = new HttpServerExchange(serverConnection);
        exchangeY.setRelativePath("/y");
        HttpServerExchange exchangeZ = new HttpServerExchange(serverConnection);
        exchangeZ.setRelativePath("/z");
        HttpServerExchange exchangeW = new HttpServerExchange(serverConnection);
        exchangeW.setRelativePath("/w");
        HttpServerExchange exchange1 = new HttpServerExchange(serverConnection);
        exchange1.setRelativePath("/1");
        HttpServerExchange exchange2 = new HttpServerExchange(serverConnection);
        exchange2.setRelativePath("/2");
        HttpServerExchange exchange3 = new HttpServerExchange(serverConnection);
        exchange3.setRelativePath("/3");
        HttpServerExchange exchange4 = new HttpServerExchange(serverConnection);
        exchange4.setRelativePath("/4");
        HttpServerExchange exchange5 = new HttpServerExchange(serverConnection);
        exchange5.setRelativePath("/555");
        HttpServerExchange exchange6 = new HttpServerExchange(serverConnection);
        exchange6.setRelativePath("/6/xpto");
        HttpServerExchange exchange7 = new HttpServerExchange(serverConnection);
        exchange7.setRelativePath("/7/xpto/test.json");
        HttpServerExchange exchangeSlash = new HttpServerExchange(serverConnection);
        exchangeSlash.setRelativePath("/");

        pathGlobHandler.handleRequest(exchangeNotMatch);
        assertThat(result.get(), equalTo("default"));

        pathGlobHandler.handleRequest(exchangeX);
        assertThat(result.get(), equalTo("x"));

        pathGlobHandler.handleRequest(exchangeY);
        assertThat(result.get(), equalTo("y"));

        pathGlobHandler.handleRequest(exchangeZ);
        assertThat(result.get(), equalTo("z"));

        pathGlobHandler.handleRequest(exchangeW);
        assertThat(result.get(), equalTo("w"));

        pathGlobHandler.handleRequest(exchange1);
        assertThat(result.get(), equalTo("1"));

        pathGlobHandler.handleRequest(exchange2);
        assertThat(result.get(), equalTo("2"));

        pathGlobHandler.handleRequest(exchange3);
        assertThat(result.get(), equalTo("3"));

        pathGlobHandler.handleRequest(exchange4);
        assertThat(result.get(), equalTo("4"));

        pathGlobHandler.handleRequest(exchange2);
        assertThat(result.get(), equalTo("2"));

        pathGlobHandler.handleRequest(exchange1);
        assertThat(result.get(), equalTo("1"));

        pathGlobHandler.handleRequest(exchange5);
        assertThat(result.get(), equalTo("5"));

        pathGlobHandler.handleRequest(exchange6);
        assertThat(result.get(), equalTo("6"));

        pathGlobHandler.handleRequest(exchange7);
        assertThat(result.get(), equalTo("7"));

        pathGlobHandler.handleRequest(exchangeSlash);
        assertThat(result.get(), equalTo("slash"));

    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    } catch (AssertionError assertionError) {
        pathGlobHandler.getPaths().forEach((k, v) -> logger.error(k.getPath() + " -> " + k.getOrder()));
        throw assertionError;
    }
}

From source file:interactivespaces.util.web.WebSocketTest.java

@Test
public void testWebSocketCommunication() throws Exception {
    final String dataKey = "message";

    final CountDownLatch clientOpenning = new CountDownLatch(1);
    final CountDownLatch clientClosing = new CountDownLatch(1);

    final AtomicBoolean onConnectCalledServer = new AtomicBoolean(false);
    final AtomicBoolean onCloseCalledServer = new AtomicBoolean(false);

    final AtomicReference<WebServerWebSocketHandler> serverHandler = new AtomicReference<WebServerWebSocketHandler>();

    int port = 8082;
    String webSocketUriPrefix = "websockettest";

    URI uri = new URI(String.format("ws://127.0.0.1:%d/%s", port, webSocketUriPrefix));

    final List<Integer> serverReceivedList = Lists.newArrayList();
    final List<Integer> clientReceivedList = Lists.newArrayList();
    List<Integer> serverSentList = Lists.newArrayList();
    List<Integer> clientSentList = Lists.newArrayList();
    Random random = new Random(System.currentTimeMillis());

    for (int i = 0; i < 100; i++) {
        clientSentList.add(random.nextInt());
        serverSentList.add(random.nextInt());
    }//  w  w  w  . jav a2 s  .  c  o  m

    NettyWebServer server = new NettyWebServer(threadPool, log);
    server.setServerName("test-server");
    server.setPort(port);
    server.setWebSocketHandlerFactory(webSocketUriPrefix, new WebServerWebSocketHandlerFactory() {

        @Override
        public WebServerWebSocketHandler newWebSocketHandler(WebSocketConnection connection) {
            WebServerWebSocketHandler handler = new WebServerWebSocketHandlerSupport(connection) {

                @Override
                public void onReceive(Object data) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> d = (Map<String, Object>) data;

                    serverReceivedList.add((Integer) d.get(dataKey));
                }

                @Override
                public void onConnect() {
                    onConnectCalledServer.set(true);
                }

                @Override
                public void onClose() {
                    onCloseCalledServer.set(true);
                }
            };

            serverHandler.set(handler);

            return handler;
        }
    });
    server.startup();

    Thread.sleep(2000);

    WebSocketHandler clientHandler = new WebSocketHandler() {

        @Override
        public void onConnect() {
            clientOpenning.countDown();
        }

        @Override
        public void onClose() {
            clientClosing.countDown();
        }

        @Override
        public void onReceive(Object data) {
            @SuppressWarnings("unchecked")
            Map<String, Object> d = (Map<String, Object>) data;

            clientReceivedList.add((Integer) d.get(dataKey));
        }
    };

    NettyWebSocketClient client = new NettyWebSocketClient(uri, clientHandler, threadPool, log);
    client.startup();

    Assert.assertTrue(clientOpenning.await(10, TimeUnit.SECONDS));

    Assert.assertTrue(client.isOpen());

    Map<String, Object> data = Maps.newHashMap();
    for (Integer i : clientSentList) {
        data.put("message", i);
        client.writeDataAsJson(data);
    }

    for (Integer i : serverSentList) {
        data.put("message", i);
        serverHandler.get().sendJson(data);
    }

    client.ping();

    client.shutdown();

    Assert.assertTrue(clientClosing.await(10, TimeUnit.SECONDS));

    server.shutdown();

    Assert.assertEquals(clientSentList, serverReceivedList);
    Assert.assertEquals(serverSentList, clientReceivedList);
    Assert.assertTrue(onConnectCalledServer.get());
    Assert.assertTrue(onCloseCalledServer.get());
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java

@Test
public void testSafetyWithCrash() throws Exception {
    final int itemQty = 100;

    DistributedQueue<TestQueueItem> producerQueue = null;
    DistributedQueue<TestQueueItem> consumerQueue1 = null;
    DistributedQueue<TestQueueItem> consumerQueue2 = null;

    CuratorFramework producerClient = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    CuratorFramework consumerClient1 = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    CuratorFramework consumerClient2 = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {/*  www . jav a2  s  .c  om*/
        producerClient.start();
        consumerClient1.start();
        consumerClient2.start();

        ExecutorService service = Executors.newCachedThreadPool();

        // make the producer queue
        {
            producerQueue = QueueBuilder.builder(producerClient, null, serializer, QUEUE_PATH).buildQueue();
            producerQueue.start();
            QueueTestProducer producer = new QueueTestProducer(producerQueue, itemQty, 0);
            service.submit(producer);
        }

        final Set<TestQueueItem> takenItems = Sets.newTreeSet();
        final Set<TestQueueItem> takenItemsForConsumer1 = Sets.newTreeSet();
        final Set<TestQueueItem> takenItemsForConsumer2 = Sets.newTreeSet();
        final AtomicReference<TestQueueItem> thrownItemFromConsumer1 = new AtomicReference<TestQueueItem>(null);

        // make the first consumer queue
        {
            final QueueConsumer<TestQueueItem> ourQueue = new QueueConsumer<TestQueueItem>() {
                @Override
                public void consumeMessage(TestQueueItem message) throws Exception {
                    synchronized (takenItems) {
                        if (takenItems.size() > 10) {
                            thrownItemFromConsumer1.set(message);
                            throw new Exception("dummy"); // simulate a crash
                        }
                    }

                    addToTakenItems(message, takenItems, itemQty);
                    synchronized (takenItemsForConsumer1) {
                        takenItemsForConsumer1.add(message);
                    }

                    Thread.sleep((long) (Math.random() * 5));
                }

                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                }
            };
            consumerQueue1 = QueueBuilder.builder(consumerClient1, ourQueue, serializer, QUEUE_PATH)
                    .lockPath("/a/locks").buildQueue();
            consumerQueue1.start();
        }

        // make the second consumer queue
        {
            final QueueConsumer<TestQueueItem> ourQueue = new QueueConsumer<TestQueueItem>() {
                @Override
                public void consumeMessage(TestQueueItem message) throws Exception {
                    addToTakenItems(message, takenItems, itemQty);
                    synchronized (takenItemsForConsumer2) {
                        takenItemsForConsumer2.add(message);
                    }
                    Thread.sleep((long) (Math.random() * 5));
                }

                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                }
            };
            consumerQueue2 = QueueBuilder.builder(consumerClient2, ourQueue, serializer, QUEUE_PATH)
                    .lockPath("/a/locks").buildQueue();
            consumerQueue2.start();
        }

        synchronized (takenItems) {
            while (takenItems.size() < itemQty) {
                takenItems.wait(1000);
            }
        }

        int i = 0;
        for (TestQueueItem item : takenItems) {
            Assert.assertEquals(item.str, Integer.toString(i++));
        }

        Assert.assertNotNull(thrownItemFromConsumer1.get());
        Assert.assertTrue((takenItemsForConsumer2.contains(thrownItemFromConsumer1.get())));
        Assert.assertTrue(Sets.intersection(takenItemsForConsumer1, takenItemsForConsumer2).size() == 0);
    } finally {
        IOUtils.closeQuietly(producerQueue);
        IOUtils.closeQuietly(consumerQueue1);
        IOUtils.closeQuietly(consumerQueue2);

        IOUtils.closeQuietly(producerClient);
        IOUtils.closeQuietly(consumerClient1);
        IOUtils.closeQuietly(consumerClient2);
    }
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncQueryIT.java

@Test
public void should_return_raw_entities_for_raw_typed_query_async() throws Exception {
    Counter counter1 = CounterBuilder.incr(15L);
    CompleteBean paul = builder().randomId().name("Paul").age(35L).addFriends("foo", "bar")
            .addFollowers("George", "Jack").addPreference(1, "FR").addPreference(2, "Paris")
            .addPreference(3, "75014").version(counter1).buid();

    Counter counter2 = CounterBuilder.incr(17L);
    CompleteBean john = builder().randomId().name("John").age(34L).addFriends("qux", "twix")
            .addFollowers("Isaac", "Lara").addPreference(1, "US").addPreference(2, "NewYork").version(counter2)
            .buid();//from ww w.j ava2s.  c  o m

    asyncManager.insert(paul).getImmediately();
    asyncManager.insert(john).getImmediately();

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy1 = new AtomicReference<>();
    final AtomicReference<Object> successSpy2 = new AtomicReference<>();

    FutureCallback<Object> successCallBack1 = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            successSpy1.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    FutureCallback<Object> successCallBack2 = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            successSpy2.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    final RegularStatement selectStar = select().from("CompleteBean").where(eq("id", bindMarker("id")));

    final AchillesFuture<CompleteBean> futurePaul = asyncManager
            .rawTypedQuery(CompleteBean.class, selectStar, paul.getId()).getFirst(successCallBack1);
    final AchillesFuture<CompleteBean> futureJohn = asyncManager
            .rawTypedQuery(CompleteBean.class, selectStar, john.getId()).getFirst(successCallBack2);

    latch.await();

    CompleteBean foundPaul = futurePaul.get();

    assertThat(foundPaul.getName()).isEqualTo(paul.getName());
    assertThat(foundPaul.getAge()).isEqualTo(paul.getAge());
    assertThat(foundPaul.getFriends()).containsAll(paul.getFriends());
    assertThat(foundPaul.getFollowers()).containsAll(paul.getFollowers());
    assertThat(foundPaul.getPreferences().get(1)).isEqualTo("FR");
    assertThat(foundPaul.getPreferences().get(2)).isEqualTo("Paris");
    assertThat(foundPaul.getPreferences().get(3)).isEqualTo("75014");
    assertThat(foundPaul.getVersion()).isNull();

    CompleteBean foundJohn = futureJohn.get();
    assertThat(foundJohn.getName()).isEqualTo(john.getName());
    assertThat(foundJohn.getAge()).isEqualTo(john.getAge());
    assertThat(foundJohn.getFriends()).containsAll(john.getFriends());
    assertThat(foundJohn.getFollowers()).containsAll(john.getFollowers());
    assertThat(foundJohn.getPreferences().get(1)).isEqualTo("US");
    assertThat(foundJohn.getPreferences().get(2)).isEqualTo("NewYork");
    assertThat(foundJohn.getVersion()).isNull();

    assertThat(successSpy1.get()).isNotNull().isInstanceOf(CompleteBean.class).isNotInstanceOf(Factory.class);
    assertThat(successSpy2.get()).isNotNull().isInstanceOf(CompleteBean.class).isNotInstanceOf(Factory.class);
}

From source file:io.pravega.segmentstore.server.writer.SegmentAggregatorTests.java

/**
 * Tests the ability of the SegmentAggregator to reconcile AppendOperations (Cached/NonCached).
 *//*  ww w . j  a v a2 s.co m*/
@Test
public void testReconcileAppends() throws Exception {
    final WriterConfig config = DEFAULT_CONFIG;
    final int appendCount = 1000;
    final int failEvery = 3;

    @Cleanup
    TestContext context = new TestContext(config);
    context.storage.create(context.segmentAggregator.getMetadata().getName(), TIMEOUT).join();
    context.segmentAggregator.initialize(TIMEOUT, executorService()).join();

    // The writes always succeed, but every few times we return some random error, indicating that they didn't.
    AtomicInteger writeCount = new AtomicInteger();
    AtomicReference<Exception> setException = new AtomicReference<>();
    context.storage.setWriteInterceptor((segmentName, offset, data, length, storage) -> {
        if (writeCount.incrementAndGet() % failEvery == 0) {
            // Time to wreak some havoc.
            return storage.write(writeHandle(segmentName), offset, data, length, TIMEOUT).thenAccept(v -> {
                IntentionalException ex = new IntentionalException(
                        String.format("S=%s,O=%d,L=%d", segmentName, offset, length));
                setException.set(ex);
                throw ex;
            });
        } else {
            setException.set(null);
            return null;
        }
    });

    @Cleanup
    ByteArrayOutputStream writtenData = new ByteArrayOutputStream();

    for (int i = 0; i < appendCount; i++) {
        // Add another operation and record its length.
        StorageOperation appendOp = generateAppendAndUpdateMetadata(i, SEGMENT_ID, context);
        context.segmentAggregator.add(appendOp);
        getAppendData(appendOp, writtenData, context);
    }

    context.increaseTime(config.getFlushThresholdTime().toMillis() + 1); // Force a flush by incrementing the time by a lot.
    while (context.segmentAggregator.mustFlush()) {
        // Call flush() and inspect the result.
        FlushResult flushResult = null;

        try {
            flushResult = context.segmentAggregator.flush(TIMEOUT, executorService()).get(TIMEOUT.toMillis(),
                    TimeUnit.MILLISECONDS);
            Assert.assertNull("An exception was expected, but none was thrown.", setException.get());
            Assert.assertNotNull("No FlushResult provided.", flushResult);
        } catch (Exception ex) {
            if (setException.get() != null) {
                Assert.assertEquals("Unexpected exception thrown.", setException.get(),
                        ExceptionHelpers.getRealException(ex));
            } else {
                // Only expecting a BadOffsetException after our own injected exception.
                Throwable realEx = ExceptionHelpers.getRealException(ex);
                Assert.assertTrue("Unexpected exception thrown: " + realEx,
                        realEx instanceof BadOffsetException);
            }
        }

        // Check flush result.
        if (flushResult != null) {
            AssertExtensions.assertGreaterThan("Not enough bytes were flushed (time threshold).", 0,
                    flushResult.getFlushedBytes());
            Assert.assertEquals("Not expecting any merged bytes in this test.", 0,
                    flushResult.getMergedBytes());
        }

        context.increaseTime(config.getFlushThresholdTime().toMillis() + 1); // Force a flush by incrementing the time by a lot.
    }

    // Verify data.
    byte[] expectedData = writtenData.toByteArray();
    byte[] actualData = new byte[expectedData.length];
    long storageLength = context.storage
            .getStreamSegmentInfo(context.segmentAggregator.getMetadata().getName(), TIMEOUT).join()
            .getLength();
    Assert.assertEquals("Unexpected number of bytes flushed to Storage.", expectedData.length, storageLength);
    context.storage.read(readHandle(context.segmentAggregator.getMetadata().getName()), 0, actualData, 0,
            actualData.length, TIMEOUT).join();

    Assert.assertArrayEquals("Unexpected data written to storage.", expectedData, actualData);
}