Java Code Examples for com.google.common.util.concurrent.Futures#getUnchecked()

The following examples show how to use com.google.common.util.concurrent.Futures#getUnchecked() . 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: BlazeAndroidRunConfigurationRunner.java    From intellij with Apache License 2.0 7 votes vote down vote up
private static String canDebug(
    DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) {
  // If we are debugging on a device, then the app needs to be debuggable
  for (ListenableFuture<IDevice> future : deviceFutures.get()) {
    if (!future.isDone()) {
      // this is an emulator, and we assume that all emulators are debuggable
      continue;
    }
    IDevice device = Futures.getUnchecked(future);
    if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
      return AndroidBundle.message(
          "android.cannot.debug.noDebugPermissions", moduleName, device.getName());
    }
  }
  return null;
}
 
Example 2
Source File: ServedCacheIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testMalformedDirCacheMetaData() throws Exception {
  ArtifactCache cache =
      TestArtifactCaches.createDirCacheForTest(
          projectFilesystem.getRootPath(), Paths.get("test-cache"));
  Path cacheFilePath =
      DirArtifactCacheTestUtil.getPathForRuleKey(
          cache, A_FILE_RULE_KEY, Optional.of(".metadata"));
  assertThat(projectFilesystem.exists(cacheFilePath), Matchers.is(true));
  try (DataOutputStream outputStream =
      new DataOutputStream(projectFilesystem.newFileOutputStream(cacheFilePath))) {
    outputStream.writeInt(1024);
  }

  webServer = new WebServer(/* port */ 0, projectFilesystem, FakeClock.doNotCare());
  webServer.updateAndStartIfNeeded(Optional.of(dirCache));

  ArtifactCache serverBackedCache =
      createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort()));

  LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
  CacheResult cacheResult =
      Futures.getUnchecked(serverBackedCache.fetchAsync(null, A_FILE_RULE_KEY, fetchedContents));
  assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.MISS));
}
 
Example 3
Source File: ServerCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"hub", "lobby"},
        desc = "Teleport to the lobby"
)
public void hub(final CommandContext args, CommandSender sender) throws CommandException {
    if(sender instanceof ProxiedPlayer) {
        final ProxiedPlayer player = (ProxiedPlayer) sender;
        final Server server = Futures.getUnchecked(executor.submit(() -> serverTracker.byPlayer(player)));
        if(server.role() == ServerDoc.Role.LOBBY || server.role() == ServerDoc.Role.PGM) {
            // If Bukkit server is running Commons, let it handle the command
            throw new CommandBypassException();
        }

        player.connect(proxy.getServerInfo("default"));
        player.sendMessage(new ComponentBuilder("Teleporting you to the lobby").color(ChatColor.GREEN).create());
    } else {
        sender.sendMessage(new ComponentBuilder("Only players may use this command").color(ChatColor.RED).create());
    }
}
 
Example 4
Source File: SQLiteArtifactCacheTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataStoreAndFetchHit() throws IOException, SQLException {
  artifactCache = cache(Optional.empty());
  artifactCache.store(
      ArtifactInfo.builder()
          .addRuleKeys(ruleKeyA)
          .putMetadata(METADATA_KEY, contentHashA.toString())
          .putMetadata(BuildInfo.MetadataKey.RULE_KEY, ruleKeyA.toString())
          .build(),
      BorrowablePath.notBorrowablePath(emptyFile));

  assertThat(artifactCache.metadataRuleKeys(), Matchers.contains(ruleKeyA));

  CacheResult result = Futures.getUnchecked(artifactCache.fetchAsync(null, ruleKeyA, output));
  assertEquals(CacheResultType.HIT, result.getType());
  assertThat(result.getMetadata(), Matchers.hasKey(METADATA_KEY));
  assertEquals(contentHashA.toString(), result.getMetadata().get(METADATA_KEY));
  assertThat(result.getMetadata(), Matchers.hasKey(BuildInfo.MetadataKey.RULE_KEY));
  assertEquals(ruleKeyA.toString(), result.getMetadata().get(BuildInfo.MetadataKey.RULE_KEY));
  assertEquals(0, result.getArtifactSizeBytes());
}
 
