Java Code Examples for java.util.concurrent.atomic.AtomicBoolean#set()

The following examples show how to use java.util.concurrent.atomic.AtomicBoolean#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FluxScanTest.java    From reactor-core with Apache License 2.0 8 votes vote down vote up
@Test
public void onNextAndCancelRaceDontPassNullToAccumulator() {
	AtomicBoolean accumulatorCheck = new AtomicBoolean(true);
	final AssertSubscriber<Integer> testSubscriber = AssertSubscriber.create();

	FluxScan.ScanSubscriber<Integer> sub =
			new FluxScan.ScanSubscriber<>(testSubscriber, (accumulated, next) -> {
				if (accumulated == null || next == null) {
					accumulatorCheck.set(false);
				}
				return next;
			});

	sub.onSubscribe(Operators.emptySubscription());

	for (int i = 0; i < 1000; i++) {
		RaceTestUtils.race(sub::cancel, () -> sub.onNext(1));

		testSubscriber.assertNoError();
		assertThat(accumulatorCheck).as("no NPE due to onNext/cancel race in round " + i).isTrue();
	}
}
 
Example 2
Source File: DeploymentTest.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemporalDirectory$vmConfig$happyPath() throws Exception {
	final AtomicBoolean valid=new AtomicBoolean(false);
	final AtomicInteger tries=new AtomicInteger(0);
	final AtomicBoolean fallback=new AtomicBoolean(false);
	final AtomicReference<File> result=new AtomicReference<File>(null);
	new MockUp<Files>() {
		@Mock
		void createParentDirs(File file) throws IOException {
			tries.incrementAndGet();
			File parentFile = file.getParentFile();
			String path = parentFile.getPath();
			valid.set(path.startsWith(dirName(System.getProperty("java.io.tmpdir"),"ldp4j","ctx","context")));
			result.set(parentFile);
		}
		@Mock
		File createTempDir() {
			fallback.set(true);
			return null;
		}
	};
	assertThat(Deployment.newInstance().withContextPath(CONTEXT).temporalDirectory(),equalTo(result.get()));
	assertThat(valid.get(),equalTo(true));
	assertThat(tries.get(),equalTo(1));
	assertThat(fallback.get(),equalTo(false));
}
 
Example 3
Source File: Futures.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a code fragment returning a CompletableFutures while a condition on the returned value is satisfied.
 *
 * @param condition Predicate that indicates whether to proceed with the loop or not.
 * @param loopBody  A Supplier that returns a CompletableFuture which represents the body of the loop. This
 *                  supplier is invoked every time the loopBody needs to execute.
 * @param executor  An Executor that is used to execute the condition and the loop support code.
 * @param <T>       Return type of the executor.
 * @return A CompletableFuture that, when completed, indicates the loop terminated without any exception. If
 * either the loopBody or condition throw/return Exceptions, these will be set as the result of this returned Future.
 */
public static <T> CompletableFuture<Void> doWhileLoop(Supplier<CompletableFuture<T>> loopBody, Predicate<T> condition, Executor executor) {
    CompletableFuture<Void> result = new CompletableFuture<>();

    // We implement the do-while loop using a regular loop, but we execute one iteration before we create the actual Loop object.
    // Since this method has slightly different arguments than loop(), we need to make one adjustment:
    // * After each iteration, we get the result and run it through 'condition' and use that to decide whether to continue.
    AtomicBoolean canContinue = new AtomicBoolean();
    Consumer<T> iterationResultHandler = ir -> canContinue.set(condition.test(ir));
    loopBody.get()
            .thenAccept(iterationResultHandler)
            .thenRunAsync(() -> {
                Loop<T> loop = new Loop<>(canContinue::get, loopBody, iterationResultHandler, result, executor);
                executor.execute(loop);
            }, executor)
            .exceptionally(ex -> {
                // Handle exceptions from the first iteration.
                result.completeExceptionally(ex);
                return null;
            });
    return result;
}
 
