Search in sources :

Example 31 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project controller by opendaylight.

the class RemoteTransactionContextTest method testLimiterOnFailure.

/**
 * OperationLimiter should be correctly released when a failure, like AskTimeoutException occurs. Future reads
 * need to complete immediately with the failure and modifications should not be throttled and thrown away
 * immediately.
 */
@Test
public void testLimiterOnFailure() throws TimeoutException, InterruptedException {
    txContext.executeModification(DELETE);
    txContext.executeModification(DELETE);
    assertEquals(2, limiter.availablePermits());
    Future<Object> future = txContext.sendBatchedModifications();
    assertEquals(2, limiter.availablePermits());
    BatchedModifications msg = kit.expectMsgClass(BatchedModifications.class);
    assertEquals(2, msg.getModifications().size());
    assertEquals(1, msg.getTotalMessagesSent());
    sendReply(new Failure(new NullPointerException()));
    assertFuture(future, new OnComplete<Object>() {

        @Override
        public void onComplete(final Throwable failure, final Object success) {
            assertTrue(failure instanceof NullPointerException);
            assertEquals(4, limiter.availablePermits());
            // The transaction has failed, no throttling should occur
            txContext.executeModification(DELETE);
            assertEquals(4, limiter.availablePermits());
            // Executing a read should result in immediate failure
            final SettableFuture<Boolean> readFuture = SettableFuture.create();
            txContext.executeRead(new DataExists(), readFuture);
            assertTrue(readFuture.isDone());
            try {
                readFuture.get();
                fail("Read future did not fail");
            } catch (ExecutionException | InterruptedException e) {
                assertTrue(e.getCause() instanceof NullPointerException);
            }
        }
    });
    future = txContext.directCommit();
    msg = kit.expectMsgClass(BatchedModifications.class);
    // Modification should have been thrown away by the dropped transmit induced by executeRead()
    assertEquals(0, msg.getModifications().size());
    assertTrue(msg.isDoCommitOnReady());
    assertTrue(msg.isReady());
    assertEquals(2, msg.getTotalMessagesSent());
    sendReply(new Failure(new IllegalStateException()));
    assertFuture(future, new OnComplete<Object>() {

        @Override
        public void onComplete(final Throwable failure, final Object success) {
            assertTrue(failure instanceof IllegalStateException);
        }
    });
    kit.expectNoMsg();
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) DataExists(org.opendaylight.controller.cluster.datastore.messages.DataExists) Failure(akka.actor.Status.Failure) BatchedModifications(org.opendaylight.controller.cluster.datastore.messages.BatchedModifications) Test(org.junit.Test)

Example 32 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project java-docs-samples by GoogleCloudPlatform.

the class Recognize method streamingRecognizeFile.

/**
 * Performs streaming speech recognition on raw PCM audio data.
 *
 * @param fileName the path to a PCM audio file to transcribe.
 */
public static void streamingRecognizeFile(String fileName) throws Exception, IOException {
    Path path = Paths.get(fileName);
    byte[] data = Files.readAllBytes(path);
    // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
    try (SpeechClient speech = SpeechClient.create()) {
        // Configure request with local raw PCM audio
        RecognitionConfig recConfig = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16).setLanguageCode("en-US").setSampleRateHertz(16000).setModel("default").build();
        StreamingRecognitionConfig config = StreamingRecognitionConfig.newBuilder().setConfig(recConfig).build();
        class ResponseApiStreamingObserver<T> implements ApiStreamObserver<T> {

            private final SettableFuture<List<T>> future = SettableFuture.create();

            private final List<T> messages = new java.util.ArrayList<T>();

            @Override
            public void onNext(T message) {
                messages.add(message);
            }

            @Override
            public void onError(Throwable t) {
                future.setException(t);
            }

            @Override
            public void onCompleted() {
                future.set(messages);
            }

            // Returns the SettableFuture object to get received messages / exceptions.
            public SettableFuture<List<T>> future() {
                return future;
            }
        }
        ResponseApiStreamingObserver<StreamingRecognizeResponse> responseObserver = new ResponseApiStreamingObserver<>();
        BidiStreamingCallable<StreamingRecognizeRequest, StreamingRecognizeResponse> callable = speech.streamingRecognizeCallable();
        ApiStreamObserver<StreamingRecognizeRequest> requestObserver = callable.bidiStreamingCall(responseObserver);
        // The first request must **only** contain the audio configuration:
        requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setStreamingConfig(config).build());
        // Subsequent requests must **only** contain the audio data.
        requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setAudioContent(ByteString.copyFrom(data)).build());
        // Mark transmission as completed after sending the data.
        requestObserver.onCompleted();
        List<StreamingRecognizeResponse> responses = responseObserver.future().get();
        for (StreamingRecognizeResponse response : responses) {
            // For streaming recognize, the results list has one is_final result (if available) followed
            // by a number of in-progress results (if iterim_results is true) for subsequent utterances.
            // Just print the first result here.
            StreamingRecognitionResult result = response.getResultsList().get(0);
            // There can be several alternative transcripts for a given chunk of speech. Just use the
            // first (most likely) one here.
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            System.out.printf("Transcript : %s\n", alternative.getTranscript());
        }
    }
}
Also used : Path(java.nio.file.Path) SettableFuture(com.google.common.util.concurrent.SettableFuture) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) SpeechRecognitionAlternative(com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative) StreamingRecognitionResult(com.google.cloud.speech.v1p1beta1.StreamingRecognitionResult) StreamingRecognizeRequest(com.google.cloud.speech.v1p1beta1.StreamingRecognizeRequest) ApiStreamObserver(com.google.api.gax.rpc.ApiStreamObserver) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) RecognitionConfig(com.google.cloud.speech.v1p1beta1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1p1beta1.SpeechClient) List(java.util.List) StreamingRecognizeResponse(com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse)

