com.google.common.util.concurrent.SettableFuture Java Examples

The following examples show how to use com.google.common.util.concurrent.SettableFuture. 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: FeeRequest.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public SettableFuture<Tuple2<Map<String, Long>, Map<String, Long>>> getFees(FeeProvider provider) {
    final SettableFuture<Tuple2<Map<String, Long>, Map<String, Long>>> resultFuture = SettableFuture.create();
    ListenableFuture<Tuple2<Map<String, Long>, Map<String, Long>>> future = executorService.submit(() -> {
        Thread.currentThread().setName("FeeRequest-" + provider.toString());
        return provider.getFees();
    });

    Futures.addCallback(future, new FutureCallback<Tuple2<Map<String, Long>, Map<String, Long>>>() {
        public void onSuccess(Tuple2<Map<String, Long>, Map<String, Long>> feeData) {
            log.debug("Received feeData of {}\nfrom provider {}", feeData, provider);
            resultFuture.set(feeData);
        }

        public void onFailure(@NotNull Throwable throwable) {
            resultFuture.setException(throwable);
        }
    });

    return resultFuture;
}
 
Example #2
Source File: LocalComputeResourceController.java    From pubsub with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<Client>> startClients() {
  SettableFuture<List<Client>> future = SettableFuture.create();
  executor.execute(
      () -> {
        List<Client> toReturn = new ArrayList<>();
        for (int i = 0; i < numWorkers; i++) {
          try {
            Integer port = getPort();
            runClientProcess(params.getClientType(), port);
            toReturn.add(new Client("localhost", params, executor, port));
          } catch (Exception e) {
            future.setException(e);
            return;
          }
        }

        future.set(toReturn);
      });
  return future;
}
 
Example #3
Source File: TestWorkProcessor.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 10_000)
public void testCreateFrom()
{
    SettableFuture<?> future = SettableFuture.create();
    List<ProcessState<Integer>> scenario = ImmutableList.of(
            ProcessState.yield(),
            ProcessState.ofResult(1),
            ProcessState.blocked(future),
            ProcessState.yield(),
            ProcessState.ofResult(2),
            ProcessState.finished());
    WorkProcessor<Integer> processor = processorFrom(scenario);

    // before
    assertFalse(processor.isBlocked());
    assertFalse(processor.isFinished());

    assertYields(processor);
    assertResult(processor, 1);
    assertBlocks(processor);
    assertUnblocks(processor, future);
    assertYields(processor);
    assertResult(processor, 2);
    assertFinishes(processor);
}
 
Example #4
Source File: ListingConnectorTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDocRepositoryDoc() throws Exception {
  setDefaultConfig();
  Item polledItem = new Item().setName("docId");
  SettableFuture<Item> updateFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            updateFuture.set(new Item());
            return updateFuture;
          })
      .when(mockIndexingService)
      .indexItem(polledItem, RequestMode.UNSPECIFIED);
  when(mockRepository.getDoc(polledItem))
      .thenReturn(new RepositoryDoc.Builder().setItem(polledItem).build());
  ListingConnector connector = new ListingConnector(mockRepository);
  connector.init(mockConnectorContext);
  connector.process(polledItem);
  verify(mockIndexingService).indexItem(polledItem, RequestMode.UNSPECIFIED);
}
 
Example #5
Source File: AirplaneModeAndroidTest.java    From firebase-jobdispatcher-android with Apache License 2.0 6 votes vote down vote up
private void waitForSomeNetworkToConnect() throws Exception {
  final SettableFuture<Void> future = SettableFuture.create();

  ConnectivityManager.NetworkCallback cb =
      new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
          NetworkInfo netInfo = connManager.getNetworkInfo(network);
          if (netInfo != null && netInfo.isConnected()) {
            future.set(null);
          }
        }
      };

  connManager.requestNetwork(
      new NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build(), cb);

  try {
    future.get(NETWORK_STATE_CHANGE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
  } finally {
    connManager.unregisterNetworkCallback(cb);
  }
}
 
