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();
}
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());
}
}
}
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();
}
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);
}
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);
}
Aggregations