Example 33 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project cdap by caskdata.

the class WorkflowTest method testWorkflow.

@Test(timeout = 120 * 1000L)
public void testWorkflow() throws Exception {
    final ApplicationWithPrograms app = AppFabricTestHelper.deployApplicationWithManager(WorkflowApp.class, TEMP_FOLDER_SUPPLIER);
    final Injector injector = AppFabricTestHelper.getInjector();
    final ProgramDescriptor programDescriptor = Iterators.filter(app.getPrograms().iterator(), input -> input.getProgramId().getType() == ProgramType.WORKFLOW).next();
    String inputPath = createInput();
    String outputPath = new File(tmpFolder.newFolder(), "output").getAbsolutePath();
    BasicArguments userArgs = new BasicArguments(ImmutableMap.of("inputPath", inputPath, "outputPath", outputPath));
    final SettableFuture<String> completion = SettableFuture.create();
    final ProgramController controller = AppFabricTestHelper.submit(app, programDescriptor.getSpecification().getClassName(), userArgs, TEMP_FOLDER_SUPPLIER);
    controller.addListener(new AbstractListener() {

        @Override
        public void init(ProgramController.State currentState, @Nullable Throwable cause) {
            LOG.info("Starting");
            long nowSecs = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            setStartAndRunning(injector.getInstance(Store.class), controller.getProgramRunId().getParent(), controller.getProgramRunId().getRun(), nowSecs);
        }

        @Override
        public void completed() {
            LOG.info("Completed");
            completion.set("Completed");
        }

        @Override
        public void error(Throwable cause) {
            LOG.info("Error", cause);
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    completion.get();
}
Also used : ProgramDescriptor(co.cask.cdap.app.program.ProgramDescriptor) ProgramController(co.cask.cdap.app.runtime.ProgramController) Supplier(com.google.common.base.Supplier) LoggerFactory(org.slf4j.LoggerFactory) SettableFuture(com.google.common.util.concurrent.SettableFuture) Iterators(com.google.common.collect.Iterators) ProgramType(co.cask.cdap.proto.ProgramType) WorkflowApp(co.cask.cdap.WorkflowApp) Store(co.cask.cdap.app.store.Store) ProgramId(co.cask.cdap.proto.id.ProgramId) MissingMapReduceWorkflowApp(co.cask.cdap.MissingMapReduceWorkflowApp) ClassRule(org.junit.ClassRule) Nullable(javax.annotation.Nullable) Threads(org.apache.twill.common.Threads) NonUniqueProgramsInWorkflowWithForkApp(co.cask.cdap.NonUniqueProgramsInWorkflowWithForkApp) AbstractListener(co.cask.cdap.internal.app.runtime.AbstractListener) Logger(org.slf4j.Logger) OneActionWorkflowApp(co.cask.cdap.OneActionWorkflowApp) ImmutableMap(com.google.common.collect.ImmutableMap) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Throwables(com.google.common.base.Throwables) Test(org.junit.Test) IOException(java.io.IOException) Category(org.junit.experimental.categories.Category) File(java.io.File) NonUniqueProgramsInWorkflowApp(co.cask.cdap.NonUniqueProgramsInWorkflowApp) ApplicationWithPrograms(co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) BasicArguments(co.cask.cdap.internal.app.runtime.BasicArguments) ScheduleAppWithMissingWorkflow(co.cask.cdap.ScheduleAppWithMissingWorkflow) XSlowTests(co.cask.cdap.test.XSlowTests) AppWithAnonymousWorkflow(co.cask.cdap.AppWithAnonymousWorkflow) AppFabricTestHelper(co.cask.cdap.internal.AppFabricTestHelper) MissingSparkWorkflowApp(co.cask.cdap.MissingSparkWorkflowApp) Assert(org.junit.Assert) WorkflowSchedulesWithSameNameApp(co.cask.cdap.WorkflowSchedulesWithSameNameApp) TemporaryFolder(org.junit.rules.TemporaryFolder) ProgramController(co.cask.cdap.app.runtime.ProgramController) ApplicationWithPrograms(co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) Injector(com.google.inject.Injector) AbstractListener(co.cask.cdap.internal.app.runtime.AbstractListener) ProgramDescriptor(co.cask.cdap.app.program.ProgramDescriptor) BasicArguments(co.cask.cdap.internal.app.runtime.BasicArguments) File(java.io.File) Test(org.junit.Test)

Example 34 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project jackrabbit-oak by apache.

the class StagingUploader method build.

/**
 * Retrieves all the files staged in the staging area and schedules them for uploads.
 * @param home the home of the repo
 * @param rootPath the parent of the cache
 */
private void build(File home, File rootPath) {
    LOG.info("Scheduling pending uploads");
    // Move any older cache pending uploads
    movePendingUploadsToStaging(home, rootPath, true);
    Iterator<File> iter = Files.fileTreeTraverser().postOrderTraversal(uploadCacheSpace).filter(new Predicate<File>() {

        @Override
        public boolean apply(File input) {
            return input.isFile();
        }
    }).iterator();
    int count = 0;
    while (iter.hasNext()) {
        File toBeSyncedFile = iter.next();
        Optional<SettableFuture<Integer>> scheduled = putOptionalDisregardingSize(toBeSyncedFile.getName(), toBeSyncedFile, true);
        if (scheduled.isPresent()) {
            count++;
        } else {
            LOG.info("File [{}] not setup for upload", toBeSyncedFile.getName());
        }
    }
    LOG.info("Scheduled [{}] pending uploads", count);
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) File(java.io.File) Predicate(com.google.common.base.Predicate)

Example 35 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project jackrabbit-oak by apache.

the class UploadStagingCacheTest method testConcurrentDifferentAdd.

/**
 * Stage different files concurrently
 * @throws Exception
 */
@Test
public void testConcurrentDifferentAdd() throws Exception {
    // Add load
    List<ListenableFuture<Integer>> futures = put(folder);
    // Add diff load
    File f2 = copyToFile(randomStream(1, 4 * 1024), folder.newFile());
    Optional<SettableFuture<Integer>> future2 = stagingCache.put(ID_PREFIX + 1, f2);
    if (future2.isPresent()) {
        futures.add(future2.get());
    }
    // start
    taskLatch.countDown();
    callbackLatch.countDown();
    assertFuture(futures, 0, 1);
    assertCacheStats(stagingCache, 0, 0, 2, 2);
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) File(java.io.File) Test(org.junit.Test)

Aggregations

SettableFuture (com.google.common.util.concurrent.SettableFuture)46 Test (org.junit.Test)25 ArrayList (java.util.ArrayList)15 List (java.util.List)15 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)14 File (java.io.File)12 IOException (java.io.IOException)10 TimeUnit (java.util.concurrent.TimeUnit)10 Futures (com.google.common.util.concurrent.Futures)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 ExecutionException (java.util.concurrent.ExecutionException)8 FutureCallback (com.google.common.util.concurrent.FutureCallback)7 Before (org.junit.Before)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 Throwables (com.google.common.base.Throwables)5 ImmutableList (com.google.common.collect.ImmutableList)5 Assert.assertSame (org.junit.Assert.assertSame)5 Mock (org.mockito.Mock)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5