Example 5
Source File: VirtualNetworkMastershipManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void balanceRoles() {
    //FIXME: More advanced logic for balancing virtual network roles.
    List<ControllerNode> nodes = clusterService.getNodes().stream()
            .filter(n -> clusterService.getState(n.id())
                    .equals(ControllerNode.State.ACTIVE))
            .collect(Collectors.toList());

    nodes.sort(Comparator.comparing(ControllerNode::id));

    //Pick a node using network Id,
    NodeId masterNode = nodes.get((int) ((networkId.id() - 1) % nodes.size())).id();

    List<CompletableFuture<Void>> setRoleFutures = Lists.newLinkedList();
    for (VirtualDevice device : manager.getVirtualDevices(networkId)) {
        setRoleFutures.add(setRole(masterNode, device.id(), MastershipRole.MASTER));
    }

    CompletableFuture<Void> balanceRolesFuture = CompletableFuture.allOf(
            setRoleFutures.toArray(new CompletableFuture[setRoleFutures.size()]));

    Futures.getUnchecked(balanceRolesFuture);
}
 
Example 6
Source File: ServedCacheIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private boolean containsKey(ArtifactCache cache, RuleKey ruleKey) throws Exception {
  Path fetchedContents = tmpDir.newFile();
  CacheResult cacheResult =
      Futures.getUnchecked(cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(fetchedContents)));
  assertThat(cacheResult.getType(), Matchers.oneOf(CacheResultType.HIT, CacheResultType.MISS));
  return cacheResult.getType().isSuccess();
}
 
Example 7
Source File: UserThreadMappedPersistableEnvelope.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
default Message toPersistableMessage() {
    FutureTask<Message> toProtoOnUserThread = new FutureTask<>(this::toProtoMessage);
    UserThread.execute(toProtoOnUserThread);
    //noinspection UnstableApiUsage
    return Futures.getUnchecked(toProtoOnUserThread);
}
 
Example 8
Source File: ServedCacheIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionDuringTheReadRetryingFail() throws Exception {
  ProjectFilesystem throwingStreamFilesystem =
      new DefaultProjectFilesystem(
          CanonicalCellName.rootCell(),
          AbsPath.of(tmpDir.getRoot()),
          new DefaultProjectFilesystemDelegate(tmpDir.getRoot()),
          DefaultProjectFilesystemFactory.getWindowsFSInstance(),
          TestProjectFilesystems.BUCK_OUT_INCLUDE_TARGET_CONFIG_HASH_FOR_TEST) {
        private int throwingStreamServedCount = 0;

        @Override
        public InputStream newFileInputStream(Path pathRelativeToProjectRoot) throws IOException {
          InputStream inputStream = super.newFileInputStream(pathRelativeToProjectRoot);
          if (throwingStreamServedCount < 3
              && pathRelativeToProjectRoot.toString().contains("outgoing_rulekey")) {
            throwingStreamServedCount++;
            return new ThrowAfterXBytesStream(inputStream, 10L);
          }
          return inputStream;
        }
      };

  webServer = new WebServer(/* port */ 0, throwingStreamFilesystem, FakeClock.doNotCare());
  webServer.updateAndStartIfNeeded(Optional.of(dirCache));

  ArtifactCache serverBackedCache =
      createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort(), 3));

  LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
  CacheResult cacheResult =
      Futures.getUnchecked(serverBackedCache.fetchAsync(null, A_FILE_RULE_KEY, fetchedContents));
  assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.ERROR));
}
 
Example 9
Source File: GcsDiffFileLister.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Traverses the sequence of diff files backwards from checkpointTime and inserts the file
 * metadata into "sequence".  Returns true if a complete sequence was discovered, false if one or
 * more files are missing.
 */