Example 4
Source File: YaraCompilerImplTest.java    From yara-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddRulePackageFails() throws Exception {
    final AtomicBoolean called = new AtomicBoolean();
    YaraCompilationCallback callback = new YaraCompilationCallback() {
        @Override
        public void onError(ErrorLevel errorLevel, String fileName, long lineNumber, String message) {
            called.set(true);
            LOGGER.log(Level.INFO, String.format("Compilation failed in %s at %d: %s",
                    fileName, lineNumber, message));
        }
    };

    try (YaraCompiler compiler = yara.createCompiler()) {
        compiler.setCallback(callback);
        compiler.addRulesPackage(TestUtils.getResource("rules/one-level.zip").toString(), null);
        compiler.addRulesPackage(TestUtils.getResource("rules/two-levels.zip").toString(), null);

        fail();
    }
    catch(YaraException e) {
    }

    assertTrue(called.get());
}
 
Example 5
Source File: DependencyPingerTest.java    From status with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithToggle() throws Exception {
    final AtomicBoolean toggle = new AtomicBoolean(true);
    final ControlledDependency dependency = ControlledDependency.builder().setToggle(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return toggle.get();
        }
    }).build();
    dependency.setInError(true);
    final DependencyPinger pinger = new DependencyPinger(MoreExecutors.newDirectExecutorService(), dependency, systemReporter);

    assertEquals(CheckStatus.OUTAGE, pinger.call().getStatus());
    assertEquals(1, dependency.getTimes());

    pinger.run();
    assertEquals(CheckStatus.OUTAGE, pinger.call().getStatus());
    assertEquals(2, dependency.getTimes());

    toggle.set(false);
    pinger.run();
    assertEquals(CheckStatus.OK, pinger.call().getStatus());
    assertEquals(2, dependency.getTimes());
}
 
Example 6
Source File: ConfigureDataValidatorTest.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void notSameRoleAnymoreUpdate() {
	columnMetaData.get(0).setRole("label");
	columnMetaData.get(1).setRole("label");
	validator.validate(0);
	validator.validate(1);
	final AtomicBoolean wasCalled = new AtomicBoolean();
	Observer<Set<Integer>> observer = new Observer<Set<Integer>>() {

		@Override
		public void update(Observable<Set<Integer>> observable, Set<Integer> arg) {
			assertTrue(arg.contains(1));
			assertTrue(arg.contains(0));
			wasCalled.set(true);
		}
	};
	validator.addObserver(observer, false);
	columnMetaData.get(1).setRole("label2");
	validator.validate(1);
	assertTrue(wasCalled.get());
}
 
Example 7
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBinaryWithByteArray() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();
    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
            session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
                @Override
                public void onMessage(byte[] message) {
                    session.getAsyncRemote().sendBinary(ByteBuffer.wrap(message.clone()));
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());

    deployServlet(builder);

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.get();
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example 8
Source File: RedissonTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconnection() throws IOException, InterruptedException, TimeoutException {
    RedisProcess runner = new RedisRunner()
            .appendonly(true)
            .randomDir()
            .randomPort()
            .run();

    Config config = new Config();
    config.useSingleServer().setAddress(runner.getRedisServerAddressAndPort());

    RedissonClient r = Redisson.create(config);
    
    r.getBucket("myBucket").set(1);
    assertThat(r.getBucket("myBucket").get()).isEqualTo(1);
    
    Assert.assertEquals(0, runner.stop());
    
    AtomicBoolean hasError = new AtomicBoolean();
    try {
        r.getBucket("myBucket").get();
    } catch (Exception e) {
        // skip error
        hasError.set(true);
    }

    assertThat(hasError.get()).isTrue();
    
    RedisProcess pp = new RedisRunner()
            .appendonly(true)
            .port(runner.getRedisServerPort())
            .dir(runner.getDefaultDir())
            .run();

    assertThat(r.getBucket("myBucket").get()).isEqualTo(1);

    r.shutdown();

    Assert.assertEquals(0, pp.stop());
}
 
Example 9
Source File: AtomicTest.java    From jtransc with Apache License 2.0 5 votes vote down vote up
static private void testBool() {
	System.out.println("AtomicTest.testBool:");
	AtomicBoolean atomicBoolean = new AtomicBoolean();
	System.out.println(atomicBoolean.get());
	atomicBoolean.set(true);
	System.out.println(atomicBoolean.get());
}
 