Example #6
Source File: ServiceContext.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Clean up the internal state of this context. This will normally happen on a
 * session close
 */
public void reset() {

  // TODO clean text editor
  for (WaveContext wc : waveRegistry.values())
    wc.close();

  waveRegistry.clear();

  if (websocketClient != null) {
    websocketClient.stop(false);
    websocketClient = null;
  }

  serviceMultiplexerFuture = SettableFuture.<RemoteViewServiceMultiplexer> create();

  if (serviceSession != null) {
    serviceSession.destroy();
    serviceSession = null;
  }

}
 
Example #7
Source File: AsyncQueue.java    From presto with Apache License 2.0 6 votes vote down vote up
public synchronized ListenableFuture<?> offer(T element)
{
    requireNonNull(element);

    if (finishing && borrowerCount == 0) {
        return immediateFuture(null);
    }
    elements.add(element);
    int newSize = elements.size();
    if (newSize == 1) {
        completeAsync(executor, notEmptySignal);
        notEmptySignal = SettableFuture.create();
    }
    if (newSize >= targetQueueSize) {
        return notFullSignal;
    }
    return immediateFuture(null);
}
 
Example #8
Source File: PublishUserEventReceivedHandler.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {

    final PUBLISH publish;
    final SettableFuture<PublishStatus> statusFuture;
    if (evt instanceof PublishWithFuture) {
        publish = ((PublishWithFuture) evt);
        statusFuture = ((PublishWithFuture) evt).getFuture();
        writePublish(ctx, publish, statusFuture);
    } else if (evt instanceof PUBLISH) {
        publish = (PUBLISH) evt;
        writePublish(ctx, publish, null);
    } else {
        super.userEventTriggered(ctx, evt);
    }

}
 
Example #9
Source File: DaprClientGrpcTest.java    From java-sdk with MIT License 6 votes vote down vote up
@Test
public void invokeServiceByteRequestObjectTest() throws Exception {
  MyObject resultObj = new MyObject(1, "Value");
  SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();
  MockCallback<CommonProtos.InvokeResponse> callback =
      new MockCallback<CommonProtos.InvokeResponse>(CommonProtos.InvokeResponse.newBuilder()
          .setData(getAny(resultObj)).build());
  addCallback(settableFuture, callback, directExecutor());
  settableFuture.set(CommonProtos.InvokeResponse.newBuilder().setData(getAny(resultObj)).build());
  when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
      .thenReturn(settableFuture);
  String request = "Request";
  byte[] byteRequest = serializer.serialize(request);
  Mono<byte[]> result = adapter.invokeService(Verb.GET, "appId", "method", byteRequest, byte[].class);
  byte[] byteOutput = result.block();
  assertEquals(resultObj, serializer.deserialize(byteOutput, MyObject.class));
}
 
Example #10
Source File: ESDeleteTask.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public ESDeleteTask(UUID jobId,
                    ESDeleteNode node,
                    TransportDeleteAction transport,
                    JobContextService jobContextService) {
    super(jobId, node.executionPhaseId(), node.docKeys().size(), jobContextService);
    List<DeleteRequest> requests = new ArrayList<>(node.docKeys().size());
    List<ActionListener> listeners = new ArrayList<>(node.docKeys().size());
    for (DocKeys.DocKey docKey : node.docKeys()) {
        DeleteRequest request = new DeleteRequest(
                ESGetTask.indexName(node.tableInfo(), docKey.partitionValues()),
                Constants.DEFAULT_MAPPING_TYPE, docKey.id());
        request.routing(docKey.routing());
        if (docKey.version().isPresent()) {
            request.version(docKey.version().get());
        }
        requests.add(request);
        SettableFuture<TaskResult> result = SettableFuture.create();
        results.add(result);
        listeners.add(new DeleteResponseListener(result));
    }

    createContext("delete", requests, listeners, transport, null);
}
 
