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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:interactivespaces.service.comm.network.NettyUdpSocketTest.java

/**
 * Test a round trip from a UDP client to a UDP server and back.
 *
 * @throws Exception//from w  w  w  .  j av  a 2s . c om
 *           something bad
 */
@Test
public void testUdpPacketSend() throws Exception {
    final byte[] serverResponseExpectedData = new byte[] { 17, 2, 89, 127 };
    byte[] serverRequestExpectedData = new byte[] { 55, 66, 22, 87 };

    int serverPort = 10000;

    final CountDownLatch serverReceiveLatch = new CountDownLatch(1);
    final AtomicReference<UdpServerRequest> serverRequestActualData = new AtomicReference<UdpServerRequest>();

    final CountDownLatch clientReceiveLatch = new CountDownLatch(1);
    final AtomicReference<byte[]> serverResponseActualData = new AtomicReference<byte[]>();

    UdpServerNetworkCommunicationEndpoint serverEndpoint = serverService.newServer(serverPort, log);
    UdpClientNetworkCommunicationEndpoint clientEndpoint = clientService.newClient(log);

    try {
        serverEndpoint.addListener(new UdpServerNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpRequest(UdpServerNetworkCommunicationEndpoint endpoint, UdpServerRequest request) {
                serverRequestActualData.set(request);

                request.writeResponse(serverResponseExpectedData);

                serverReceiveLatch.countDown();
            }
        });

        serverEndpoint.startup();

        clientEndpoint.addListener(new UdpClientNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpResponse(UdpClientNetworkCommunicationEndpoint endpoint, byte[] response,
                    InetSocketAddress remoteAddress) {
                serverResponseActualData.set(response);

                clientReceiveLatch.countDown();
            }
        });
        clientEndpoint.startup();

        WriteableUdpPacket packet = clientEndpoint.newWriteableUdpPacket(serverRequestExpectedData.length);
        packet.writeBytes(serverRequestExpectedData);

        packet.write(new InetSocketAddress("127.0.0.1", serverPort));

        Assert.assertTrue(clientReceiveLatch.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverReceiveLatch.await(5, TimeUnit.SECONDS));
    } finally {
        clientEndpoint.shutdown();
        serverEndpoint.shutdown();
    }

    Assert.assertArrayEquals(serverRequestExpectedData, serverRequestActualData.get().getRequest());
    Assert.assertArrayEquals(serverResponseExpectedData, serverResponseActualData.get());
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

private void verifyAuthorizationPage(OAuth2RestTemplate restTemplate, String location) {
    final AtomicReference<String> confirmationPage = new AtomicReference<String>();
    AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider() {
        @Override/* w w  w  .  j av  a  2  s  . c o m*/
        protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
            return new ResponseExtractor<ResponseEntity<Void>>() {
                public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
                    confirmationPage
                            .set(StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")));
                    return new ResponseEntity<Void>(response.getHeaders(), response.getStatusCode());
                }
            };
        }
    };
    try {
        provider.obtainAuthorizationCode(restTemplate.getResource(),
                restTemplate.getOAuth2ClientContext().getAccessTokenRequest());
    } catch (UserApprovalRequiredException e) {
        // ignore
    }
    String page = confirmationPage.get();
    verifyAuthorizationPage(page);
}

From source file:io.smartspaces.service.comm.network.NettyUdpSocketTest.java

/**
 * Test a round trip from a UDP client to a UDP server and back.
 *
 * @throws Exception//from   w  w  w. jav  a  2s  .  c  om
 *           something bad
 */
@Test
public void testUdpPacketSend() throws Exception {
    final byte[] serverResponseExpectedData = new byte[] { 17, 2, 89, 127 };
    byte[] serverRequestExpectedData = new byte[] { 55, 66, 22, 87 };

    int serverPort = 8099;

    final CountDownLatch serverReceiveLatch = new CountDownLatch(1);
    final AtomicReference<UdpServerRequest> serverRequestActualData = new AtomicReference<UdpServerRequest>();

    final CountDownLatch clientReceiveLatch = new CountDownLatch(1);
    final AtomicReference<byte[]> serverResponseActualData = new AtomicReference<byte[]>();

    UdpServerNetworkCommunicationEndpoint serverEndpoint = serverService.newServer(serverPort, log);
    UdpClientNetworkCommunicationEndpoint clientEndpoint = clientService.newClient(log);

    try {
        serverEndpoint.addListener(new UdpServerNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpRequest(UdpServerNetworkCommunicationEndpoint endpoint, UdpServerRequest request) {
                serverRequestActualData.set(request);

                request.writeResponse(serverResponseExpectedData);

                serverReceiveLatch.countDown();
            }
        });

        serverEndpoint.startup();

        clientEndpoint.addListener(new UdpClientNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpResponse(UdpClientNetworkCommunicationEndpoint endpoint, byte[] response,
                    InetSocketAddress remoteAddress) {
                serverResponseActualData.set(response);

                clientReceiveLatch.countDown();
            }
        });
        clientEndpoint.startup();

        WriteableUdpPacket packet = clientEndpoint.newWriteableUdpPacket(serverRequestExpectedData.length);
        packet.writeBytes(serverRequestExpectedData);

        packet.write(new InetSocketAddress("127.0.0.1", serverPort));

        Assert.assertTrue(clientReceiveLatch.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverReceiveLatch.await(5, TimeUnit.SECONDS));
    } finally {
        clientEndpoint.shutdown();
        serverEndpoint.shutdown();
    }

    Assert.assertArrayEquals(serverRequestExpectedData, serverRequestActualData.get().getRequest());
    Assert.assertArrayEquals(serverResponseExpectedData, serverResponseActualData.get());
}