Example 10
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void comment(BaseDocument baseDocument, TokenSequence<? extends LatteTopTokenId> topTs, AtomicBoolean processedByLatte) {
    if (moveToOpeningDelimiter(topTs)) {
        int start = topTs.offset() + topTs.token().length();
        if (moveToClosingDelimiter(topTs)) {
            int end = topTs.offset() + COMMENT_DELIMITER_PART_LENGTH;
            try {
                baseDocument.insertString(start, COMMENT_DELIMITER_PART, null);
                baseDocument.insertString(end, COMMENT_DELIMITER_PART, null);
            } catch (BadLocationException ex) {
                LOGGER.log(Level.WARNING, null, ex);
            }
            processedByLatte.set(true);
        }
    }
}
 
Example 11
Source File: SpliteratorTraverseAddRemoveTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "spliteratorTraversers")
public void testQueue(String desc, Consumer<Queue<String>> c)
        throws InterruptedException {
    AtomicBoolean done = new AtomicBoolean(false);
    Queue<String> msgs = new LinkedTransferQueue<>();

    CompletableFuture<Void> traversalTask = CompletableFuture.runAsync(() -> {
        while (!done.get()) {
            // Traversal will fail if self-linked nodes of
            // LinkedTransferQueue are erroneously reported
            c.accept(msgs);
        }
    });
    CompletableFuture<Void> addAndRemoveTask = CompletableFuture.runAsync(() -> {
        while (!traversalTask.isDone()) {
            msgs.add("msg");
            msgs.remove("msg");
        }
    });

    Thread.sleep(TimeUnit.SECONDS.toMillis(1));
    done.set(true);

    addAndRemoveTask.join();
    Assert.assertTrue(traversalTask.isDone());
    traversalTask.join();
}
 
Example 12
Source File: ConfigFileControllerIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithGrayReleaseAndIncorrectCase() throws Exception {
  AtomicBoolean stop = new AtomicBoolean();
  periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace),
      stop);

  TimeUnit.MILLISECONDS.sleep(500);

  stop.set(true);

  ResponseEntity<String> response =
      restTemplate
          .getForEntity(
              "http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
              String.class,
              getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), grayClientIp);

  ResponseEntity<String> anotherResponse =
      restTemplate
          .getForEntity(
              "http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
              String.class,
              getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), nonGrayClientIp);

  Map<String, String> configs = gson.fromJson(response.getBody(), mapResponseType);
  Map<String, String> anotherConfigs = gson.fromJson(anotherResponse.getBody(), mapResponseType);

  assertEquals(HttpStatus.OK, response.getStatusCode());
  assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());

  assertEquals("override-v1", configs.get("k1"));
  assertEquals("gray-v2", configs.get("k2"));

  assertEquals("override-v1", anotherConfigs.get("k1"));
  assertEquals("default-v2", anotherConfigs.get("k2"));
}
 
Example 13
Source File: ConcurrentHeapQuickSelectSketch.java    From incubator-datasketches-java with Apache License 2.0 5 votes vote down vote up
@Override
public void endPropagation(final AtomicBoolean localPropagationInProgress, final boolean isEager) {
  //update volatile theta, uniques estimate and propagation flag
  updateVolatileTheta();
  updateEstimationSnapshot();
  if (isEager) {
    sharedPropagationInProgress_.set(false);
  }
  if (localPropagationInProgress != null) {
    localPropagationInProgress.set(false); //clear local propagation flag
  }
}
 
Example 14
Source File: PolygonBuilder.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Create a connected list of a list of coordinates
 *
 * @param points
 *            array of point
 * @param offset
 *            index of the first point
 * @param length
 *            number of points
 * @return Array of edges
 */