Example #11
Source File: MemoryPerUserWaveViewHandlerImpl.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onParticipantAdded(WaveletName waveletName, ParticipantId user) {
  Multimap<WaveId, WaveletId> perUserView = explicitPerUserWaveViews.getIfPresent(user);
  if (perUserView != null) {
    if (!perUserView.containsEntry(waveletName.waveId, waveletName.waveletId)) {
      perUserView.put(waveletName.waveId, waveletName.waveletId);
      if(LOG.isFineLoggable()) {
        LOG.fine("Added wavelet: " + waveletName + " to the view of user: " + user.getAddress());
        LOG.fine("View size is now: " + perUserView.size());
      }
    }
  }
  SettableFuture<Void> task = SettableFuture.create();
  task.set(null);
  return task;
}
 
Example #12
Source File: FuturesConverter.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
/** Converts an {@see ApiFuture} to a {@see ListenableFuture}. */
public static <T> ListenableFuture<T> apiFutureToListenableFuture(final ApiFuture<T> apiFuture) {
  SettableFuture<T> settableFuture = SettableFuture.create();
  ApiFutures.addCallback(
      apiFuture,
      new ApiFutureCallback<T>() {
        @Override
        public void onFailure(Throwable t) {
          settableFuture.setException(t);
        }

        @Override
        public void onSuccess(T result) {
          settableFuture.set(result);
        }
      });
  return settableFuture;
}
 
Example #13
Source File: PublishDistributorImpl.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public ListenableFuture<Void> distributeToNonSharedSubscribers(@NotNull final Map<String, SubscriberWithIdentifiers> subscribers,
                                                               @NotNull final PUBLISH publish, @NotNull final ExecutorService executorService) {

    final ImmutableList.Builder<ListenableFuture<Void>> publishResultFutureBuilder = ImmutableList.builder();

    for (final Map.Entry<String, SubscriberWithIdentifiers> entry : subscribers.entrySet()) {
        final SubscriberWithIdentifiers subscriber = entry.getValue();

        final ListenableFuture<PublishStatus> publishFuture = sendMessageToSubscriber(publish, entry.getKey(), subscriber.getQos(),
                false, subscriber.isRetainAsPublished(), subscriber.getSubscriptionIdentifier());

        final SettableFuture<Void> publishFinishedFuture = SettableFuture.create();
        publishResultFutureBuilder.add(publishFinishedFuture);
        Futures.addCallback(publishFuture, new StandardPublishCallback(entry.getKey(), publish, publishFinishedFuture), executorService);
    }

    return FutureUtils.voidFutureFromList(publishResultFutureBuilder.build());
}
 
Example #14
Source File: AsyncChannelAsserts.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<T> future(Matcher<? super T> matcher) {
  SettableFuture<T> finished = SettableFuture.create();

  fiber.execute(() -> {
    synchronized (messageLog) {
      for (T element : messageLog) {
        if (matcher.matches(element)) {
          finished.set(element);
          return;
        }
      }
    }
    waitingToMatch.put(matcher, finished);
  });

  return finished;
}
 
Example #15
Source File: FutureUtilsTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_void_future_from_list() throws Exception {
    final SettableFuture<Void> future1 = SettableFuture.create();
    final SettableFuture<Void> future2 = SettableFuture.create();

    final ImmutableList.Builder<ListenableFuture<Void>> builder = ImmutableList.builder();


    builder.add(future1).add(future2);
    final ListenableFuture<Void> resultFuture = FutureUtils.voidFutureFromList(builder.build());
    assertEquals(false, resultFuture.isDone());
    future1.set(null);
    assertEquals(false, resultFuture.isDone());
    future2.set(null);
    assertEquals(true, resultFuture.isDone());
}
 