private boolean constructDiffSequence(
    Map<DateTime, ListenableFuture<GcsFileMetadata>> upperBoundTimesToMetadata,
    DateTime fromTime,
    DateTime lastTime,
    TreeMap<DateTime, GcsFileMetadata> sequence) {
  DateTime checkpointTime = lastTime;
  while (isBeforeOrAt(fromTime, checkpointTime)) {
    GcsFileMetadata metadata;
    if (upperBoundTimesToMetadata.containsKey(checkpointTime)) {
      metadata = Futures.getUnchecked(upperBoundTimesToMetadata.get(checkpointTime));
    } else {
      String filename = DIFF_FILE_PREFIX + checkpointTime;
      logger.atInfo().log("Patching GCS list; discovered file: %s", filename);
      metadata = getMetadata(filename);

      // If we hit a gap, quit.
      if (metadata == null) {
        logger.atInfo().log(
            "Gap discovered in sequence terminating at %s, missing file: %s",
            sequence.lastKey(), filename);
        logger.atInfo().log("Found sequence from %s to %s", checkpointTime, lastTime);
        return false;
      }
    }
    sequence.put(checkpointTime, metadata);
    checkpointTime = getLowerBoundTime(metadata);
  }
  logger.atInfo().log("Found sequence from %s to %s", checkpointTime, lastTime);
  return true;
}
 
Example 10
Source File: HttpArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchUrl() {
  RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
  String expectedUri = "/artifacts/key/00000000000000000000000000000000";

  argsBuilder.setFetchClient(
      withMakeRequest(
          (path, requestBuilder) -> {
            Request request = requestBuilder.url(SERVER + path).build();
            assertEquals(expectedUri, request.url().encodedPath());
            return new OkHttpResponseWrapper(
                new Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK)
                    .body(
                        createResponseBody(
                            ImmutableSet.of(ruleKey),
                            ImmutableMap.of(),
                            ByteSource.wrap(new byte[0]),
                            "data"))
                    .message("")
                    .build());
          }));
  HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
  Futures.getUnchecked(
      cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(Paths.get("output/file"))));
  cache.close();
}
 
Example 11
Source File: CharSequenceInputBuffer.java    From grappa with Apache License 2.0 5 votes vote down vote up
@Override
public String extractLine(final int lineNumber)
{
    Preconditions.checkArgument(lineNumber > 0, "line number is negative");
    final LineCounter counter = Futures.getUnchecked(lineCounter);
    final Range<Integer> range = counter.getLineRange(lineNumber);
    final int start = range.lowerEndpoint();
    int end = range.upperEndpoint();
    if (charAt(end - 1) == '\n')
        end--;
    if (charAt(end - 1) == '\r')
        end--;
    return extract(start, end);
}
 
Example 12
Source File: MultiArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void preserveErrorsFromInnerCache() {
  ErroringArtifactCache inner = new ErroringArtifactCache();
  MultiArtifactCache cache = new MultiArtifactCache(ImmutableList.of(inner));
  CacheResult result = Futures.getUnchecked(cache.fetchAsync(null, dummyRuleKey, dummyFile));
  assertThat(result.cacheMode(), Matchers.equalTo(Optional.of(ArtifactCacheMode.http)));
  assertSame(result.getType(), CacheResultType.ERROR);
  cache.close();
}
 
Example 13
Source File: HttpArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchBadChecksum() throws Exception {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
  List<Response> responseList = new ArrayList<>();
  argsBuilder.setFetchClient(
      withMakeRequest(
          (path, requestBuilder) -> {
            Request request = requestBuilder.url(SERVER + path).build();
            Response response =
                new Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK)
                    .body(
                        createResponseBody(
                            ImmutableSet.of(ruleKey),
                            ImmutableMap.of(),
                            ByteSource.wrap(new byte[0]),
                            "data"))
                    .message("")
                    .build();
            responseList.add(response);
            return new OkHttpResponseWrapper(response);
          }));
  HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
  Path output = Paths.get("output/file");
  CacheResult result =
      Futures.getUnchecked(cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(output)));
  assertEquals(CacheResultType.ERROR, result.getType());
  assertEquals(Optional.empty(), filesystem.readFileIfItExists(output));
  assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
  cache.close();
}
 