private static Edge[] ring(int component, boolean direction, boolean handedness,
                             Coordinate[] points, int offset, Edge[] edges, int toffset, int length, final AtomicBoolean translated) {

    boolean orientation = getOrientation(points, offset, length);

    // OGC requires shell as ccw (Right-Handedness) and holes as cw (Left-Handedness)
    // since GeoJSON doesn't specify (and doesn't need to) GEO core will assume OGC standards
    // thus if orientation is computed as cw, the logic will translate points across dateline
    // and convert to a right handed system

    // compute the bounding box and calculate range
    double[] range = range(points, offset, length);
    final double rng = range[1] - range[0];
    // translate the points if the following is true
    //   1.  shell orientation is cw and range is greater than a hemisphere (180 degrees) but not spanning 2 hemispheres
    //       (translation would result in a collapsed poly)
    //   2.  the shell of the candidate hole has been translated (to preserve the coordinate system)
    boolean incorrectOrientation = component == 0 && handedness != orientation;
    if ((incorrectOrientation && (rng > DATELINE && rng != 2 * DATELINE)) || (translated.get() && component != 0)) {
        translate(points);
        // flip the translation bit if the shell is being translated
        if (component == 0) {
            translated.set(true);
        }
        // correct the orientation post translation (ccw for shell, cw for holes)
        if (component == 0 || handedness == orientation) {
            orientation = !orientation;
        }
    }
    return concat(component, direction ^ orientation, points, offset, edges, toffset, length);
}
 
Example 15
Source File: JMXStartStopTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static void test_09() throws Exception {
    // Run an app without JMX enabled
    // attempt to start JMX using a non-available port
    // Check for valid messages in the output

    System.out.println("**** Test nine ****");

    TestAppRun s = doTest("test_09");

    try (ServerSocket ss = new ServerSocket(0)) {
        int localPort = ss.getLocalPort();
        int[] ports;
        do {
            ports = PortAllocator.allocatePorts(1);
        } while (localPort == ports[0]);

        final AtomicBoolean checks = new AtomicBoolean(false);

        int retryCntr = 1;
        do {
            final AtomicBoolean retry = new AtomicBoolean(false);

            try {
                jcmd.start(
                    line -> {
                        if (line.contains(Agent.getText(AgentConfigurationError.AGENT_EXCEPTION))) {
                            retry.set(true);
                        }
                    },
                    "jmxremote.port=" + ports[0],
                    "jmxremote.rmi.port=" + localPort,
                    "jmxremote.authenticate=false",
                    "jmxremote.ssl=false"
                );
            } catch (BindException e) {
                checks.set(true);
            }
            if (!retry.get()) {
                break;
            }
            System.out.println("Attempt " + retryCntr + " >>>");
            System.out.println("Unexpected reply from the agent. Retrying in 500ms ...");
            Thread.sleep(500);
        } while (retryCntr++ < 10);

        if (!checks.get()) {
            throw new Exception("Starting agent on port " + ports[0] + " should "
                    + "report port in use");
        }
    } finally {
        s.stop();
    }

}
 
Example 16
Source File: HttpCoder.java    From hasor with Apache License 2.0 4 votes vote down vote up
private void doInvoker(final ChannelHandlerContext ctx) throws Throwable {
    final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    HttpHandler.HttpResult httpResult = new HttpHandler.HttpResult() {
        @Override
        public void callRPC(RequestInfo requestInfo, HttpHandler.ResponseEncoder encoder) {
            Objects.requireNonNull(requestInfo);
            Objects.requireNonNull(encoder);
            if (atomicBoolean.get()) {
                throw new IllegalStateException("callRPC and finishRPC , have only one of to use");
            }
            httpRequest.setRsfRequest(requestInfo);
            HttpCoder.this.encoder = encoder;
            atomicBoolean.set(true);
        }

        @Override
        public void finishRPC() {
            if (atomicBoolean.get()) {
                throw new IllegalStateException("callRPC and finishRPC , have only one of to use");
            }
            atomicBoolean.set(true);
        }
    };
    this.httpHandler.receivedRequest(this.httpRequest, this.httpResponse, httpResult);
    if (!atomicBoolean.get()) {
        if (this.httpResponse.getStatus() == 0) {
            this.httpResponse.sendError(ProtocolStatus.InvokeError, "the server didn't respond");
        }
        this.write(ctx, this.httpResponse.getHttpResponse(), null);
        return;
    }
    //
    // .引发fireChannelRead或者响应response
    // .已经做出 response 回应,不需要在处理RequestInfo。
    if (this.httpResponse.isCommitted()) {
        this.write(ctx, this.httpResponse.getHttpResponse(), null);
        return;
    }
    // .需要解析 Request,启动一个定时任务,防止任务执行时间过长导致资源无法释放。
    RequestInfo rsfRequest = this.httpRequest.getRsfRequest();
    if (rsfRequest != null) {
        this.rsfContext.getEnvironment().atTime(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                if (ctx.channel().isActive()) {
                    exceptionCaught(ctx, new RsfException(ProtocolStatus.Timeout, "request timeout."));
                }
            }
        }, this.rsfContext.getEnvironment().getSettings().getRequestTimeout());
        ctx.fireChannelRead(rsfRequest);
        return;
    }
    //
    // .没有解析到 request,直接响应结束
    ResponseInfo info = ProtocolUtils.buildResponseStatus(//
            this.rsfContext.getEnvironment(), 0, ProtocolStatus.ProtocolError, "request has no invoker.");
    this.write(ctx, info, null);
}
 