Example #16
Source File: TestQuorumJournalManagerUnit.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteEditsOneSlow() throws Exception {
  EditLogOutputStream stm = createLogSegment();
  writeOp(stm, 1);
  stm.setReadyToFlush();
  
  // Make the first two logs respond immediately
  futureReturns(null).when(spyLoggers.get(0)).sendEdits(
      anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());
  futureReturns(null).when(spyLoggers.get(1)).sendEdits(
      anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());
  
  // And the third log not respond
  SettableFuture<Void> slowLog = SettableFuture.create();
  Mockito.doReturn(slowLog).when(spyLoggers.get(2)).sendEdits(
      anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());
  stm.flush();
  
  Mockito.verify(spyLoggers.get(0)).setCommittedTxId(1L);
}
 
Example #17
Source File: FullTraversalConnectorTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testTraverseExceptionInDeleteQueueItems() throws Exception {
  SettableFuture<Operation> result = SettableFuture.create();
  result.setException(new ExecutionException("outer", new IOException("inner")));
  doAnswer(invocation -> result).when(indexingServiceMock).deleteQueueItems(any());
  when(repositoryMock.getAllDocs(null))
      .thenReturn(
          new CheckpointCloseableIterableImpl.Builder<>(Collections.<ApiOperation>emptyList())
          .build());
  setConfig("0", DefaultAclChoices.PUBLIC);
  FullTraversalConnector connector =
      new FullTraversalConnector(repositoryMock, checkpointHandlerMock);
  connector.init(connectorContextMock);
  // No exception thrown.
  connector.traverse();
}
 
Example #18
Source File: PopupMethodResolver.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SettableFuture<String> method(List<String> methods) {
    final SettableFuture<String> future = SettableFuture.create();
    if (methods.size() == 1) {
        future.set(methods.get(0));
    } else {
        final MaterialDialog.Builder builder = UI.popup(activity, R.string.id_choose_method_to_authorize_the)
                                               .cancelable(false)
                                               .items(methods)
                                               .itemsCallbackSingleChoice(0, (dialog, v, which, text) -> {
            Log.d("RSV", "PopupMethodResolver CHOOSE callback");
            future.set(methods.get(which));
            return true;
        })
                                               .onNegative((dialog, which) -> {
            Log.d("RSV", "PopupMethodResolver CANCEL callback");
            future.set(null);
        });
        activity.runOnUiThread(() -> {
            Log.d("RSV", "PopupMethodResolver dialog show");
            builder.show();
        });
    }
    return future;
}
 
Example #19
Source File: TrickleErrorHandlingTest.java    From trickle with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotBlockOnUnterminatedInputFuture() throws Exception {
  Input<String> nonTerminating = Input.named("nonTerminating");
  Input<String> failing = Input.named("failing");

  RuntimeException expected = new RuntimeException("expected");

  SettableFuture<String> nonFuture = SettableFuture.create();
  ListenableFuture<String> failFuture = immediateFailedFuture(expected);

  Func2<String, String, String> func = new Func2<String, String, String>() {
    @Override
    public ListenableFuture<String> run(@Nullable String arg1, @Nullable String arg2) {
      return immediateFuture(arg1 + arg2);
    }
  };

  Graph<String> g = call(func).with(nonTerminating, failing);

  thrown.expect(hasAncestor(expected));

  g.bind(failing, failFuture).bind(nonTerminating, nonFuture).run().get();
}
 
Example #20
Source File: ConfigUpdaterTest.java    From consultant with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10_000)
public void verifyFolderIsIgnored() throws Exception {
	CloseableHttpResponse response = mock(CloseableHttpResponse.class);
	when(response.getFirstHeader(eq("X-Consul-Index"))).thenReturn(new BasicHeader("X-Consul-Index", "1000"));
	when(response.getStatusLine()).thenReturn(createStatus(200, "OK"));
	when(response.getEntity()).thenReturn(toJson(ImmutableMap.of("some-prefix/oauth/", "some-value",
			"some-prefix/oauth/some.key", "some-value")));

	when(http.execute(any())).thenReturn(response);

	SettableFuture<Properties> future = SettableFuture.create();
	ConfigUpdater updater = new ConfigUpdater(executor, http, null, null, id, objectMapper, null, future::set,
			"some-prefix");

	updater.run();

	Properties properties = future.get();
	assertEquals(properties.keySet(), Sets.newHashSet("some.key"));
}
 
