List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference
public AtomicReference()
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 a v a 2 s. 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:org.elasticsearch.client.HeapBufferedAsyncResponseConsumerTests.java
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override//w w w .j a v a2s .c o m public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch (ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
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 .j av a 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(false, serverValue.get()); assertEquals(false, optionHandler.getAcceptRemote()); }
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//ww w . j a v a2 s . c o m * 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:io.restassured.module.mockmvc.ContentTypeTest.java
@Test public void doesnt_add_default_charset_to_content_type_if_charset_is_defined_explicitly() { final AtomicReference<String> contentType = new AtomicReference<String>(); RestAssuredMockMvc.given().standaloneSetup(new GreetingController()) .contentType(ContentType.JSON.withCharset("UTF-16")) .interceptor(new MockHttpServletRequestBuilderInterceptor() { public void intercept(MockHttpServletRequestBuilder requestBuilder) { MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder, "headers"); contentType.set(String.valueOf(headers.getFirst("Content-Type"))); }/*from www. j a v a 2s . c o m*/ }).when().get("/greeting?name={name}", "Johan").then().statusCode(200); assertThat(contentType.get()).isEqualTo("application/json;charset=UTF-16"); }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.mock.TestUtils.java
/** * Get the future build to start as reference. * * @param event the event to monitor./* w w w. j a va2 s .c o m*/ * @return the reference of future build to start. */ public static AtomicReference<Run> getFutureBuildToStart2(GerritEventLifecycle event) { final AtomicReference<Run> reference = new AtomicReference<Run>(); event.addListener(new GerritEventLifeCycleAdaptor() { @Override public void buildStarted(GerritEvent event, Run build) { reference.getAndSet(build); } }); return reference; }
From source file:eu.eubrazilcc.lvl.storage.LinkedInStateCollectionTest.java
@Test public void test() { System.out.println("LinkedInStateCollectionTest.test()"); try {/* ww w .j ava 2 s . c o m*/ // insert final long issuedAt = currentTimeMillis() / 1000l; final LinkedInState state = LinkedInState.builder().state("1234567890abcdEFGhiJKlMnOpqrstUVWxyZ") .issuedAt(issuedAt).expiresIn(23l).redirectUri("http://localhost/redirect") .callback("http://localhost/callback").build(); LINKEDIN_STATE_DAO.insert(state); // find LinkedInState state2 = LINKEDIN_STATE_DAO.find(state.getState()); assertThat("linkedin state is not null", state2, notNullValue()); assertThat("linkedin state coincides with original", state2, equalTo(state)); System.out.println(state2.toString()); // update state.setExpiresIn(604800l); LINKEDIN_STATE_DAO.update(state); // find after update state2 = LINKEDIN_STATE_DAO.find(state.getState()); assertThat("linkedin state is not null", state2, notNullValue()); assertThat("linkedin state coincides with original", state2, equalTo(state)); System.out.println(state2.toString()); // list by issued date List<LinkedInState> states = LINKEDIN_STATE_DAO.listByIssuedDate(new Date(issuedAt)); assertThat("linkedin states are not null", states, notNullValue()); assertThat("linkedin states are not empty", !states.isEmpty(), equalTo(true)); assertThat("number of linkedin states coincides with expected", states.size(), equalTo(1)); assertThat("linkedin states coincide with original", states.get(0), equalTo(state)); // check validity final AtomicReference<String> redirectUriRef = new AtomicReference<String>(); final AtomicReference<String> callbackRef = new AtomicReference<String>(); boolean validity = LINKEDIN_STATE_DAO.isValid(state.getState(), redirectUriRef, callbackRef); assertThat("linkedin state is valid", validity, equalTo(true)); assertThat("linkedin redirect URI is not null", redirectUriRef.get(), notNullValue()); assertThat("linkedin redirect URI coincides with expected", redirectUriRef.get(), equalTo("http://localhost/redirect")); assertThat("linkedin callback URI is not null", callbackRef.get(), notNullValue()); assertThat("linkedin callback URI coincides with expected", callbackRef.get(), equalTo("http://localhost/callback")); // remove LINKEDIN_STATE_DAO.delete(state.getState()); final long numRecords = LINKEDIN_STATE_DAO.count(); assertThat("number of linkedin states stored in the database coincides with expected", numRecords, equalTo(0l)); // pagination final List<String> ids = newArrayList(); for (int i = 0; i < 11; i++) { final LinkedInState state3 = LinkedInState.builder().state(Integer.toString(i)).build(); ids.add(state3.getState()); LINKEDIN_STATE_DAO.insert(state3); } final int size = 3; int start = 0; states = null; final MutableLong count = new MutableLong(0l); do { states = LINKEDIN_STATE_DAO.list(start, size, null, null, null, count); if (states.size() != 0) { System.out.println("Paging: first item " + start + ", showing " + states.size() + " of " + count.getValue() + " items"); } start += states.size(); } while (!states.isEmpty()); for (final String id2 : ids) { LINKEDIN_STATE_DAO.delete(id2); } LINKEDIN_STATE_DAO.stats(System.out); } catch (Exception e) { e.printStackTrace(System.err); fail("LinkedInStateCollectionTest.test() failed: " + e.getMessage()); } finally { System.out.println("LinkedInStateCollectionTest.test() has finished"); } }
From source file:org.apache.brooklyn.util.http.HttpTool.java
/** * Connects to the given url and returns the connection. * Caller should {@code connection.getInputStream().close()} the result of this * (especially if they are making heavy use of this method). *//*w w w . j a va2 s .c om*/ public static URLConnection connectToUrl(String u) throws Exception { final URL url = new URL(u); final AtomicReference<Exception> exception = new AtomicReference<Exception>(); // sometimes openConnection hangs, so run in background Future<URLConnection> f = executor.submit(new Callable<URLConnection>() { public URLConnection call() { try { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); URLConnection connection = url.openConnection(); TrustingSslSocketFactory.configure(connection); connection.connect(); connection.getContentLength(); // Make sure the connection is made. return connection; } catch (Exception e) { exception.set(e); LOG.debug("Error connecting to url " + url + " (propagating): " + e, e); } return null; } }); try { URLConnection result = null; try { result = f.get(60, TimeUnit.SECONDS); } catch (InterruptedException e) { throw e; } catch (Exception e) { LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e); throw new IllegalStateException( "Connect to URL not complete within 60 seconds, for url " + url + ": " + e); } if (exception.get() != null) { LOG.debug("Error connecting to url " + url + ", thread caller of " + exception, new Throwable("source of rethrown error " + exception)); throw exception.get(); } else { return result; } } finally { f.cancel(true); } }
From source file:it.anyplace.sync.bep.BlockPuller.java
public FileDownloadObserver pullBlocks(FileBlocks fileBlocks) throws InterruptedException { logger.info("pulling file = {}", fileBlocks); checkArgument(connectionHandler.hasFolder(fileBlocks.getFolder()), "supplied connection handler %s will not share folder %s", connectionHandler, fileBlocks.getFolder());//ww w . j a va 2 s. com final Object lock = new Object(); final AtomicReference<Exception> error = new AtomicReference<>(); final Object listener = new Object() { @Subscribe public void handleResponseMessageReceivedEvent(ResponseMessageReceivedEvent event) { synchronized (lock) { try { if (!requestIds.contains(event.getMessage().getId())) { return; } checkArgument(equal(event.getMessage().getCode(), ErrorCode.NO_ERROR), "received error response, code = %s", event.getMessage().getCode()); byte[] data = event.getMessage().getData().toByteArray(); String hash = BaseEncoding.base16().encode(Hashing.sha256().hashBytes(data).asBytes()); blockCache.pushBlock(data); if (missingHashes.remove(hash)) { blocksByHash.put(hash, data); logger.debug("aquired block, hash = {}", hash); lock.notify(); } else { logger.warn("received not-needed block, hash = {}", hash); } } catch (Exception ex) { error.set(ex); lock.notify(); } } } }; FileDownloadObserver fileDownloadObserver = new FileDownloadObserver() { private long getReceivedData() { return blocksByHash.size() * BLOCK_SIZE; } private long getTotalData() { return (blocksByHash.size() + missingHashes.size()) * BLOCK_SIZE; } @Override public double getProgress() { return isCompleted() ? 1d : getReceivedData() / ((double) getTotalData()); } @Override public String getProgressMessage() { return (Math.round(getProgress() * 1000d) / 10d) + "% " + FileUtils.byteCountToDisplaySize(getReceivedData()) + " / " + FileUtils.byteCountToDisplaySize(getTotalData()); } @Override public boolean isCompleted() { return missingHashes.isEmpty(); } @Override public void checkError() { if (error.get() != null) { throw new RuntimeException(error.get()); } } @Override public double waitForProgressUpdate() throws InterruptedException { if (!isCompleted()) { synchronized (lock) { checkError(); lock.wait(); checkError(); } } return getProgress(); } @Override public InputStream getInputStream() { checkArgument(missingHashes.isEmpty(), "pull failed, some blocks are still missing"); List<byte[]> blockList = Lists .newArrayList(Lists.transform(hashList, Functions.forMap(blocksByHash))); return new SequenceInputStream(Collections .enumeration(Lists.transform(blockList, new Function<byte[], ByteArrayInputStream>() { @Override public ByteArrayInputStream apply(byte[] data) { return new ByteArrayInputStream(data); } }))); } @Override public void close() { missingHashes.clear(); hashList.clear(); blocksByHash.clear(); try { connectionHandler.getEventBus().unregister(listener); } catch (Exception ex) { } if (closeConnection) { connectionHandler.close(); } } }; try { synchronized (lock) { hashList.addAll(Lists.transform(fileBlocks.getBlocks(), new Function<BlockInfo, String>() { @Override public String apply(BlockInfo block) { return block.getHash(); } })); missingHashes.addAll(hashList); for (String hash : missingHashes) { byte[] block = blockCache.pullBlock(hash); if (block != null) { blocksByHash.put(hash, block); missingHashes.remove(hash); } } connectionHandler.getEventBus().register(listener); for (BlockInfo block : fileBlocks.getBlocks()) { if (missingHashes.contains(block.getHash())) { int requestId = Math.abs(new Random().nextInt()); requestIds.add(requestId); connectionHandler.sendMessage(Request.newBuilder().setId(requestId) .setFolder(fileBlocks.getFolder()).setName(fileBlocks.getPath()) .setOffset(block.getOffset()).setSize(block.getSize()) .setHash(ByteString.copyFrom(BaseEncoding.base16().decode(block.getHash()))) .build()); logger.debug("sent request for block, hash = {}", block.getHash()); } } return fileDownloadObserver; } } catch (Exception ex) { fileDownloadObserver.close(); throw ex; } }
From source file:de.hybris.platform.test.HJMPOptimisticConcurrencyPerformanceTest.java
private void doTestMissingUpdateProblem() throws JaloBusinessException, InterruptedException { final Media m = MediaManager.getInstance().createMedia("codeBefore"); try {//from w w w . java2 s . co m m.setMime("mimeBefore"); m.setDescription("descriptionBefore"); final CyclicBarrier txStartJoinPoint = new CyclicBarrier(2); final AtomicReference<Throwable> tx1Error = new AtomicReference<Throwable>(); final AtomicReference<Throwable> tx2Error = new AtomicReference<Throwable>(); final Thread[] threads = createTxThreads(// new TxRunnable() { @Override public void run() throws Exception { txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to begin assertEquals("codeBefore", m.getCode()); txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to have read same version m.setMime("tx1Mime"); m.setCode("tx1Code"); } }, // new TxRunnable() { @Override public void run() throws Exception { txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx assertEquals("codeBefore", m.getCode()); txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to have read same version m.setMime("tx2Mime"); m.setDescription("tx2Description"); } }, tx1Error, tx2Error); threads[0].start(); threads[1].start(); threads[0].join(50 * 1000); threads[1].join(50 * 1000); assertFalse(threads[0].isAlive()); assertFalse(threads[1].isAlive()); if (isConcurrentModificationCheckEnabled()) { assertEquals("missing update from tx1", "tx1Code", m.getCode()); assertEquals("missing update from tx1", "tx1Mime", m.getMime()); assertEquals("unexpected update from tx2", "descriptionBefore", m.getDescription()); assertNull("unexpected error from tx1", tx1Error.get()); assertNotNull("expected error from tx2", tx2Error.get()); } else { assertNull("unexpected error from tx1", tx1Error.get()); assertNull("unexpected error from tx2", tx2Error.get()); assertEquals("missing update from tx1", "tx1Code", m.getCode()); assertEquals("missing update from tx2", "tx2Description", m.getDescription()); assertEquals("missing update from tx2", "tx2Mime", m.getMime()); } } finally { m.remove(); } }