Example 17
Source File: ShootLogicCameraTest.java    From canon-sdk-java with MIT License 4 votes vote down vote up
@Disabled("Only run manually")
    @Test
    void testShoot() throws InterruptedException {
        log.warn("Camera: {} , {}, {}, {}", camera, camera.getPointer(), cameraRef, cameraRef.getPointer());
        final EdsdkLibrary.EdsObjectEventHandler eventHandler = (inEvent, inRef, inContext) -> {
            log.warn("event {}, {}, {}", EdsObjectEvent.ofValue(inEvent.intValue()), inRef, inRef.getPointer());
            CanonFactory.edsdkLibrary().EdsDownloadCancel(new EdsDirectoryItemRef(inRef.getPointer()));
            return new NativeLong(0);
        };
        TestShortcutUtil.registerObjectEventHandler(cameraRef, eventHandler);

        CanonFactory.propertySetLogic().setPropertyData(cameraRef, EdsPropertyID.kEdsPropID_SaveTo, EdsSaveTo.kEdsSaveTo_Host);

        final AtomicBoolean init = new AtomicBoolean(false);
        for (int i = 0; i < 2; i++) {
            CanonFactory.cameraLogic().setCapacity(cameraRef);

            final EdsdkError error = toEdsdkError(CanonFactory.edsdkLibrary().EdsSendCommand(cameraRef, new NativeLong(EdsCameraCommand.kEdsCameraCommand_TakePicture.value()), new NativeLong(0)));

            log.warn("Error: {}", error);

            getEvents();
            // if too quick, camera will return error of busy
            Thread.sleep(800);
        }

        for (int i = 0; i < 50; i++) {
            CanonFactory.cameraLogic().setCapacity(cameraRef);
            final Thread run_in = new Thread(() -> {
                if (!init.get()) {
                    init.set(true);
                    Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
                }
                log.warn("Run in");
                CanonFactory.edsdkLibrary().EdsSendCommand(cameraRef, new NativeLong(EdsCameraCommand.kEdsCameraCommand_PressShutterButton.value()), new NativeLong(EdsdkLibrary.EdsShutterButton.kEdsCameraCommand_ShutterButton_Completely));
                log.warn("Middle Run in");
                CanonFactory.edsdkLibrary().EdsSendCommand(cameraRef, new NativeLong(EdsCameraCommand.kEdsCameraCommand_PressShutterButton.value()), new NativeLong(EdsdkLibrary.EdsShutterButton.kEdsCameraCommand_ShutterButton_OFF));
                Ole32.INSTANCE.CoUninitialize();
                log.warn("End Run in");
            });
            run_in.setDaemon(true);
            run_in.start();
//        run_in.join();

            final Thread run_in2 = new Thread(() -> {
                Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
                log.warn("Run in 2");
                getEvents();
                getEvents();
                log.warn("end Run in 2");
                Ole32.INSTANCE.CoUninitialize();
            });
            run_in2.setDaemon(true);
            run_in2.start();

            Thread.sleep(10000);
            log.warn("End sleep");

            // only here I shoot from threads will happen... why...
            getEvents();

            Thread.sleep(1000);

            CanonFactory.edsdkLibrary().EdsSendCommand(cameraRef, new NativeLong(EdsCameraCommand.kEdsCameraCommand_PressShutterButton.value()), new NativeLong(EdsdkLibrary.EdsShutterButton.kEdsCameraCommand_ShutterButton_Completely_NonAF));
            CanonFactory.edsdkLibrary().EdsSendCommand(cameraRef, new NativeLong(EdsCameraCommand.kEdsCameraCommand_PressShutterButton.value()), new NativeLong(EdsdkLibrary.EdsShutterButton.kEdsCameraCommand_ShutterButton_OFF));

            getEvents();
            Thread.sleep(1000);

            CanonFactory.edsdkLibrary().EdsSendCommand(cameraRef, new NativeLong(EdsCameraCommand.kEdsCameraCommand_TakePicture.value()), new NativeLong(0));

            getEvents();
            Thread.sleep(2000);
        }
    }
 