Example #21
Source File: WebRTCWrapper.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
ListenableFuture<SessionDescription> createOffer() {
    return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
        final SettableFuture<SessionDescription> future = SettableFuture.create();
        peerConnection.createOffer(new CreateSdpObserver() {
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                future.set(sessionDescription);
            }

            @Override
            public void onCreateFailure(String s) {
                future.setException(new IllegalStateException("Unable to create offer: " + s));
            }
        }, new MediaConstraints());
        return future;
    }, MoreExecutors.directExecutor());
}
 
Example #22
Source File: MobileServiceSyncTable.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Insert an item into the local table and enqueue the operation to be
 * synchronized on context push.
 *
 * @param item the item to be inserted
 * @return A ListenableFuture that is done when the item has been inserted,
 * returning a copy of the inserted item including id.
 */
public ListenableFuture<E> insert(E item) {
    final SettableFuture<E> future = SettableFuture.create();

    final JsonObject json = mClient.getGsonBuilder().create().toJsonTree(item).getAsJsonObject();

    JsonElement idJsonObject = json.get("id");

    if (idJsonObject != null && !idJsonObject.isJsonNull()) {
        String itemId = idJsonObject.getAsString();

        ListenableFuture<JsonObject> lookUpInternalFuture = mInternalTable.lookUp(itemId);

        Futures.addCallback(lookUpInternalFuture, new FutureCallback<JsonObject>() {
            @Override
            public void onFailure(Throwable throwable) {
                future.setException(throwable);
            }

            @Override
            public void onSuccess(JsonObject result) {

                if (result != null) {
                    future.set(parseResults(result).get(0));
                    return;
                }

                insertInternal(json, future);
            }
        }, MoreExecutors.directExecutor());
    } else {
        insertInternal(json, future);
    }

    return future;
}
 
Example #23
Source File: EncoderUnitTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteMultipleByteBufs() {
  Integer payload = new Integer(1);
  ByteBuf buf1 = Unpooled.buffer();
  buf1.writeBytes(Ints.toByteArray(payload));

  ByteBuf buf2 = Unpooled.buffer();
  buf2.writeBytes(Ints.toByteArray(payload));

  Request request =
      new Request(
          UUID.fromString("6566a1c5-b0ec-47a8-8e77-b5173b78873a"), SettableFuture.create());
  Message message = new Message(request, payload);

  channel.writeOutbound(buf1);
  channel.writeOutbound(buf2);
  channel.writeOutbound(message);
  channel.runPendingTasks();

  ByteBuf encoded = (ByteBuf) channel.outboundMessages().poll();
  String expectedEncoded =
      new StringBuilder()
          .append("         +-------------------------------------------------+\n")
          .append("         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |\n")
          .append(
              "+--------+-------------------------------------------------+----------------+\n")
          .append(
              "|00000000| 36 35 36 36 61 31 63 35 2d 62 30 65 63 2d 34 37 |6566a1c5-b0ec-47|\n")
          .append(
              "|00000010| 61 38 2d 38 65 37 37 2d 62 35 31 37 33 62 37 38 |a8-8e77-b5173b78|\n")
          .append(
              "|00000020| 38 37 33 61 00 00 00 00 00 00 00 08 00 00 00 01 |873a............|\n")
          .append(
              "|00000030| 00 00 00 01                                     |....            |\n")
          .append("+--------+-------------------------------------------------+----------------+")
          .toString();

  assertEquals(
      "Expected:\n" + expectedEncoded, expectedEncoded, ByteBufUtil.prettyHexDump(encoded));
}
 