Example 14
Source File: GraphExceptionWrapper.java    From trickle with Apache License 2.0 5 votes vote down vote up
private static Object inputValueFromFuture(ListenableFuture<?> input) {
  if (input.isDone()) {
    return Futures.getUnchecked(input);
  }
  else {
    return "NOT TERMINATED FUTURE";
  }
}
 
Example 15
Source File: HttpArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchExtraPayload() throws Exception {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
  List<Response> responseList = new ArrayList<>();
  argsBuilder.setFetchClient(
      withMakeRequest(
          (path, requestBuilder) -> {
            Request request = requestBuilder.url(SERVER + path).build();
            Response response =
                new Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK)
                    .body(
                        createResponseBody(
                            ImmutableSet.of(ruleKey),
                            ImmutableMap.of(),
                            ByteSource.wrap("more data than length".getBytes(Charsets.UTF_8)),
                            "small"))
                    .message("")
                    .build();
            responseList.add(response);
            return new OkHttpResponseWrapper(response);
          }));
  HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
  Path output = Paths.get("output/file");
  CacheResult result =
      Futures.getUnchecked(cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(output)));
  assertEquals(CacheResultType.ERROR, result.getType());
  assertEquals(Optional.empty(), filesystem.readFileIfItExists(output));
  assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
  cache.close();
}
 
Example 16
Source File: SQLiteArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlinedContentStoreAndFetchHit() throws IOException, SQLException {
  artifactCache = cache(Optional.empty());
  writeInlinedArtifact(fileA);
  artifactCache.store(artifactInfoA, BorrowablePath.notBorrowablePath(fileA));

  assertThat(artifactCache.inlinedArtifactContentHashes(), Matchers.contains(contentHashA));

  CacheResult result = Futures.getUnchecked(artifactCache.fetchAsync(null, contentHashA, output));
  assertEquals(CacheResultType.HIT, result.getType());
  assertThat(result.getMetadata(), Matchers.anEmptyMap());
  assertEquals(filesystem.getFileSize(fileA), result.getArtifactSizeBytes());
  assertArrayEquals(Files.readAllBytes(fileA), Files.readAllBytes(output.get()));
}
 
Example 17
Source File: LocationCacheCleaner.java    From twill with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void forceCleanup(final long currentTime) {
  Futures.getUnchecked(scheduler.submit(() -> cleanup(currentTime)));
}
 
Example 18
Source File: ECDeviceStore.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public DeviceEvent removeDevice(DeviceId deviceId) {
    NodeId master = mastershipService.getMasterFor(deviceId);
    // if there exist a master, forward
    // if there is no master, try to become one and process
    boolean relinquishAtEnd = false;
    if (master == null) {
        final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
        if (myRole != MastershipRole.NONE) {
            relinquishAtEnd = true;
        }
        log.debug("Temporarily requesting role for {} to remove", deviceId);
        MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
        if (role == MastershipRole.MASTER) {
            master = localNodeId;
        }
    }

    if (!localNodeId.equals(master)) {
        log.debug("{} has control of {}, forwarding remove request",
                  master, deviceId);

        clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master)
                           .whenComplete((r, e) -> {
                               if (e != null) {
                                   log.error("Failed to forward {} remove request to its master", deviceId, e);
                               }
                           });
        return null;
    }

    // I have control..
    DeviceEvent event = null;
    final DeviceKey deviceKey = new DeviceKey(getPrimaryProviderId(deviceId), deviceId);
    DeviceDescription removedDeviceDescription =
            deviceDescriptions.remove(deviceKey);
    if (removedDeviceDescription != null) {
        event = purgeDeviceCache(deviceId);
    }

    if (relinquishAtEnd) {
        log.debug("Relinquishing temporary role acquired for {}", deviceId);
        mastershipService.relinquishMastership(deviceId);
    }
    return event;
}
 
Example 19
Source File: WorkThreadTrackingTask.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public T getRawResult() {
  return result.isDone() ? Futures.getUnchecked(result) : null;
}
 
Example 20
Source File: ZKDiscoveryService.java    From twill with Apache License 2.0 4 votes vote down vote up
@Override
public void cancel() {
  Futures.getUnchecked(asyncCancel());
  LOG.debug("Service unregistered: {} {}", discoverable, path);
}