From source file:de.acosix.alfresco.utility.repo.subsystems.SubsystemChildApplicationContextManager.java

/**
 * Determines the instance ID for a specific child application context from within all the child application contexts managed by this
 * instance./*ww w  .  j  a  v a 2 s  . c  o  m*/
 *
 * @param childApplicationContext
 *            the child application context
 * @return the ID of the child application instance or {@code null} if none of the currently active child application contexts match the
 *         provided one
 */
public String determineInstanceId(final ApplicationContext childApplicationContext) {
    this.lock.readLock().lock();
    try {
        final SubsystemApplicationContextManagerState state = (SubsystemApplicationContextManagerState) this
                .getState(false);

        final Collection<String> instanceIds = state.getInstanceIds();
        final AtomicReference<String> matchingInstanceId = new AtomicReference<>(null);

        for (final String id : instanceIds) {
            if (matchingInstanceId.get() == null) {
                final SubsystemChildApplicationContextFactory applicationContextFactory = state
                        .getApplicationContextFactory(id);
                final ApplicationContext readOnlyApplicationContext = applicationContextFactory
                        .getReadOnlyApplicationContext();

                if (readOnlyApplicationContext == childApplicationContext) {
                    matchingInstanceId.set(id);
                }
            }
        }

        return matchingInstanceId.get();
    } finally

    {
        this.lock.readLock().unlock();
    }
}

From source file:io.vertx.camel.OutboundEndpointTest.java

@Test
public void testWithRouteWithFailure() throws Exception {
    AtomicReference<String> calledSpy = new AtomicReference<>();

    camel.addRoutes(new RouteBuilder() {
        @Override//from w w  w  .ja v  a  2s. c  o  m
        public void configure() throws Exception {
            from("direct:my-route").to("http://localhost:8081");
        }
    });

    bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel)
            .addOutboundMapping(fromVertx("camel-route").toCamel("direct:my-route")));

    camel.start();
    BridgeHelper.startBlocking(bridge);

    vertx.eventBus().send("camel-route", "hello", reply -> {
        calledSpy.set(reply.cause().getMessage());
    });

    await().atMost(DEFAULT_TIMEOUT).untilAtomic(calledSpy, is("Connection refused"));
}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testAcceptNAWS() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    final AtomicReference<int[]> size = new AtomicReference<>();
    WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, true, false);
    testOptionValue(() -> new TelnetHandler() {
        @Override/*from w  w w  .j  a v  a  2  s.  c  o m*/
        protected void onOpen(TelnetConnection conn) {
            conn.writeDoOption(Option.NAWS);
        }

        @Override
        protected void onNAWS(boolean naws) {
            serverValue.set(naws);
        }

        @Override
        protected void onSize(int width, int height) {
            size.set(new int[] { width, height });
            testComplete();
        }
    }, optionHandler);
    assertEquals(true, serverValue.get());
    assertEquals(true, optionHandler.getAcceptLocal());
    assertEquals(2, size.get().length);
    assertEquals(20, size.get()[0]);
    assertEquals(10, size.get()[1]);
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void readTimeout() throws Exception {
    //set(client + ".niws.client.ReadTimeout", "100");
    int code = 200;
    statusCode.set(code);/*from w ww.  j  av  a2 s . com*/
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 3);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/readTimeout")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            throwable.set(t);
            latch.countDown();
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    Assert.assertTrue(throwable.get() instanceof ReadTimeoutException);
    assertEquals(expected, statusCounts);
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void readTimeoutDoesntRetry() throws Exception {
    //set(client + ".niws.client.ReadTimeout", "100");
    set(client + ".niws.client.RetryReadTimeouts", "false");
    int code = 200;
    statusCode.set(code);/*from   www.  j a  va  2 s . c om*/
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/readTimeout")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            throwable.set(t);
            latch.countDown();
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    Assert.assertTrue(throwable.get() instanceof ReadTimeoutException);
    assertEquals(expected, statusCounts);
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void absoluteRedirect() throws Exception {
    int code = 200;
    statusCode.set(code);//w  w w. j  a  v a2s. c om
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.incrementAndGet(code);
    expected.addAndGet(302, 3);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/absoluteRedirect")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            throwable.set(t);
            latch.countDown();
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    Assert.assertNull(throwable.get());
    assertEquals(expected, statusCounts);
}

From source file:org.bpmscript.exec.js.serialize.ContinuationInspectionTest.java

public void testChannel() throws Exception {

    MemoryIntegrationTestSupport integrationTestSupport = new MemoryIntegrationTestSupport();
    integrationTestSupport.execute(new ITestCallback<IServiceLookup>() {

        public void execute(IServiceLookup services) throws Exception {
            final CountDownLatch latch = new CountDownLatch(1);

            final MemoryMessageBus bus = services.get("bus");
            final BpmScriptEngine engine = services.get("engine");
            final MemoryScopeStore scopeStore = services.get("scopeStore");
            final JavascriptSerializingContinuationService continuationService = services
                    .get("continuationService");
            final MemoryContinuationJournal continuationJournal = services.get("continuationJournal");
            final AtomicReference<Continuation> continuationReference = new AtomicReference<Continuation>();

            IVersionedDefinitionManager processManager = engine.getVersionedDefinitionManager();
            processManager.createDefinition("id",
                    new JavascriptProcessDefinition("test", StreamService.DEFAULT_INSTANCE
                            .getResourceAsString("/org/bpmscript/integration/memory/reply.js")));
            engine.setInstanceListener(new LoggingInstanceListener() {
                @Override/*w w  w. j a  v  a  2 s  .  c o m*/
                public void instancePaused(String pid, IPausedResult result) {
                    continuationReference.set((Continuation) result.getContinuation());
                    latch.countDown();
                }
            });

            InvocationMessage message = new InvocationMessage();
            message.setArgs(null, "test", "test", new Object[] { new Integer(1) });
            message.setReplyTo("recorder");
            bus.send("bpmscript-first", message);
            latch.await();

            Continuation continuation = continuationReference.get();
            Object implementation = continuation.getImplementation();
            Field[] fields = implementation.getClass().getFields();
            // Field field = implementation.getClass().getField("idata");
            Field declaredField = implementation.getClass().getDeclaredField("idata");
            declaredField.setAccessible(true);
            Object object = declaredField.get(implementation);
            DebuggableScript debuggableScript = (DebuggableScript) object;

            printStuff(debuggableScript);

            //                DynamicContextFactory dynamicContextFactory = new DynamicContextFactory();
            //                dynamicContextFactory.addListener(new ContextFactory.Listener() {
            //                
            //                    public void contextReleased(Context cx) {
            //                        // TODO Auto-generated method stub
            //                
            //                    }
            //                
            //                    public void contextCreated(Context cx) {
            //                        // TODO Auto-generated method stub
            //                
            //                    }
            //                
            //                });
            //                Context cx = dynamicContextFactory.enterContext();
            //                cx.setOptimizationLevel(-1);
            //                cx.setDebugger(new Debugger() {
            //                
            //                    public void handleCompilationDone(Context cx, DebuggableScript fnOrScript, String source) {
            //                        log.info("here");
            //                    }
            //                
            //                    public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript) {
            //                        log.info("here");
            //                        return new DebugFrame() {
            //                        
            //                            public void onLineChange(Context cx, int lineNumber) {
            //                                log.info("onLineChange");
            //                            }
            //                        
            //                            public void onExit(Context cx, boolean byThrow, Object resultOrException) {
            //                                log.info("onExit");
            //                            }
            //                        
            //                            public void onExceptionThrown(Context cx, Throwable ex) {
            //                                log.info("onLineChange");
            //                            }
            //                        
            //                            public void onEnter(Context cx, Scriptable activation, Scriptable thisObj, Object[] args) {
            //                                log.info("onEnter");
            //                            }
            //                        
            //                            public void onDebuggerStatement(Context cx) {
            //                                log.info("onDebuggerStatement");
            //                            }
            //                        
            //                        };
            //                    }
            //                
            //                }, new Object());
            //                cx.setInstructionObserverThreshold(0);
            //                
            //                try {
            //                    Scriptable scope = scopeStore.findScope(cx, "id");
            //                    // // TODO: hang on, why do we pass the invocation context? hmmm... do we
            //                    // restore it in the get
            //                    // continuationService.getContinuation(new HashMap<String, Object>(), scope,
            //                    // pid, branch);
            //                    Object call = continuationReference.get().call(cx, scope, scope,
            //                            new Object[] { Context.javaToJS(new NextMessage("", "", "", "", "debug"), scope) });
            //                    assertNotNull(call);
            //                } finally {
            //                    Context.exit();
            //                }

        }

        /**
         * @param debuggableScript
         */
        private void printStuff(DebuggableScript debuggableScript) {
            log.debug("sourceName " + debuggableScript.getSourceName());
            log.debug("name " + debuggableScript.getFunctionName());
            int functionCount = debuggableScript.getFunctionCount();
            for (int i = 0; i < functionCount; i++) {
                log.debug("function " + debuggableScript.getFunction(i).getFunctionName());
            }
            int[] lineNumbers = debuggableScript.getLineNumbers();
            for (int j : lineNumbers) {
                log.debug("line number: " + j);
            }
            int paramAndVarCount = debuggableScript.getParamAndVarCount();
            for (int i = 0; i < paramAndVarCount; i++) {
                log.debug("param or var name " + debuggableScript.getParamOrVarName(i));
            }
            DebuggableScript parent = debuggableScript.getParent();
            if (parent != null) {
                printStuff(parent);
            }
        }

    });

}