Example #24
Source File: TestIpcdRegistry.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void TestRegisterDevice_HappyPath() {
   Place place = Fixtures.createPlace();
   place.setId(UUID.randomUUID());
   expect(mockPlaceDao.findById(place.getId())).andReturn(place);

   DeviceProtocolAddress dpa = Fixtures.createProtocolAddress("IPCD");
   expect(mockIpcdDeviceDao
         .claimAndGetProtocolAddress(anyObject(com.iris.protocol.ipcd.message.model.Device.class), anyObject(UUID.class), eq(place.getId())))
         .andReturn(dpa.getRepresentation());

   final SettableFuture<PlatformMessage> future = SettableFuture.create();
   expect(mockPlatformBusClient.request(anyObject(PlatformMessage.class), anyInt())).andReturn(future);

   mockPlatformBusClient.sendEvent(anyObject(PlatformMessage.class));
   EasyMock.expectLastCall().anyTimes();

   EasyMock.replay(mockPlaceDao, mockIpcdDeviceDao, mockPlatformBusClient);

   MessageBody mb = BridgeService.RegisterDeviceRequest.builder()
         .withAttrs(
            ImmutableMap.of(
               IpcdProtocol.ATTR_SN, "123456",
               IpcdProtocol.ATTR_V1DEVICETYPE, IpcdProtocol.V1_DEVICE_TYPE_ECOWATER_SOFTENER
            )
         )
         .build();

   MessageBody result = ipcdRegistry.registerDevice(mb, place.getId().toString());
   assertNotNull(result);
   assertNotEquals("Error", result.getMessageType());
}
 
Example #25
Source File: KinesisProducerMock.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized ListenableFuture<UserRecordResult> addUserRecord(
    String stream, String partitionKey, String explicitHashKey, ByteBuffer data) {
  seqNumber.incrementAndGet();
  SettableFuture<UserRecordResult> f = SettableFuture.create();
  f.set(
      new UserRecordResult(
          new ArrayList<>(), String.valueOf(seqNumber.get()), explicitHashKey, !isFailedFlush));

  if (kinesisService.getExistedStream().equals(stream)) {
    addedRecords.add(new UserRecord(stream, partitionKey, explicitHashKey, data));
  }
  return f;
}
 
Example #26
Source File: DefaultAckMessageAcceptanceMonitor.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Override
public void received(AckMessageAckCommandV5 cmd) {
	SettableFuture<Pair<Boolean, Endpoint>> future = m_futures.remove(cmd.getHeader().getCorrelationId());
	if (future != null) {
		future.set(new Pair<Boolean, Endpoint>(cmd.isSuccess(), cmd.getNewEndpoint()));
	}
}
 
Example #27
Source File: ListingConnectorTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testTraverseIgnoreError() throws Exception {
  Properties properties = new Properties();
  properties.put(TraverseExceptionHandlerFactory.TRAVERSE_EXCEPTION_HANDLER, "ignore");
  overrideDefaultConfig(properties);
  PushItem pushItem = new PushItem();
  ApiOperation pushOperation = new PushItems.Builder().addPushItem("pushedId", pushItem).build();
  ApiOperation deleteOperation = ApiOperations.deleteItem("deletedItem");
  Collection<ApiOperation> operations =
      Arrays.asList(pushOperation, errorOperation, deleteOperation);
  TestCloseableIterable delegate = new TestCloseableIterable(operations);
  CheckpointCloseableIterable<ApiOperation> testIterable =
      new CheckpointCloseableIterableImpl.Builder<>(delegate).build();
  when(mockRepository.getIds(any())).thenReturn(testIterable);
  SettableFuture<Item> pushFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            pushFuture.set(new Item());
            return pushFuture;
          })
      .when(mockIndexingService)
      .push(eq("pushedId"), eq(pushItem));
  SettableFuture<Operation> deleteFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            deleteFuture.set(new Operation());
            return deleteFuture;
          })
      .when(mockIndexingService)
      .deleteItem("deletedItem", null, RequestMode.UNSPECIFIED);
  ListingConnector connector = new ListingConnector(mockRepository, mockCheckpointHandler);
  connector.init(mockConnectorContext);
  connector.traverse();
  InOrder inOrder = Mockito.inOrder(mockIndexingService);
  inOrder.verify(mockIndexingService).push("pushedId", pushItem);
  inOrder.verify(mockIndexingService).deleteItem("deletedItem", null, RequestMode.UNSPECIFIED);
  assertTrue(delegate.isClosed());
}
 
Example #28
Source File: ListingConnectorTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocDefaultAclOverride() throws Exception {
  Properties config = new Properties();
  config.put(DefaultAcl.DEFAULT_ACL_MODE, "override");
  config.put(DefaultAcl.DEFAULT_ACL_PUBLIC, "true");
  overrideDefaultConfig(config);
  Item polledItem = new Item().setName("PollItem");
  RepositoryDoc.Builder repositoryDoc = new Builder();
  repositoryDoc
      .setItem(
          new IndexingItemBuilder("PollItem")
              .setTitle(FieldOrValue.withValue("testItem"))
              .setAcl(
                  new Acl.Builder()
                      .setReaders(Arrays.asList(Acl.getUserPrincipal("user1")))
                      .build())
              .build())
      .build();
  SettableFuture<Operation> updateFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            updateFuture.set(new Operation().setDone(true));
            return updateFuture;
          })
      .when(mockIndexingService)
      .indexItem(any(), any());
  when(mockRepository.getDoc(polledItem)).thenReturn(repositoryDoc.build());

  ListingConnector connector = new ListingConnector(mockRepository);
  connector.init(mockConnectorContext);
  connector.process(polledItem);
  verify(mockIndexingService).indexItem(itemListCaptor.capture(), any());
  assertEquals(DOMAIN_PUBLIC_ACL, itemListCaptor.getAllValues().get(0).getAcl());
}
 
Example #29
Source File: DefaultPullEntry.java    From qmq with Apache License 2.0 5 votes vote down vote up
private ListenableFuture waitOnline() {
    synchronized (onlineSwitcher) {
        if (onlineSwitcher.isOnline()) {
            return null;
        }

        final SettableFuture<Boolean> future = SettableFuture.create();
        this.onlineFuture = future;
        return future;
    }
}
 
Example #30
Source File: BuckQueryEnvironment.java    From buck with Apache License 2.0 5 votes vote down vote up
private Optional<ListenableFuture<Unit>> discoverNewTargetsConcurrently(
    BuildTarget buildTarget,
    DependencyStack dependencyStack,
    ConcurrentHashMap<BuildTarget, ListenableFuture<Unit>> jobsCache)
    throws BuildFileParseException {
  ListenableFuture<Unit> job = jobsCache.get(buildTarget);
  if (job != null) {
    return Optional.empty();
  }
  SettableFuture<Unit> newJob = SettableFuture.create();
  if (jobsCache.putIfAbsent(buildTarget, newJob) != null) {
    return Optional.empty();
  }

  ListenableFuture<Unit> future =
      Futures.transformAsync(
          parser.getTargetNodeJobAssertCompatible(parserState, buildTarget, dependencyStack),
          targetNode -> {
            targetsToNodes.put(buildTarget, targetNode);
            checker.addTarget(buildTarget, dependencyStack);
            List<ListenableFuture<Unit>> depsFuture = new ArrayList<>();
            Set<BuildTarget> parseDeps = targetNode.getParseDeps();
            for (BuildTarget parseDep : parseDeps) {
              discoverNewTargetsConcurrently(parseDep, dependencyStack.child(parseDep), jobsCache)
                  .ifPresent(
                      depWork ->
                          depsFuture.add(
                              attachParentNodeToErrorMessage(buildTarget, parseDep, depWork)));
            }
            return Futures.transform(
                Futures.allAsList(depsFuture),
                Functions.constant(null),
                MoreExecutors.directExecutor());
          });
  newJob.setFuture(future);
  return Optional.of(newJob);
}