Example 18
Source File: SingleToCompletionStageTest.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private static Runnable trueJdkForkJoinThread(AtomicBoolean ref) {
    return () -> {
        verifyInJdkForkJoinThread();
        ref.set(true);
    };
}
 
Example 19
Source File: SettingsProviderTest.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
private void setSettingAndAssertSuccessfulChange(Runnable setCommand, final int type,
        final String name, final String value, final int userId) throws Exception {
    ContentResolver contentResolver = getContext().getContentResolver();

    final Uri settingUri = getBaseUriForType(type);

    final AtomicBoolean success = new AtomicBoolean();

    ContentObserver contentObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
        public void onChange(boolean selfChange, Uri changeUri, int changeId) {
            Log.i(LOG_TAG, "onChange(" + selfChange + ", " + changeUri + ", " + changeId + ")");
            assertEquals("Wrong change Uri", changeUri, settingUri);
            assertEquals("Wrong user id", userId, changeId);
            String changeValue = getStringViaFrontEndApiSetting(type, name, userId);
            assertEquals("Wrong setting value", value, changeValue);

            success.set(true);

            synchronized (mLock) {
                mLock.notifyAll();
            }
        }
    };

    contentResolver.registerContentObserver(settingUri, false, contentObserver, userId);

    try {
        setCommand.run();

        final long startTimeMillis = SystemClock.uptimeMillis();
        synchronized (mLock) {
            if (success.get()) {
                return;
            }
            final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
            if (elapsedTimeMillis > WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS) {
                fail("Could not change setting for "
                        + WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS + " ms");
            }
            final long remainingTimeMillis = WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS
                    - elapsedTimeMillis;
            try {
                mLock.wait(remainingTimeMillis);
            } catch (InterruptedException ie) {
                /* ignore */
            }
        }
    } finally {
        contentResolver.unregisterContentObserver(contentObserver);
    }
}
 
Example 20
Source File: NonBlockingRouterTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Response handling related tests for all operation managers.
 */
