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

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

Introduction

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

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.WorkspaceVersionTable.java

private void add(final WorkspaceLocalItem lvEntry, final boolean fromLoad) {
    final AtomicReference<WorkspaceLocalItem> atomicMatch = new AtomicReference<WorkspaceLocalItem>();

    // Create a callback.
    final ModifyInPlaceCallback<WorkspaceLocalItemPair> callback = new ModifyInPlaceCallback<WorkspaceLocalItemPair>() {
        @Override//from   w ww  .  j  a  v  a2 s . c  om
        public WorkspaceLocalItemPair invoke(final String token, WorkspaceLocalItemPair pair,
                final Object param) {
            if (pair == null) {
                pair = new WorkspaceLocalItemPair();
            }

            if (lvEntry.isCommitted()) {
                atomicMatch.set(pair.getCommitted());
                pair.setCommitted(lvEntry);
            } else {
                atomicMatch.set(pair.getUncommitted());
                pair.setUncommitted(lvEntry);
            }

            return pair;
        }
    };

    // Insert by the primary key (ServerItem, IsCommitted).
    server.modifyInPlace(lvEntry.getServerItem(), callback, null);
    final WorkspaceLocalItem matchingEntry = atomicMatch.get();

    setDirty(!fromLoad);

    // Remove the replaced entry from other indexes.
    if (null != matchingEntry) {
        final String localItem = matchingEntry.getLocalItem();
        if (localItem != null && localItem.length() > 0) {
            local.remove(localItem, false);
        }

        if (matchingEntry.isPendingReconcile()) {
            pendingReconcileCount--;
        }
    }

    if (lvEntry.isPendingReconcile()) {
        pendingReconcileCount++;
    }

    // Add the entry to the LocalItem tree if necessary.
    final String localItem = lvEntry.getLocalItem();
    if (localItem != null && localItem.length() > 0) {
        local.add(localItem, lvEntry, true);
    }
}

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

