List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean
public AtomicBoolean(boolean initialValue)
From source file:info.archinnov.achilles.it.TestCRUDSimpleEntity.java
@Test public void should_delete_with_equal_condition() throws Exception { //Given/* w ww . j a v a 2 s .c o m*/ final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); final Date date = buildDateKey(); scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql", ImmutableMap.of("id", id, "table", "simple")); final AtomicBoolean success = new AtomicBoolean(false); final LWTResultListener lwtResultListener = new LWTResultListener() { @Override public void onSuccess() { success.getAndSet(true); } @Override public void onError(LWTResult lwtResult) { } }; //When manager.dsl().delete().allColumns_FromBaseTable().where().id_Eq(id).date_Eq(date) .ifSimpleSet_Eq(Sets.newHashSet(1.0, 2.0)).withLwtResultListener(lwtResultListener).execute(); //Then final Row row = session.execute("SELECT * FROM simple WHERE id = " + id).one(); assertThat(row).isNull(); assertThat(success.get()).isTrue(); }
From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java
private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId, final Buffer payload, final String contentType, final Future<MessageSender> senderTracker, final String endpointName) { if (!isPayloadOfIndicatedType(payload, contentType)) { HttpUtils.badRequest(ctx,/*from w w w. j av a 2s .c om*/ String.format("Content-Type %s does not match with the payload", contentType)); } else { final Integer qosHeader = getQoSLevel(ctx.request().getHeader(Constants.HEADER_QOS_LEVEL)); if (contentType == null) { HttpUtils.badRequest(ctx, String.format("%s header is missing", HttpHeaders.CONTENT_TYPE)); } else if (qosHeader != null && qosHeader == HEADER_QOS_INVALID) { HttpUtils.badRequest(ctx, "Bad QoS Header Value"); } else { final Device authenticatedDevice = getAuthenticatedDevice(ctx); final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice); final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant); // AtomicBoolean to control if the downstream message was sent successfully final AtomicBoolean downstreamMessageSent = new AtomicBoolean(false); // AtomicReference to a Handler to be called to close an open command receiver link. final AtomicReference<Handler<Void>> closeLinkAndTimerHandlerRef = new AtomicReference<>(); // Handler to be called with a received command. If the timer expired, null is provided as command. final Handler<Message> commandReceivedHandler = commandMessage -> { // reset the closeHandler reference, since it is not valid anymore at this time. closeLinkAndTimerHandlerRef.set(null); if (downstreamMessageSent.get()) { // finish the request, since the response is now complete (command was added) if (!ctx.response().closed()) { ctx.response().end(); } } }; CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> { if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) { final MessageSender sender = senderTracker.result(); final Message downstreamMessage = newMessage( ResourceIdentifier.from(endpointName, tenant, deviceId), sender.isRegistrationAssertionRequired(), ctx.request().uri(), contentType, payload, tokenTracker.result(), HttpUtils.getTimeTilDisconnect(ctx)); customizeDownstreamMessage(downstreamMessage, ctx); // first open the command receiver link (if needed) return openCommandReceiverLink(ctx, tenant, deviceId, commandReceivedHandler) .compose(closeLinkAndTimerHandler -> { closeLinkAndTimerHandlerRef.set(closeLinkAndTimerHandler); if (qosHeader == null) { return sender.send(downstreamMessage); } else { return sender.sendAndWaitForOutcome(downstreamMessage); } }); } else { // this adapter is not enabled for the tenant return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN)); } }).compose(delivery -> { LOG.trace( "successfully processed message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName); metrics.incrementProcessedHttpMessages(endpointName, tenant); ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED); downstreamMessageSent.set(true); // if no command timer was created, the request now can be responded if (closeLinkAndTimerHandlerRef.get() == null) { ctx.response().end(); } return Future.succeededFuture(); }).recover(t -> { LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName, t); cancelResponseTimer(closeLinkAndTimerHandlerRef); if (ClientErrorException.class.isInstance(t)) { final ClientErrorException e = (ClientErrorException) t; ctx.fail(e.getErrorCode()); } else { metrics.incrementUndeliverableHttpMessages(endpointName, tenant); HttpUtils.serviceUnavailable(ctx, 2); } return Future.failedFuture(t); }); } } }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testEndpointNotAvailable() throws InterruptedException { _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> { // Annotations Assert.assertEquals(0, r.getAnnotationsCount()); // Dimensions Assert.assertEquals(0, r.getDimensionsCount()); // Samples Assert.assertEquals(0, r.getTimersCount()); Assert.assertEquals(0, r.getCountersCount()); Assert.assertEquals(0, r.getGaugesCount()); })).willReturn(WireMock.aResponse().withStatus(404))); final AtomicBoolean assertionResult = new AtomicBoolean(false); final Semaphore semaphore = new Semaphore(0); final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class); final Sink sink = new ApacheHttpSink( new ApacheHttpSink.Builder().setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)) .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 1, 2, false, new CompletionHandler(semaphore))), logger);/*from w w w. j a v a 2 s . c om*/ final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS, TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event); semaphore.acquire(); // Ensure expected handler was invoked Assert.assertTrue(assertionResult.get()); // Request matcher final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH)) .withHeader("Content-Type", WireMock.equalTo("application/octet-stream")); // Assert that data was sent _wireMockRule.verify(1, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); // Assert that an IOException was captured Mockito.verify(logger).error( Mockito.startsWith("Encountered failure when sending metrics to HTTP endpoint; uri="), Mockito.any(RuntimeException.class)); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.PendingChange.java
/** * Acquires base content if the pending change is in local workspace. If * file is in the baseline folder, copies it from there. If not, downloads * it from the server.//ww w . j a v a 2 s .c om * * @param client * the {@link VersionControlClient} to use (must not be * <code>null</code>) * @param localFileName * the local file name to copy the baseline to (must not be * <code>null</code>) * @return true if this pending change is in local workspace, false if this * is server workspace. * @throws VersionControlException * if this is local workspace but we failed to acquire content (e.g. * baseline is deleted and connection to the server failed). */ private boolean copyLocalBaseline(final VersionControlClient client, final String localFileName) { Check.notNull(client, "client"); //$NON-NLS-1$ Check.notNull(localFileName, "localFileName"); //$NON-NLS-1$ final AtomicBoolean handled = new AtomicBoolean(false); Check.isTrue( pendingSetName != null && pendingSetName.length() > 0 && pendingSetOwner != null && pendingSetOwner.length() > 0, MessageFormat.format("PendingSetName or PendingSetOwner were not populated for pending change {0}", //$NON-NLS-1$ toString())); if (inShelveset || pendingSetName == null || pendingSetName.length() == 0 || pendingSetOwner == null || pendingSetOwner.length() == 0) { return handled.get(); } final Workspace workspace = client.getRuntimeWorkspaceCache().tryGetWorkspace(pendingSetName, pendingSetOwner); if (workspace != null && workspace.getLocation() == WorkspaceLocation.LOCAL) { if (isAdd()) { throw new VersionControlException( MessageFormat.format(Messages.getString("PendingChange.NoBaseFileForPendingChangeFormat"), //$NON-NLS-1$ getLocalOrServerItem())); } final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace); try { transaction.execute(new WorkspacePropertiesLocalVersionTransaction() { @Override public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv) { final WorkspaceLocalItem lvEntry = lv.getByPendingChange(PendingChange.this); if (null != lvEntry && null != lvEntry.getBaselineFileGUID()) { try { final boolean symlink = PropertyConstants.IS_SYMLINK .equals(PropertyUtils.selectMatching(lvEntry.getPropertyValues(), PropertyConstants.SYMBOLIC_KEY)); wp.copyBaselineToTarget(lvEntry.getBaselineFileGUID(), localFileName, lvEntry.getLength(), lvEntry.getHashValue(), symlink); handled.set(true); } catch (final Exception e) { /* Could not copy the local baseline */ } } } }); } finally { try { transaction.close(); } catch (final IOException e) { throw new VersionControlException(e); } } if (!handled.get()) { // we don't have baseline which we should have, let's hit the // server to get it // TODO we can compress and store it as a baseline final String serverItem = (getSourceServerItem() == null || getSourceServerItem().length() == 0) ? getServerItem() : getSourceServerItem(); final int versionToDownload = isBranch() ? getSourceVersionFrom() : getVersion(); // for pending branch we use SourceServerItem (source of // branch), but SourceVersionFrom (version of the source) // instead of Version since it's not committed final Item item = client.getItem(serverItem, new ChangesetVersionSpec(versionToDownload), getDeletionID(), true); client.downloadFile(new DownloadSpec(item.getDownloadURL()), new File(localFileName), true); handled.set(true); } } return handled.get(); }
From source file:info.archinnov.achilles.it.TestCRUDSimpleEntity.java
@Test public void should_delete_with_inequal_condition() throws Exception { //Given//from w w w . jav a2 s .c om final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); final Date date = buildDateKey(); scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql", ImmutableMap.of("id", id, "table", "simple")); final AtomicBoolean success = new AtomicBoolean(false); final LWTResultListener lwtResultListener = new LWTResultListener() { @Override public void onSuccess() { success.getAndSet(true); } @Override public void onError(LWTResult lwtResult) { } }; //When manager.dsl().delete().allColumns_FromBaseTable().where().id_Eq(id).date_Eq(date).ifValue_Lt("_") .withLwtResultListener(lwtResultListener).execute(); //Then final Row row = session.execute("SELECT * FROM simple WHERE id = " + id).one(); assertThat(row).isNull(); assertThat(success.get()).isTrue(); }
From source file:com.streamsets.pipeline.stage.origin.jdbc.AbstractTableJdbcSource.java
private synchronized boolean shutdownExecutorIfNeeded() { AtomicBoolean interrupted = new AtomicBoolean(false); Optional.ofNullable(executorService).ifPresent(executor -> { if (!executor.isTerminated()) { LOG.info("Shutting down executor service"); executor.shutdown();/*from w w w . j ava2 s .c om*/ try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { LOG.warn("Shutdown interrupted"); interrupted.set(true); } } }); return interrupted.get(); }
From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java
@Test public void testReadRetrybugWhenChannelThrowsAccessException() throws IOException, URISyntaxException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { final String tempPathPrefix = null; final Path tempDirectoryPath = Files.createTempDirectory(Paths.get("."), tempPathPrefix); final AtomicBoolean caughtException = new AtomicBoolean(false); try {/*from w w w . j a v a 2s . c o m*/ final String DIR_NAME = "largeFiles/"; final String FILE_NAME = "lesmis-copies.txt"; final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME); final long bookSize = Files.size(objPath); final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize); final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client); final int maxNumBlockAllocationRetries = 1; final int maxNumObjectTransferAttempts = 3; final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim, maxNumBlockAllocationRetries, maxNumObjectTransferAttempts); final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj)); final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId())); assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue())); readJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { throw new AccessControlException(key); } }); } catch (final IOException e) { caughtException.set(true); assertTrue(e.getCause() instanceof AccessControlException); } finally { FileUtils.deleteDirectory(tempDirectoryPath.toFile()); } assertTrue(caughtException.get()); }
From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java
@Test public void testBuildWithPull() throws Exception { assumeTrue("We need Docker API >= v1.19 to run this test." + "This Docker API is " + sut.version().apiVersion(), versionCompare(sut.version().apiVersion(), "1.19") >= 0); final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); final String pullMsg = "Pulling from"; // Build once to make sure we have cached images. sut.build(Paths.get(dockerDirectory)); // Build again with PULL set, and verify we pulled the base image final AtomicBoolean pulled = new AtomicBoolean(false); sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() { @Override//from w w w . ja v a2 s . c om public void progress(ProgressMessage message) throws DockerException { if (message.status().contains(pullMsg)) { pulled.set(true); } } }, PULL_NEWER_IMAGE); assertTrue(pulled.get()); }
From source file:com.datatorrent.stram.engine.GenericNodeTest.java
private void testCheckpointDistance(int dagCheckPoint, int opCheckPoint) throws InterruptedException { int windowWidth = 50; long sleeptime = 25L; int maxWindows = 60; // Adding some extra time for the windows to finish long maxSleep = windowWidth * maxWindows + 5000; ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, "default"); final WindowGenerator windowGenerator = new WindowGenerator(executorService, 1024); windowGenerator.setWindowWidth(windowWidth); windowGenerator.setFirstWindow(executorService.getCurrentTimeMillis()); windowGenerator.setCheckpointCount(dagCheckPoint, 0); //GenericOperator go = new GenericOperator(); CheckpointDistanceOperator go = new CheckpointDistanceOperator(); go.maxWindows = maxWindows;//w ww .java2 s. c o m List<Integer> checkpoints = new ArrayList<Integer>(); int window = 0; while (window < maxWindows) { window = (int) Math.ceil((double) (window + 1) / dagCheckPoint) * dagCheckPoint; window = (int) Math.ceil((double) window / opCheckPoint) * opCheckPoint; checkpoints.add(window); } final StreamContext stcontext = new StreamContext("s1"); DefaultAttributeMap attrMap = new DefaultAttributeMap(); attrMap.put(Context.DAGContext.CHECKPOINT_WINDOW_COUNT, dagCheckPoint); attrMap.put(Context.OperatorContext.CHECKPOINT_WINDOW_COUNT, opCheckPoint); final OperatorContext context = new com.datatorrent.stram.engine.OperatorContext(0, attrMap, null); final GenericNode gn = new GenericNode(go, context); gn.setId(1); //DefaultReservoir reservoir1 = new DefaultReservoir("ip1Res", 1024); //DefaultReservoir reservoir2 = new DefaultReservoir("ip2Res", 1024); //gn.connectInputPort("ip1", reservoir1); //gn.connectInputPort("ip2", reservoir2); gn.connectInputPort("ip1", windowGenerator.acquireReservoir("ip1", 1024)); gn.connectInputPort("ip2", windowGenerator.acquireReservoir("ip2", 1024)); gn.connectOutputPort("op", Sink.BLACKHOLE); final AtomicBoolean ab = new AtomicBoolean(false); Thread t = new Thread() { @Override public void run() { gn.setup(context); windowGenerator.activate(stcontext); gn.activate(); ab.set(true); gn.run(); windowGenerator.deactivate(); gn.deactivate(); gn.teardown(); } }; t.start(); long interval = 0; do { Thread.sleep(sleeptime); interval += sleeptime; } while ((go.numWindows < maxWindows) && (interval < maxSleep)); Assert.assertEquals("Number distances", maxWindows, go.numWindows); int chkindex = 0; int nextCheckpoint = checkpoints.get(chkindex++); for (int i = 0; i < maxWindows; ++i) { if ((i + 1) > nextCheckpoint) { nextCheckpoint = checkpoints.get(chkindex++); } Assert.assertEquals("Windows from checkpoint for " + i, nextCheckpoint - i, (int) go.distances.get(i)); } gn.shutdown(); t.join(); }
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java
@Test public void testFlush() throws Exception { final Timing timing = new Timing(); final CountDownLatch latch = new CountDownLatch(1); DistributedQueue<TestQueueItem> queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();/*w ww. j av a2 s.co m*/ try { final AtomicBoolean firstTime = new AtomicBoolean(true); queue = new DistributedQueue<TestQueueItem>(client, null, serializer, "/test", new ThreadFactoryBuilder().build(), MoreExecutors.sameThreadExecutor(), 10, true, null, QueueBuilder.NOT_SET, true, 0) { @Override void internalCreateNode(final String path, final byte[] bytes, final BackgroundCallback callback) throws Exception { if (firstTime.compareAndSet(true, false)) { Executors.newSingleThreadExecutor().submit(new Callable<Object>() { @Override public Object call() throws Exception { latch.await(); timing.sleepABit(); client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback) .forPath(path, bytes); return null; } }); } else { super.internalCreateNode(path, bytes, callback); } } }; queue.start(); queue.put(new TestQueueItem("1")); Assert.assertFalse(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); latch.countDown(); Assert.assertTrue(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { if (latch.getCount() > 0) { latch.countDown(); } IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } }