List of usage examples for java.util.concurrent.atomic AtomicInteger incrementAndGet
public final int incrementAndGet()
From source file:net.solarnetwork.node.dao.jdbc.AbstractBatchableJdbcDao.java
private BatchResult batchProcessInternal(final BatchCallback<T> callback, final BatchOptions options) { final String querySql = getBatchJdbcStatement(options); final AtomicInteger rowCount = new AtomicInteger(0); getJdbcTemplate().execute(new ConnectionCallback<Object>() { @Override//from w w w . jav a2 s. c o m public net.solarnetwork.node.dao.BatchableDao.BatchResult doInConnection(Connection con) throws SQLException, DataAccessException { PreparedStatement queryStmt = null; ResultSet queryResult = null; try { queryStmt = con.prepareStatement(querySql, (options.isUpdatable() ? ResultSet.TYPE_SCROLL_SENSITIVE : ResultSet.TYPE_FORWARD_ONLY), (options.isUpdatable() ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY), ResultSet.CLOSE_CURSORS_AT_COMMIT); queryResult = queryStmt.executeQuery(); while (queryResult.next()) { T entity = getBatchRowEntity(options, queryResult, rowCount.incrementAndGet()); BatchCallbackResult rowResult = callback.handle(entity); switch (rowResult) { case CONTINUE: break; case STOP: return null; case DELETE: queryResult.deleteRow(); break; case UPDATE: case UPDATE_STOP: updateBatchRowEntity(options, queryResult, rowCount.intValue(), entity); queryResult.updateRow(); if (rowResult == BatchCallbackResult.UPDATE_STOP) { return null; } break; } } } finally { if (queryResult != null) { queryResult.close(); } if (queryStmt != null) { queryStmt.close(); } } return null; } }); return new BasicBatchResult(rowCount.intValue()); }
From source file:com.facebook.BatchRequestTests.java
@LargeTest public void testMixedBatchCallbacks() { final AtomicInteger requestProgressCount = new AtomicInteger(); final AtomicInteger requestCompletedCount = new AtomicInteger(); final AtomicInteger batchProgressCount = new AtomicInteger(); final AtomicInteger batchCompletedCount = new AtomicInteger(); final AccessToken accessToken = getAccessTokenForSharedUser(); String appId = getApplicationId(); GraphRequest.setDefaultBatchApplicationId(appId); GraphRequest request1 = GraphRequest.newGraphPathRequest(null, "4", new GraphRequest.OnProgressCallback() { @Override/*from w w w . j a v a 2 s .c om*/ public void onCompleted(GraphResponse response) { requestCompletedCount.incrementAndGet(); } @Override public void onProgress(long current, long max) { if (current == max) { requestProgressCount.incrementAndGet(); } else if (current > max) { requestProgressCount.set(0); } } }); assertNotNull(request1); GraphRequest request2 = GraphRequest.newGraphPathRequest(null, "4", null); assertNotNull(request2); GraphRequestBatch batch = new GraphRequestBatch(request1, request2); batch.addCallback(new GraphRequestBatch.OnProgressCallback() { @Override public void onBatchCompleted(GraphRequestBatch batch) { batchCompletedCount.incrementAndGet(); } @Override public void onBatchProgress(GraphRequestBatch batch, long current, long max) { if (current == max) { batchProgressCount.incrementAndGet(); } else if (current > max) { batchProgressCount.set(0); } } }); batch.executeAndWait(); assertEquals(1, requestProgressCount.get()); assertEquals(1, requestCompletedCount.get()); assertEquals(1, batchProgressCount.get()); assertEquals(1, batchCompletedCount.get()); }
From source file:org.dataconservancy.packaging.tool.integration.PackageGenerationTest.java
@Test public void complexPropertiesTest() throws Exception { PackageState initialState = initializer.initialize(DCS_PROFILE); OpenedPackage opened = packager.createPackage(initialState, folder.getRoot()); DomainProfileService profileService = profileServiceFactory .getProfileService(opened.getPackageState().getDomainObjectRDF()); Property creator1 = new Property(bop.getHasCreator()); Property creator1_name = new Property(bop.getName()); creator1_name.setStringValue("Fred"); Property creator1_mbox = new Property(bop.getMbox()); creator1_mbox.setStringValue("fred@mertz.org"); creator1.setComplexValue(Arrays.asList(creator1_name, creator1_mbox)); Property creator2 = new Property(bop.getHasCreator()); Property creator2_name = new Property(bop.getName()); creator2_name.setStringValue("Ethel"); Property creator2_mbox = new Property(bop.getMbox()); creator2_mbox.setStringValue("ethel@mertz.org"); creator2.setComplexValue(Arrays.asList(creator2_name, creator2_mbox)); AtomicInteger collectionCount = new AtomicInteger(0); /* Add two creators to each collection */ opened.getPackageTree().walk(node -> { if (node.getNodeType().getDomainTypes().contains(URI.create(NS_DCS_ONTOLOGY_BOM + "Collection"))) { collectionCount.incrementAndGet(); profileService.addProperty(node, creator1); profileService.addProperty(node, creator2); }//from w ww .j a va2 s. c o m }); OpenedPackage afterSaveAndReopen = packager.createPackage(opened.getPackageState(), folder.getRoot()); Set<String> initialObjects = initialState.getDomainObjectRDF().listObjects().filterKeep(RDFNode::isLiteral) .mapWith(RDFNode::asLiteral).mapWith(Literal::getString).toSet(); Set<String> openedObjects = opened.getPackageState().getDomainObjectRDF().listObjects() .filterKeep(RDFNode::isLiteral).mapWith(RDFNode::asLiteral).mapWith(Literal::getString).toSet(); Set<String> afterSaveAndReopenObjects = afterSaveAndReopen.getPackageState().getDomainObjectRDF() .listObjects().filterKeep(RDFNode::isLiteral).mapWith(RDFNode::asLiteral) .mapWith(Literal::getString).toSet(); Set<String> afterSaveAndReopenCustodialObjects = custodialDomainObjects(afterSaveAndReopen).listObjects() .filterKeep(RDFNode::isLiteral).mapWith(RDFNode::asLiteral).mapWith(Literal::getString).toSet(); assertFalse(initialObjects.contains(creator1_name.getStringValue())); assertTrue(openedObjects.contains(creator1_name.getStringValue())); assertTrue(openedObjects.contains(creator2_name.getStringValue())); assertEquals(2 * collectionCount.get(), opened.getPackageState().getDomainObjectRDF() .listStatements(null, opened.getPackageState().getDomainObjectRDF() .getProperty(creator1.getPropertyType().getDomainPredicate().toString()), (RDFNode) null) .toSet().size()); assertTrue(afterSaveAndReopenObjects.contains(creator1_name.getStringValue())); assertTrue(afterSaveAndReopenObjects.contains(creator2_name.getStringValue())); assertTrue(afterSaveAndReopenCustodialObjects.contains(creator1_name.getStringValue())); assertTrue(afterSaveAndReopenCustodialObjects.contains(creator2_name.getStringValue())); assertNotEquals(domainObjectSizes(initialState), domainObjectSizes(opened.getPackageState())); assertEquals(domainObjectSizes(opened.getPackageState()), domainObjectSizes(afterSaveAndReopen.getPackageState())); Model custodialAfterSaveAndReopen = custodialDomainObjects(afterSaveAndReopen); assertEquals(afterSaveAndReopen.getPackageState().getDomainObjectRDF().listStatements().toSet().size(), custodialAfterSaveAndReopen.listStatements().toSet().size()); }
From source file:net.ychron.unirestins.test.http.UnirestInstTest.java
private void makeParallelRequests() throws InterruptedException { ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); final AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < 200; i++) { newFixedThreadPool.execute(new Runnable() { public void run() { try { unirestInst.get("http://httpbin.org/get").queryString("index", counter.incrementAndGet()) .asJson();/*from ww w . j ava 2s . c o m*/ } catch (UnirestException e) { throw new RuntimeException(e); } } }); } newFixedThreadPool.shutdown(); newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); }
From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializerTest.java
@Test public void testMarshalEntireState() throws Exception { ByteArrayOutputStream sink = new ByteArrayOutputStream(); underTest.setArchive(false);//from w w w .j a v a 2s .com underTest.serialize(state, sink); AtomicInteger verifiedStreamCount = new AtomicInteger(0); mockedMarshallerMap.entrySet().forEach(entry -> { StreamId streamId = entry.getKey(); StreamMarshaller streamMarshaller = entry.getValue(); try { switch (streamId) { case APPLICATION_VERSION: verify(streamMarshaller.getMarshaller()).marshal(eq(applicationVersion), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; case PACKAGE_NAME: verify(streamMarshaller.getMarshaller()).marshal(eq(packageName), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; case PACKAGE_METADATA: verify(streamMarshaller.getMarshaller()).marshal(eq(packageMetadata), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; case DOMAIN_PROFILE_LIST: verify(streamMarshaller.getMarshaller()).marshal(eq(domainProfileUris), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; case DOMAIN_OBJECTS: verify(streamMarshaller.getMarshaller()).marshal(eq(domainObjectsRDF), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; case USER_SPECIFIED_PROPERTIES: verify(streamMarshaller.getMarshaller()).marshal(eq(userProperties), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; case PACKAGE_TREE: verify(streamMarshaller.getMarshaller()).marshal(eq(packageTreeRDF), isNotNull(Result.class)); verifiedStreamCount.incrementAndGet(); break; } } catch (IOException e) { fail("Encountered IOE: " + e.getMessage()); } }); assertEquals(mockedMarshallerMap.size(), verifiedStreamCount.intValue()); }
From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java
/** * Tests the ability of getOrAssignStreamSegmentId to handle the TooManyActiveSegmentsException. *///w w w . j a v a 2s. com @Test public void testGetOrAssignStreamSegmentIdWithMetadataLimit() throws Exception { final String segmentName = "Segment"; final String transactionName = StreamSegmentNameUtils.getTransactionNameFromId(segmentName, UUID.randomUUID()); HashSet<String> storageSegments = new HashSet<>(); storageSegments.add(segmentName); storageSegments.add(transactionName); @Cleanup TestContext context = new TestContext(); setupStorageGetHandler(context, storageSegments, name -> new StreamSegmentInformation(name, 0, false, false, new ImmutableDate())); // 1. Verify the behavior when even after the retry we still cannot map. AtomicInteger exceptionCounter = new AtomicInteger(); AtomicBoolean cleanupInvoked = new AtomicBoolean(); // We use 'containerId' as a proxy for the exception id (to make sure we collect the right one). context.operationLog.addHandler = op -> FutureHelpers .failedFuture(new TooManyActiveSegmentsException(exceptionCounter.incrementAndGet(), 0)); Supplier<CompletableFuture<Void>> noOpCleanup = () -> { if (!cleanupInvoked.compareAndSet(false, true)) { return FutureHelpers.failedFuture(new AssertionError("Cleanup invoked multiple times/")); } return CompletableFuture.completedFuture(null); }; val mapper1 = new StreamSegmentMapper(context.metadata, context.operationLog, context.stateStore, noOpCleanup, context.storage, executorService()); AssertExtensions.assertThrows( "Unexpected outcome when trying to map a segment name to a full metadata that cannot be cleaned.", () -> mapper1.getOrAssignStreamSegmentId(segmentName, TIMEOUT), ex -> ex instanceof TooManyActiveSegmentsException && ((TooManyActiveSegmentsException) ex).getContainerId() == exceptionCounter.get()); Assert.assertEquals("Unexpected number of attempts to map.", 2, exceptionCounter.get()); Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get()); // Now with a transaction. exceptionCounter.set(0); cleanupInvoked.set(false); AssertExtensions.assertThrows( "Unexpected outcome when trying to map a segment name to a full metadata that cannot be cleaned.", () -> mapper1.getOrAssignStreamSegmentId(transactionName, TIMEOUT), ex -> ex instanceof TooManyActiveSegmentsException && ((TooManyActiveSegmentsException) ex).getContainerId() == exceptionCounter.get()); Assert.assertEquals("Unexpected number of attempts to map.", 2, exceptionCounter.get()); Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get()); // 2. Verify the behavior when the first call fails, but the second one succeeds. exceptionCounter.set(0); cleanupInvoked.set(false); Supplier<CompletableFuture<Void>> workingCleanup = () -> { if (!cleanupInvoked.compareAndSet(false, true)) { return FutureHelpers.failedFuture(new AssertionError("Cleanup invoked multiple times.")); } setupOperationLog(context); // Setup the OperationLog to function correctly. return CompletableFuture.completedFuture(null); }; val mapper2 = new StreamSegmentMapper(context.metadata, context.operationLog, context.stateStore, workingCleanup, context.storage, executorService()); long id = mapper2.getOrAssignStreamSegmentId(segmentName, TIMEOUT).join(); Assert.assertEquals("Unexpected number of attempts to map.", 1, exceptionCounter.get()); Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get()); Assert.assertNotEquals("No valid SegmentId assigned.", ContainerMetadata.NO_STREAM_SEGMENT_ID, id); }
From source file:com.btoddb.chronicle.plunkers.HdfsPlunkerImplIT.java
@Test @Ignore("very flakey, need to work out a more stable way of testing") public void testLongRun() throws Exception { plunker.setIdleTimeout(0);// w w w.ja va 2 s. c om plunker.setRollPeriod(2); plunker.setTimeoutCheckPeriod(100); plunker.init(config); final int sleep = 200; final int maxCount = 100; // 20 seconds at 'sleep' interval should be 10 files final AtomicInteger count = new AtomicInteger(); // do this to prime HDFS FileSystem object - otherwise timing is off plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust") .withHeader("msgId", String.valueOf(count.getAndIncrement())))); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); System.out.println("start"); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { System.out.println("time = " + System.currentTimeMillis()); plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust") .withHeader("msgId", String.valueOf(count.get())))); } catch (Exception e) { e.printStackTrace(); } count.incrementAndGet(); } }, 0, sleep, TimeUnit.MILLISECONDS); while (count.get() < maxCount) { Thread.sleep(sleep / 2); } executor.shutdown(); executor.awaitTermination(60, TimeUnit.SECONDS); Thread.sleep(1500); plunker.shutdown(); Event[] events = new Event[count.get()]; for (int i = 0; i < count.get(); i++) { events[i] = new Event("the-body").withHeader("customer", "cust").withHeader("msgId", String.valueOf(i)); } File theDir = new File(String.format("%s/the/cust/path", baseDir.getPath())); assertThat(theDir, ftUtils.countWithSuffix(".tmp", 0)); assertThat(theDir, ftUtils.countWithSuffix(".avro", 10)); assertThat(theDir, ftUtils.hasEventsInDir(events)); }
From source file:org.apache.sshd.common.forward.PortForwardingLoadTest.java
@Test @SuppressWarnings("checkstyle:nestedtrydepth") public void testLocalForwardingPayload() throws Exception { final int numIterations = 100; final String payloadTmpData = "This is significantly longer Test Data. This is significantly " + "longer Test Data. This is significantly longer Test Data. This is significantly " + "longer Test Data. This is significantly longer Test Data. This is significantly " + "longer Test Data. This is significantly longer Test Data. This is significantly " + "longer Test Data. This is significantly longer Test Data. This is significantly " + "longer Test Data. "; StringBuilder sb = new StringBuilder(payloadTmpData.length() * 1000); for (int i = 0; i < 1000; i++) { sb.append(payloadTmpData);//from w w w.j ava2 s .c o m } final String payload = sb.toString(); Session session = createSession(); try (ServerSocket ss = new ServerSocket()) { ss.setReuseAddress(true); ss.bind(new InetSocketAddress((InetAddress) null, 0)); int forwardedPort = ss.getLocalPort(); int sinkPort = session.setPortForwardingL(0, TEST_LOCALHOST, forwardedPort); final AtomicInteger conCount = new AtomicInteger(0); final Semaphore iterationsSignal = new Semaphore(0); Thread tAcceptor = new Thread(getCurrentTestName() + "Acceptor") { @SuppressWarnings("synthetic-access") @Override public void run() { try { byte[] buf = new byte[8192]; log.info("Started..."); for (int i = 0; i < numIterations; ++i) { try (Socket s = ss.accept()) { conCount.incrementAndGet(); try (InputStream sockIn = s.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { while (baos.size() < payload.length()) { int l = sockIn.read(buf); if (l < 0) { break; } baos.write(buf, 0, l); } assertEquals("Mismatched received data at iteration #" + i, payload, baos.toString()); try (InputStream inputCopy = new ByteArrayInputStream(baos.toByteArray()); OutputStream sockOut = s.getOutputStream()) { while (true) { int l = sockIn.read(buf); if (l < 0) { break; } sockOut.write(buf, 0, l); } } } } log.info("Finished iteration {}", i); iterationsSignal.release(); } log.info("Done"); } catch (Exception e) { log.error("Failed to complete run loop", e); } } }; tAcceptor.start(); Thread.sleep(TimeUnit.SECONDS.toMillis(1L)); byte[] buf = new byte[8192]; byte[] bytes = payload.getBytes(StandardCharsets.UTF_8); for (int i = 0; i < numIterations; i++) { log.info("Iteration {}", i); try (Socket s = new Socket(TEST_LOCALHOST, sinkPort); OutputStream sockOut = s.getOutputStream()) { s.setSoTimeout((int) FactoryManager.DEFAULT_NIO2_MIN_WRITE_TIMEOUT); sockOut.write(bytes); sockOut.flush(); try (InputStream sockIn = s.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length)) { while (baos.size() < payload.length()) { int l = sockIn.read(buf); if (l < 0) { break; } baos.write(buf, 0, l); } assertEquals("Mismatched payload at iteration #" + i, payload, baos.toString()); } } catch (Exception e) { log.error("Error in iteration #" + i, e); } } try { assertTrue("Failed to await pending iterations=" + numIterations, iterationsSignal.tryAcquire(numIterations, numIterations, TimeUnit.SECONDS)); } finally { session.delPortForwardingL(sinkPort); } ss.close(); tAcceptor.join(TimeUnit.SECONDS.toMillis(11L)); } finally { session.disconnect(); } }
From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java
@Test public void shouldFireKeepAlive() throws Exception { final AtomicInteger keepAliveEventCounter = new AtomicInteger(); final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference(); ViewHandler testHandler = new ViewHandler(endpoint, responseRingBuffer, queue, false) { @Override/* ww w .jav a 2 s . c o m*/ public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); ctxRef.compareAndSet(null, ctx); } @Override protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) { assertEquals(1, keepAliveEventCounter.incrementAndGet()); } @Override protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) { assertEquals(2, keepAliveEventCounter.incrementAndGet()); } }; EmbeddedChannel channel = new EmbeddedChannel(testHandler); //test idle event triggers a view keepAlive request and hook is called testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT); assertEquals(1, keepAliveEventCounter.get()); assertTrue(queue.peek() instanceof ViewHandler.KeepAliveRequest); ViewHandler.KeepAliveRequest keepAliveRequest = (ViewHandler.KeepAliveRequest) queue.peek(); //test responding to the request with http response is interpreted into a KeepAliveResponse and hook is called HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channel.writeInbound(response); ViewHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable() .cast(ViewHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single(); assertEquals(2, keepAliveEventCounter.get()); assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status()); }
From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java
@Test public void modifyHealthCheckShouldPostCorrectRequest() throws CloudException, InternalException { final int portChangeTo = 8080; final AtomicInteger getCount = new AtomicInteger(0); final AtomicInteger postCount = new AtomicInteger(0); new MockUp<CloseableHttpClient>() { @Mock// w ww . j a v a 2 s. c om public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException { if ("GET".equals(request.getMethod()) && DEFINITION_URL.equals(request.getURI().toString())) { getCount.incrementAndGet(); assertGet(request, DEFINITION_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }); if (getCount.get() == 1) { DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>( createDefinitionModel("Failover", "Enabled", HC_PORT)); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else { DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>( createDefinitionModel("Failover", "Enabled", portChangeTo)); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } } else if ("POST".equals(request.getMethod()) && DEFINITIONS_URL.equals(request.getURI().toString())) { postCount.incrementAndGet(); assertPost(request, DEFINITIONS_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }, createDefinitionModel("Failover", "Enabled", portChangeTo)); DefinitionModel definitionModel = new DefinitionModel(); definitionModel.setVersion("2"); DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>( definitionModel); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else { throw new IOException("Request is not mocked"); } } }; LoadBalancerHealthCheck loadBalancerHealthCheck = loadBalancerSupport.modifyHealthCheck(LB_NAME, HealthCheckOptions.getInstance(LB_NAME, HC_DESCRIPTION, LB_NAME, null, HC_PROTOCOL, 8080, HC_PATH, 9, 9, 9, 9)); assertEquals("LoadBalancerSupport.modifyHealthCheck() post count doesn't match", 1, postCount.get()); assertLoadBalancerHealthCheck(loadBalancerHealthCheck, portChangeTo); }