@Test
public void should_batch_with_custom_consistency_level_async() throws Exception {
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("simple_tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("simple_tweet2").buid();
    Tweet tweet3 = TweetTestBuilder.tweet().randomId().content("simple_tweet3").buid();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override//from w  w  w  . j  ava  2s  .  co  m
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    asyncManager.insert(tweet1).getImmediately();

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();

    batch.startBatch(QUORUM);

    logAsserter.prepareLogLevelForDriverConnection();

    Tweet foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();

    assertThat(foundTweet1.getContent()).isEqualTo(tweet1.getContent());

    batch.insert(tweet2);
    batch.insert(tweet3);

    batch.asyncEndBatch(successCallBack);

    latch.await();

    logAsserter.assertConsistencyLevels(QUORUM);
    assertThatBatchContextHasBeenReset(batch);

    assertThat(successSpy.get()).isSameAs(Empty.INSTANCE);
}

From source file:io.symcpe.hendrix.nifi.lmm.interceptor.LMMInterceptor.java

@Override
public void onTrigger(ProcessContext ctx, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//from  w ww .j  a va  2  s .  c o m
    if (flowFile == null) {
        return;
    }

    try {
        AtomicReference<String> message = new AtomicReference<String>();
        session.read(flowFile, true, new InputStreamCallback() {

            @Override
            public void process(InputStream in) throws IOException {
                message.set(IOUtils.toString(in));
            }
        });
        flowFile = session.putAttribute(flowFile, "message", message.get());
        flowFile = session.putAttribute(flowFile, ATTR_TENANT_ID, ctx.getProperty(TENANT_ID).getValue());
        flowFile = session.putAttribute(flowFile, ATTR_API_KEY, ctx.getProperty(API_KEY).getValue());
        flowFile = session.putAttribute(flowFile, ATTR_VERSION, _1);
        String timestamp = ctx.getProperty(TIMESTAMP).evaluateAttributeExpressions(flowFile).getValue();
        DateTime ts = formatter.withZoneUTC().parseDateTime(timestamp);
        flowFile = session.putAttribute(flowFile, ATTR_TIMESTAMP,
                ts.toString(TARGET_TIMESTAMP_PATTERN, Locale.ENGLISH));
        session.transfer(flowFile, SUCCESS);
    } catch (Exception e) {
        flowFile = session.putAttribute(flowFile, "Exception", e.getMessage());
        session.transfer(flowFile, FAILURE);
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

@Override
protected boolean searchForBuildFile(final boolean forceCheckForBuildFile) {
    if (super.searchForBuildFile(forceCheckForBuildFile)) {
        return true;
    } else {/*from www  .  j  a v a 2 s.  c  o m*/
        final GitProjectFileControl gitProjectFileControl = projectFileTabPage.getControl();
        final String buildFileLocation = gitProjectFileControl.getConfigFolderText().getText();

        final GitRepositoriesMap repositoriesMap = getRepositoriesMap();
        final List<GitRepository> mappedRepositories = repositoriesMap.getMappedRepositories();

        gitProjectFileControl.clearProjectFileStatus();

        final AtomicReference<String> projectName = new AtomicReference<String>();
        final AtomicReference<String> repositoryName = new AtomicReference<String>();
        final AtomicReference<String> branchName = new AtomicReference<String>();
        final AtomicReference<String> path = new AtomicReference<String>();

        if (GitProperties.parseGitItemUrl(buildFileLocation, projectName, repositoryName, branchName, path)
                && projectName.get().equalsIgnoreCase(teamProjectName)) {
            for (final GitRepository repository : mappedRepositories) {
                if (repository.getName().equalsIgnoreCase(repositoryName.get())) {
                    gitProjectFileControl.setRepositoryCloned(true);

                    if (branchName.get().equalsIgnoreCase(repository.getCurrentBranch().getRemoteName())) {
                        gitProjectFileControl.setBranchCheckedOut(true);

                        final String configFolderLocalPath = LocalPath
                                .combine(repository.getWorkingDirectoryPath(), path.get());

                        localCopyExists = LocalPath.exists(
                                LocalPath.combine(configFolderLocalPath, BuildConstants.PROJECT_FILE_NAME));

                        gitProjectFileControl.setLocalCopyExists(localCopyExists);
                    }

                    break;
                }
            }
        }

        return false;
    }
}

From source file:org.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldFailOnListMetricTypesWhenChunksAreInvalid() {
    // Data & mocks
    Metric<String> m1 = new Metric<>("inventory.123.mt.m1", null, 7, MetricType.STRING, null);
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.just(m1));
    DataPoint<String> tempDataPoint = buildMetricTypeDatapoint(currentTime - 500, "metricType1",
            "metric type 1");
    DataPoint<String> dataPoint = new DataPoint<>(tempDataPoint.getTimestamp(), tempDataPoint.getValue(),
            ImmutableMap.<String, String>builder().put("chunks", "3").put("size", "1000").build());
    when(metricsService.findStringData(m1.getMetricId(), 0, currentTime, false, 0, Order.DESC))
            .thenReturn(Observable.just(dataPoint,
                    buildMetricTypeDatapoint(currentTime - 501, "metricType1", "metric type 1"),
                    buildMetricTypeDatapoint(currentTime - 800, "metricType1", "metric type 1")));

    // Test & assertions
    AtomicReference<Throwable> refException = new AtomicReference<>();
    InventoryHelper.listMetricTypes(metricsService, "tenant", "feed", currentTime).toList().subscribe(a -> {
    }, refException::set);/*  w w w . j  ava2  s .c o m*/
    Assert.assertEquals(InvalidInventoryChunksException.class, refException.get().getCause().getClass());
    Assert.assertTrue("Unexpected message: " + refException.get().getCause().getMessage(), refException.get()
            .getCause().getMessage().contains("Inventory sanity check failure: chunk n2 timestamp is"));
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testInvalidUsername() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//  www.ja va2  s .c om
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "BASIC " + encodeCredentials("user3", "user1pass"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10047", status.getCode());
    }
}

From source file:com.quartercode.eventbridge.test.def.bridge.module.DefaultStandardHandlerModuleTest.java

@SuppressWarnings("unchecked")
@Test//from ww w.j  a va2s .co m
public void testCallHandler() {

    final BridgeConnector source = context.mock(BridgeConnector.class);

    final EmptyEvent1 regularEvent = new EmptyEvent1();
    final EmptyEvent2 otherEvent = new EmptyEvent2();

    final EventHandler<Event> handler = context.mock(EventHandler.class, "handler");
    final EventPredicate<Event> predicate = context.mock(EventPredicate.class, "predicate");

    final StandardHandleInterceptor interceptor = context.mock(StandardHandleInterceptor.class);
    module.getChannel().addInterceptor(new DummyStandardHandleInterceptor(interceptor), 1);

    final AtomicReference<LowLevelHandler> lowLevelHandler = new AtomicReference<>();

    // @formatter:off
    context.checking(new Expectations() {
        {

            allowing(predicate).test(regularEvent);
            will(returnValue(true));
            allowing(predicate).test(otherEvent);
            will(returnValue(false));

            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(predicate)));
            will(storeArgument(0).in(lowLevelHandler));

            final Sequence handleChain = context.sequence("handleChain");
            // Regular event
            oneOf(interceptor).handle(with(any(ChannelInvocation.class)), with(regularEvent), with(source),
                    with(handler));
            inSequence(handleChain);
            oneOf(handler).handle(regularEvent);
            inSequence(handleChain);
            // Other event
            // Expect the unwanted event to be invoked since the predicate is not tested by the StandardHandlerModule
            // In fact, the predicate is tested by the LowLevelHandlerModule
            oneOf(interceptor).handle(with(any(ChannelInvocation.class)), with(otherEvent), with(source),
                    with(handler));
            inSequence(handleChain);
            oneOf(handler).handle(otherEvent);
            inSequence(handleChain);

        }
    });
    // @formatter:on

    module.addHandler(handler, predicate);

    lowLevelHandler.get().handle(regularEvent, source);
    lowLevelHandler.get().handle(otherEvent, source);
}

From source file:com.networknt.basicauth.BasicAuthHandlerTest.java

@Test
public void testInvalidBasicHeaderPrefixText() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from w  w w. j  a v a2  s.  c  om*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer " + encodeCredentials("user1", "user1pass"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10046", status.getCode());
    }
}

From source file:com.joyent.manta.client.MantaSeekableByteChannel.java

@Override
public SeekableByteChannel position(final long newPosition) throws IOException {
    return new MantaSeekableByteChannel(new AtomicReference<>(), new AtomicReference<>(), path,
            new AtomicLong(newPosition), httpHelper);
}

From source file:org.eclipse.mylyn.commons.repositories.http.tests.CommonHttpClientTest.java

@Test
public void testHttpContextPerThread() throws Exception {
    RepositoryLocation location = new RepositoryLocation("http://mylyn.org/");
    final CommonHttpClient client = new CommonHttpClient(location);
    final AtomicReference<HttpContext> otherThreadContext = new AtomicReference<HttpContext>();
    Thread t = new Thread() {
        @Override/* www .  jav  a 2  s. c o  m*/
        public void run() {
            otherThreadContext.set(client.getContext());
        };
    };
    t.start();
    t.join();
    assertNotNull(otherThreadContext.get());
    assertNotNull(client.getContext());
    assertFalse(otherThreadContext.get() == client.getContext());
}