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:io.restassured.module.mockmvc.ContentTypeTest.java

@Test
public void doesnt_add_default_charset_to_content_type_if_configured_not_to_do_so() {
    final AtomicReference<String> contentType = new AtomicReference<String>();

    RestAssuredMockMvc.given()/* www  . j  a v a2 s .  c o m*/
            .config(RestAssuredMockMvc.config().encoderConfig(
                    EncoderConfig.encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)))
            .standaloneSetup(new GreetingController()).contentType(ContentType.JSON)
            .interceptor(new MockHttpServletRequestBuilderInterceptor() {
                public void intercept(MockHttpServletRequestBuilder requestBuilder) {
                    MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder,
                            "headers");
                    contentType.set(String.valueOf(headers.getFirst("Content-Type")));
                }
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

    assertThat(contentType.get()).isEqualTo("application/json");
}

From source file:com.netflix.discovery.shared.Applications.java

/**
 * Shuffle the instances and filter for only {@link InstanceStatus#UP} if
 * required.//w  w w  . j av a2 s . c  o  m
 *
 */
private void shuffleAndFilterInstances(Map<String, AbstractQueue<InstanceInfo>> srcMap,
        Map<String, AtomicReference<List<InstanceInfo>>> destMap, Map<String, AtomicLong> vipIndexMap,
        boolean filterUpInstances) {
    for (Map.Entry<String, AbstractQueue<InstanceInfo>> entries : srcMap.entrySet()) {
        AbstractQueue<InstanceInfo> instanceInfoQueue = entries.getValue();
        List<InstanceInfo> l = new ArrayList<InstanceInfo>(instanceInfoQueue);
        if (filterUpInstances) {
            Iterator<InstanceInfo> it = l.iterator();

            while (it.hasNext()) {
                InstanceInfo instanceInfo = it.next();
                if (!InstanceStatus.UP.equals(instanceInfo.getStatus())) {
                    it.remove();
                }
            }
        }
        Collections.shuffle(l);
        AtomicReference<List<InstanceInfo>> instanceInfoList = destMap.get(entries.getKey());
        if (instanceInfoList == null) {
            instanceInfoList = new AtomicReference<List<InstanceInfo>>(l);
            destMap.put(entries.getKey(), instanceInfoList);
        }
        instanceInfoList.set(l);
        vipIndexMap.put(entries.getKey(), new AtomicLong(0));
    }

    // finally remove all vips that are completed deleted (i.e. missing) from the srcSet
    Set<String> srcVips = srcMap.keySet();
    Set<String> destVips = destMap.keySet();
    destVips.retainAll(srcVips);
}

From source file:com.dmbstream.android.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;/*from w  w w. j a  v a  2s. co  m*/
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Encoding.UTF_8.name()));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Add default headers to identify this app
        request.addHeader("Content-Type", "application/json");
        request.addHeader("X-ApiKey", ApiConstants.instance().getApiKey());
        request.addHeader("User-Agent", ApiConstants.instance().getAppName());

        String userToken = Util.getUserToken(context);
        if (!ValidationHelper.isNullOrWhitespace(userToken))
            request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(userToken, ""),
                    Encoding.UTF_8.name(), false));
        else
            Log.w(TAG, "No usertoken was specified for the request.");

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

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

@Test
public void testAcceptEcho() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    EchoOptionHandler optionHandler = new EchoOptionHandler(false, false, false, true);
    testOptionValue(() -> new TelnetHandler() {
        @Override/* w  w  w.j ava2  s.co  m*/
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.ECHO);
        }

        @Override
        protected void onEcho(boolean echo) {
            serverValue.set(echo);
            testComplete();
        }
    }, optionHandler);
    assertEquals(true, serverValue.get());
    assertEquals(true, optionHandler.getAcceptRemote());
}

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

@Test
public void testRejectEcho() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    EchoOptionHandler optionHandler = new EchoOptionHandler(false, false, false, false);
    testOptionValue(() -> new TelnetHandler() {
        @Override//from   ww  w.  j  av a2  s.  c  o m
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.ECHO);
        }

        @Override
        protected void onEcho(boolean echo) {
            serverValue.set(echo);
            testComplete();
        }
    }, optionHandler);
    assertEquals(false, serverValue.get());
    assertEquals(false, optionHandler.getAcceptRemote());
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSocketSink() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override/*from w w w .j  a v  a 2 s  .  co  m*/
        public void run() {
            try {
                SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0);
                simpleSink.open(new Configuration());
                simpleSink.invoke(TEST_MESSAGE + '\n');
                simpleSink.close();
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));

    String value = rdr.readLine();

    sinkRunner.join();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}

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

@Test
public void testAcceptSGA() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    SuppressGAOptionHandler optionHandler = new SuppressGAOptionHandler(false, false, false, true);
    testOptionValue(() -> new TelnetHandler() {
        @Override//from w w w  . j  a va  2 s  . co m
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.SGA);
        }

        @Override
        protected void onSGA(boolean sga) {
            serverValue.set(sga);
            testComplete();
        }
    }, optionHandler);
    assertEquals(true, serverValue.get());
    assertEquals(true, optionHandler.getAcceptRemote());
}

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

@Test
public void testRejectSGA() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    SuppressGAOptionHandler optionHandler = new SuppressGAOptionHandler(false, false, false, false);
    testOptionValue(() -> new TelnetHandler() {
        @Override/*w  w  w  .ja va 2 s.c o  m*/
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.SGA);
        }

        @Override
        protected void onSGA(boolean sga) {
            serverValue.set(sga);
            testComplete();
        }
    }, optionHandler);
    assertEquals(false, serverValue.get());
    assertEquals(false, optionHandler.getAcceptRemote());
}

From source file:fi.solita.phantomrunner.jetty.PhantomWebSocketHandler.java

public JsonNode sendMessageToConnections(String msg) {
    try {/* ww w. j a  v  a2 s .  co  m*/
        final Object requestLock = new Object();
        final AtomicReference<JsonNode> result = new AtomicReference<JsonNode>();

        synchronized (socketLock) {
            if (socket.get() == null) {
                // wait for 10 secs for the socket to open
                socketLock.wait(TimeUnit.SECONDS.toMillis(10));
            }
        }

        if (socket.get() == null) {
            throw new PhantomWebSocketException("No open websocket connection available, cannot send message");
        }

        try {
            socket.get().send(msg, new PhantomMessageListener() {
                @Override
                public void message(JsonNode readTree) {
                    synchronized (requestLock) {
                        result.set(readTree);
                        requestLock.notifyAll();
                    }
                }
            });
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        synchronized (requestLock) {
            requestLock.wait(10000);
        }

        return result.get();
    } catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
}