@Test
public void testResponseHandling() throws Exception {
  Properties props = getNonBlockingRouterProperties("DC1");
  VerifiableProperties verifiableProperties = new VerifiableProperties((props));
  setOperationParams();
  final List<ReplicaId> failedReplicaIds = new ArrayList<>();
  final AtomicInteger successfulResponseCount = new AtomicInteger(0);
  final AtomicBoolean invalidResponse = new AtomicBoolean(false);
  ResponseHandler mockResponseHandler = new ResponseHandler(mockClusterMap) {
    @Override
    public void onEvent(ReplicaId replicaId, Object e) {
      if (e instanceof ServerErrorCode) {
        if (e == ServerErrorCode.No_Error) {
          successfulResponseCount.incrementAndGet();
        } else {
          invalidResponse.set(true);
        }
      } else {
        failedReplicaIds.add(replicaId);
      }
    }
  };

  // Instantiate a router just to put a blob successfully.
  MockServerLayout mockServerLayout = new MockServerLayout(mockClusterMap);
  setRouter(props, mockServerLayout, new LoggingNotificationSystem());
  setOperationParams();

  // More extensive test for puts present elsewhere - these statements are here just to exercise the flow within the
  // NonBlockingRouter class, and to ensure that operations submitted to a router eventually completes.
  String blobIdStr =
      router.putBlob(putBlobProperties, putUserMetadata, putChannel, new PutBlobOptionsBuilder().build()).get();
  BlobId blobId = RouterUtils.getBlobIdFromString(blobIdStr, mockClusterMap);
  router.close();
  for (MockServer mockServer : mockServerLayout.getMockServers()) {
    mockServer.setServerErrorForAllRequests(ServerErrorCode.No_Error);
  }

  SocketNetworkClient networkClient =
      new MockNetworkClientFactory(verifiableProperties, mockSelectorState, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL,
          CHECKOUT_TIMEOUT_MS, mockServerLayout, mockTime).getNetworkClient();
  cryptoJobHandler = new CryptoJobHandler(CryptoJobHandlerTest.DEFAULT_THREAD_COUNT);
  KeyManagementService localKMS = new MockKeyManagementService(new KMSConfig(verifiableProperties), singleKeyForKMS);
  putManager = new PutManager(mockClusterMap, mockResponseHandler, new LoggingNotificationSystem(),
      new RouterConfig(verifiableProperties), new NonBlockingRouterMetrics(mockClusterMap, null),
      new RouterCallback(networkClient, new ArrayList<>()), "0", localKMS, cryptoService, cryptoJobHandler,
      accountService, mockTime, MockClusterMap.DEFAULT_PARTITION_CLASS);
  OperationHelper opHelper = new OperationHelper(OperationType.PUT);
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, null, successfulResponseCount,
      invalidResponse, -1);
  // Test that if a failed response comes before the operation is completed, failure detector is notified.
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, null, successfulResponseCount,
      invalidResponse, 0);
  // Test that if a failed response comes after the operation is completed, failure detector is notified.
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, null, successfulResponseCount,
      invalidResponse, PUT_REQUEST_PARALLELISM - 1);
  testNoResponseNoNotification(opHelper, failedReplicaIds, null, successfulResponseCount, invalidResponse);
  testResponseDeserializationError(opHelper, networkClient, null);

  opHelper = new OperationHelper(OperationType.GET);
  getManager = new GetManager(mockClusterMap, mockResponseHandler, new RouterConfig(verifiableProperties),
      new NonBlockingRouterMetrics(mockClusterMap, null),
      new RouterCallback(networkClient, new ArrayList<BackgroundDeleteRequest>()), localKMS, cryptoService,
      cryptoJobHandler, mockTime);
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, blobId, successfulResponseCount,
      invalidResponse, -1);
  // Test that if a failed response comes before the operation is completed, failure detector is notified.
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, blobId, successfulResponseCount,
      invalidResponse, 0);
  // Test that if a failed response comes after the operation is completed, failure detector is notified.
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, blobId, successfulResponseCount,
      invalidResponse, GET_REQUEST_PARALLELISM - 1);
  testNoResponseNoNotification(opHelper, failedReplicaIds, blobId, successfulResponseCount, invalidResponse);
  testResponseDeserializationError(opHelper, networkClient, blobId);

  opHelper = new OperationHelper(OperationType.DELETE);
  deleteManager =
      new DeleteManager(mockClusterMap, mockResponseHandler, accountService, new LoggingNotificationSystem(),
          new RouterConfig(verifiableProperties), new NonBlockingRouterMetrics(mockClusterMap, null),
          new RouterCallback(null, new ArrayList<BackgroundDeleteRequest>()), mockTime);
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, blobId, successfulResponseCount,
      invalidResponse, -1);
  // Test that if a failed response comes before the operation is completed, failure detector is notified.
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, blobId, successfulResponseCount,
      invalidResponse, 0);
  // Test that if a failed response comes after the operation is completed, failure detector is notified.
  testFailureDetectorNotification(opHelper, networkClient, failedReplicaIds, blobId, successfulResponseCount,
      invalidResponse, DELETE_REQUEST_PARALLELISM - 1);
  testNoResponseNoNotification(opHelper, failedReplicaIds, blobId, successfulResponseCount, invalidResponse);
  testResponseDeserializationError(opHelper, networkClient, blobId);
  putManager.close();
  getManager.close();
  deleteManager.close();
}