@Override
 public ListenableFuture<Boolean> consumeAsync() {
   // TODO make this actually asynch
   final SettableFuture<Boolean> result = SettableFuture.create();
   try {
     consume();
     result.set(true);
   } catch (final Exception e) {
     LOGGER.warn("Got exception consuming RDF stream", e);
     result.setException(e);
     result.set(false);
   }
   return result;
 }
Example #2
0
 public boolean isFinished() {
   boolean finished = split.isFinished();
   if (finished) {
     finishedFuture.set(null);
   }
   return finished || destroyed.get();
 }
Example #3
0
  private void doWalk(
      Path path, FileStatusCallback callback, AtomicLong taskCount, SettableFuture<Void> future) {
    try (SetThreadName ignored = new SetThreadName("HiveHdfsWalker")) {
      RemoteIterator<LocatedFileStatus> iterator = getLocatedFileStatusRemoteIterator(path);

      while (iterator.hasNext()) {
        LocatedFileStatus status = getLocatedFileStatus(iterator);

        // ignore hidden files. Hive ignores files starting with _ and . as well.
        String fileName = status.getPath().getName();
        if (fileName.startsWith("_") || fileName.startsWith(".")) {
          continue;
        }
        if (isDirectory(status)) {
          recursiveWalk(status.getPath(), callback, taskCount, future);
        } else {
          callback.process(status, status.getBlockLocations());
        }
        if (future.isDone()) {
          return;
        }
      }
    } catch (FileNotFoundException e) {
      future.setException(new FileNotFoundException("Partition location does not exist: " + path));
    } catch (Throwable t) {
      future.setException(t);
    } finally {
      if (taskCount.decrementAndGet() == 0) {
        future.set(null);
      }
    }
  }
Example #4
0
  /**
   * Fences a ledger. From this point on, clients will be unable to write to this ledger. Only
   * recoveryAddEntry will be able to add entries to the ledger. This method is idempotent. Once a
   * ledger is fenced, it can never be unfenced. Fencing a fenced ledger has no effect.
   */
  public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey)
      throws IOException, BookieException {
    LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey);
    boolean success;
    synchronized (handle) {
      success = handle.setFenced();
    }
    if (success) {
      // fenced first time, we should add the key to journal ensure we can rebuild
      ByteBuffer bb = ByteBuffer.allocate(8 + 8);
      bb.putLong(ledgerId);
      bb.putLong(METAENTRY_ID_FENCE_KEY);
      bb.flip();

      FutureWriteCallback fwc = new FutureWriteCallback();
      LOG.debug("record fenced state for ledger {} in journal.", ledgerId);
      journal.logAddEntry(bb, fwc, null);
      return fwc.getResult();
    } else {
      // already fenced
      SettableFuture<Boolean> successFuture = SettableFuture.create();
      successFuture.set(true);
      return successFuture;
    }
  }
Example #5
0
  @Test
  public void successMonitor() throws Exception {
    ProducerToken token = ProducerToken.create(SimpleProducerModule_SettableFutureStrFactory.class);

    SettableFuture<String> strFuture = SettableFuture.create();
    SettableFuture<SettableFuture<String>> strFutureFuture = SettableFuture.create();
    Producer<SettableFuture<String>> strFutureProducer = producerOfFuture(strFutureFuture);
    Producer<String> producer =
        new SimpleProducerModule_SettableFutureStrFactory(
            executorProvider, componentMonitorProvider, strFutureProducer);
    assertThat(producer.get().isDone()).isFalse();

    InOrder order = inOrder(componentMonitor, monitor);
    order.verify(componentMonitor).producerMonitorFor(token);

    strFutureFuture.set(strFuture);
    order.verify(monitor).methodStarting();
    order.verify(monitor).methodFinished();
    assertThat(producer.get().isDone()).isFalse();

    strFuture.set("monkey");
    assertThat(producer.get().get()).isEqualTo("monkey");
    order.verify(monitor).succeeded("monkey");

    order.verifyNoMoreInteractions();
  }
  @Test
  public void testFireOnceMajoritySuccess() {

    SettableFuture<Boolean> f1 = SettableFuture.create();
    SettableFuture<Boolean> f2 = SettableFuture.create();
    SettableFuture<Boolean> f3 = SettableFuture.create();

    List<SettableFuture<Boolean>> responses = Lists.newArrayList(f1, f2, f3);

    ListenableFuture<Boolean> collector = majorityResponse(responses, Identity);

    f1.set(Boolean.TRUE);
    assertFalse(collector.isDone());

    f2.set(Boolean.TRUE);
    assertTrue(collector.isDone());

    assertTrue(Futures.getUnchecked(collector));
  }
Example #7
0
    @Override
    public void writeComplete(
        int rc, long ledgerId, long entryId, BookieSocketAddress addr, Object ctx) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Finished writing entry {} @ ledger {} for {} : {}",
            new Object[] {entryId, ledgerId, addr, rc});
      }

      result.set(0 == rc);
    }
Example #8
0
 @Test
 public void singleArgMethod() throws Exception {
   SettableFuture<Integer> intFuture = SettableFuture.create();
   Producer<Integer> intProducer = producerOfFuture(intFuture);
   Producer<String> producer =
       new SimpleProducerModule_StrWithArgFactory(
           executorProvider, componentMonitorProvider, intProducer);
   assertThat(producer.get().isDone()).isFalse();
   intFuture.set(42);
   assertThat(producer.get().get()).isEqualTo("str with arg");
 }
 @Override
 protected void processMessage(Message m) throws Exception {
   if (m instanceof Ping) {
     SettableFuture<Void> future = mapPingFutures.get(((Ping) m).getNonce());
     if (future != null) {
       future.set(null);
       return;
     }
   }
   if (m instanceof BloomFilter) {
     lastReceivedFilter = (BloomFilter) m;
   }
   inboundMessages.offer(m);
 }
 @Override
 public void featureEvent(FeatureEvent featureEvent) {
   String feature = featureEvent.getFeature().getId();
   InstallFuture installFutureWrapper = futures.getIfPresent(feature);
   if (installFutureWrapper == null) {
     return;
   }
   switch (featureEvent.getType()) {
     case FeatureInstalled:
       SettableFuture<Boolean> future = installFutureWrapper.future;
       if (future != null) {
         futures.invalidate(feature);
         future.set(installFutureWrapper.install);
       }
       break;
     case FeatureUninstalled:
       future = installFutureWrapper.future;
       if (future != null) {
         futures.invalidate(feature);
         future.set(!installFutureWrapper.install);
       }
       break;
   }
 }
 @Override
 public void onRemoval(
     RemovalNotification<String, InstallFuture> removalNotification) {
   switch (removalNotification.getCause()) {
     case EXPLICIT:
       break;
     case REPLACED:
     case COLLECTED:
     case EXPIRED:
     case SIZE:
       SettableFuture<Boolean> value = removalNotification.getValue().future;
       if (value != null) { // May have been GCed
         value.set(false);
       }
       break;
   }
 }
Example #12
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public void processResult(JsonNode response) {
    log.debug("Handle result");
    String requestId = response.get("id").asText();
    SettableFuture sf = requestResult.get(requestId);
    if (sf == null) {
      log.debug("No such future to process");
      return;
    }
    String methodName = requestMethod.get(requestId);

    Object result;
    result = FromJsonUtil.jsonResultParser(response, methodName);

    sf.set(result);
    return;
  }
  static void pingBeforeActivate(
      final AsyncCommand<?, ?, ?> cmd,
      final SettableFuture<Boolean> initializedFuture,
      final ChannelHandlerContext ctx,
      final List<ChannelHandler> handlers)
      throws Exception {
    cmd.handle(
        (o, throwable) -> {
          if (throwable == null) {
            initializedFuture.set(true);
            ctx.fireChannelActive();
          } else {
            initializedFuture.setException(throwable);
          }
          return null;
        });

    ctx.channel().writeAndFlush(cmd);
  }
  @Test
  public void testFireOnceMajorityFailed() {

    SettableFuture<Boolean> f1 = SettableFuture.create();
    SettableFuture<Boolean> f2 = SettableFuture.create();
    SettableFuture<Boolean> f3 = SettableFuture.create();
    ListenableFuture<Boolean> f4 = Futures.immediateFuture(Boolean.TRUE);

    List<ListenableFuture<Boolean>> responses = Lists.newArrayList(f1, f2, f3, f4);

    ListenableFuture<Boolean> collector = majorityResponse(responses, Identity);

    f1.setException(new Exception());
    assertFalse(collector.isDone());

    f3.set(Boolean.TRUE);
    assertFalse(collector.isDone());

    f2.setException(new Exception());
    assertTrue(collector.isDone());

    assertFalse(Futures.getUnchecked(collector));
  }
Example #15
0
  public synchronized void free(QueryId queryId, long bytes) {
    checkArgument(bytes >= 0, "bytes is negative");
    checkArgument(freeBytes + bytes <= maxBytes, "tried to free more memory than is reserved");
    if (bytes == 0) {
      // Freeing zero bytes is a no-op
      return;
    }

    Long queryReservation = queryMemoryReservations.get(queryId);
    requireNonNull(queryReservation, "queryReservation is null");
    checkArgument(
        queryReservation - bytes >= 0, "tried to free more memory than is reserved by query");
    queryReservation -= bytes;
    if (queryReservation == 0) {
      queryMemoryReservations.remove(queryId);
    } else {
      queryMemoryReservations.put(queryId, queryReservation);
    }
    freeBytes += bytes;
    if (freeBytes > 0 && future != null) {
      future.set(null);
      future = null;
    }
  }
Example #16
0
  @Test
  public void testCancel() throws Exception {
    HttpClient httpClient = EasyMock.createStrictMock(HttpClient.class);

    Capture<Request> capturedRequest = EasyMock.newCapture();
    ListenableFuture<Object> cancelledFuture = Futures.immediateCancelledFuture();
    SettableFuture<Object> cancellationFuture = SettableFuture.create();

    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(cancelledFuture)
        .once();

    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(cancellationFuture)
        .once();

    EasyMock.replay(httpClient);

    final ServerSelector serverSelector =
        new ServerSelector(
            new DataSegment(
                "test",
                new Interval("2013-01-01/2013-01-02"),
                new DateTime("2013-01-01").toString(),
                Maps.<String, Object>newHashMap(),
                Lists.<String>newArrayList(),
                Lists.<String>newArrayList(),
                NoneShardSpec.instance(),
                0,
                0L),
            new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()));

    DirectDruidClient client1 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            "foo",
            new NoopServiceEmitter());

    QueryableDruidServer queryableDruidServer1 =
        new QueryableDruidServer(
            new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client1);
    serverSelector.addServerAndUpdateSegment(queryableDruidServer1, serverSelector.getSegment());

    TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build();
    HashMap<String, List> context = Maps.newHashMap();
    cancellationFuture.set(
        new StatusResponseHolder(HttpResponseStatus.OK, new StringBuilder("cancelled")));
    Sequence results = client1.run(query, context);
    Assert.assertEquals(HttpMethod.DELETE, capturedRequest.getValue().getMethod());
    Assert.assertEquals(0, client1.getNumOpenConnections());

    QueryInterruptedException exception = null;
    try {
      Sequences.toList(results, Lists.newArrayList());
    } catch (QueryInterruptedException e) {
      exception = e;
    }
    Assert.assertNotNull(exception);

    EasyMock.verify(httpClient);
  }
  private void finishCanCommit(final SettableFuture<Boolean> returnFuture) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Tx {} finishCanCommit", transactionId);
    }

    // For empty transactions return immediately
    if (cohorts.size() == 0) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Tx {}: canCommit returning result: {}", transactionId, true);
      }
      returnFuture.set(Boolean.TRUE);
      return;
    }

    final Object message = new CanCommitTransaction(transactionId).toSerializable();

    final Iterator<ActorSelection> iterator = cohorts.iterator();

    final OnComplete<Object> onComplete =
        new OnComplete<Object>() {
          @Override
          public void onComplete(Throwable failure, Object response) throws Throwable {
            if (failure != null) {
              if (LOG.isDebugEnabled()) {
                LOG.debug("Tx {}: a canCommit cohort Future failed: {}", transactionId, failure);
              }
              returnFuture.setException(failure);
              return;
            }

            boolean result = true;
            if (response.getClass().equals(CanCommitTransactionReply.SERIALIZABLE_CLASS)) {
              CanCommitTransactionReply reply =
                  CanCommitTransactionReply.fromSerializable(response);
              if (!reply.getCanCommit()) {
                result = false;
              }
            } else {
              LOG.error("Unexpected response type {}", response.getClass());
              returnFuture.setException(
                  new IllegalArgumentException(
                      String.format("Unexpected response type %s", response.getClass())));
              return;
            }

            if (iterator.hasNext() && result) {
              Future<Object> future =
                  actorContext.executeOperationAsync(
                      iterator.next(),
                      message,
                      actorContext.getTransactionCommitOperationTimeout());
              future.onComplete(this, actorContext.getClientDispatcher());
            } else {
              if (LOG.isDebugEnabled()) {
                LOG.debug("Tx {}: canCommit returning result: {}", transactionId, result);
              }
              returnFuture.set(Boolean.valueOf(result));
            }
          }
        };

    Future<Object> future =
        actorContext.executeOperationAsync(
            iterator.next(), message, actorContext.getTransactionCommitOperationTimeout());
    future.onComplete(onComplete, actorContext.getClientDispatcher());
  }
Example #18
0
 /** Sets the result. */
 public boolean set(ResponseT value) {
   return settableFuture.set(value);
 }
Example #19
0
 private synchronized void notifyBlockedCallers() {
   for (SettableFuture<?> blockedCaller : blockedCallers) {
     blockedCaller.set(null);
   }
   blockedCallers.clear();
 }
  @Override
  public int execute(ExecutionContext context) throws InterruptedException {

    final String bundleID;
    try {
      bundleID =
          AppleInfoPlistParsing.getBundleIdFromPlistStream(
                  filesystem.getInputStreamForRelativePath(infoPlist))
              .get();
    } catch (IOException e) {
      throw new HumanReadableException("Unable to get bundle ID from info.plist: " + infoPlist);
    }

    final Optional<ImmutableMap<String, NSObject>> entitlements;
    final String prefix;
    if (entitlementsPlist.isPresent()) {
      try {
        NSDictionary entitlementsPlistDict =
            (NSDictionary) PropertyListParser.parse(entitlementsPlist.get().toFile());
        entitlements = Optional.of(ImmutableMap.copyOf(entitlementsPlistDict.getHashMap()));
        prefix = ProvisioningProfileMetadata.prefixFromEntitlements(entitlements.get());
      } catch (IOException e) {
        throw new HumanReadableException(
            "Unable to find entitlement .plist: " + entitlementsPlist.get());
      } catch (Exception e) {
        throw new HumanReadableException(
            "Malformed entitlement .plist: " + entitlementsPlist.get());
      }
    } else {
      entitlements = ProvisioningProfileStore.MATCH_ANY_ENTITLEMENT;
      prefix = "*";
    }

    Optional<ProvisioningProfileMetadata> bestProfile =
        provisioningProfileUUID.isPresent()
            ? provisioningProfileStore.getProvisioningProfileByUUID(provisioningProfileUUID.get())
            : provisioningProfileStore.getBestProvisioningProfile(bundleID, entitlements);

    if (!bestProfile.isPresent()) {
      throw new HumanReadableException(
          "No valid non-expired provisioning profiles match for " + prefix + "." + bundleID);
    }

    selectedProvisioningProfileFuture.set(bestProfile.get());
    Path provisioningProfileSource = bestProfile.get().getProfilePath();

    // Copy the actual .mobileprovision.
    try {
      filesystem.copy(
          provisioningProfileSource, provisioningProfileDestination, CopySourceMode.FILE);
    } catch (IOException e) {
      context.logError(e, "Failed when trying to copy: %s", getDescription(context));
      return 1;
    }

    // Merge tne entitlements with the profile, and write out.
    if (entitlementsPlist.isPresent()) {
      return (new PlistProcessStep(
              filesystem,
              entitlementsPlist.get(),
              signingEntitlementsTempPath,
              bestProfile.get().getEntitlements(),
              ImmutableMap.<String, NSObject>of(),
              PlistProcessStep.OutputFormat.XML))
          .execute(context);
    } else {
      // No entitlements.plist explicitly specified; write out the minimal entitlements needed.
      String appID = bestProfile.get().getAppID().getFirst() + "." + bundleID;
      NSDictionary entitlementsPlist = new NSDictionary();
      entitlementsPlist.putAll(bestProfile.get().getEntitlements());
      entitlementsPlist.put(APPLICATION_IDENTIFIER, appID);
      entitlementsPlist.put(KEYCHAIN_ACCESS_GROUPS, new String[] {appID});
      return (new WriteFileStep(
              filesystem,
              entitlementsPlist.toXMLPropertyList(),
              signingEntitlementsTempPath,
              /* executable */ false))
          .execute(context);
    }
  }
Example #21
0
 void setChannelSet(ChannelSet channelSet) {
   boolean wasSet = channelSetFuture.set(checkNotNull(channelSet, "channelSet is null"));
   checkState(wasSet, "ChannelSet already set");
 }
Example #22
0
 public static <T> SettableFuture<T> createSettableFuture(T obj) {
   SettableFuture<T> future = SettableFuture.create();
   future.set(obj);
   return future;
 }
Example #23
0
  @Test
  public void testRun() throws Exception {
    HttpClient httpClient = EasyMock.createMock(HttpClient.class);
    final URL url = new URL("http://foo/druid/v2/");

    SettableFuture<InputStream> futureResult = SettableFuture.create();
    Capture<Request> capturedRequest = EasyMock.newCapture();
    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(futureResult)
        .times(1);

    SettableFuture futureException = SettableFuture.create();
    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(futureException)
        .times(1);

    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(SettableFuture.create())
        .atLeastOnce();

    EasyMock.replay(httpClient);

    final ServerSelector serverSelector =
        new ServerSelector(
            new DataSegment(
                "test",
                new Interval("2013-01-01/2013-01-02"),
                new DateTime("2013-01-01").toString(),
                Maps.<String, Object>newHashMap(),
                Lists.<String>newArrayList(),
                Lists.<String>newArrayList(),
                NoneShardSpec.instance(),
                0,
                0L),
            new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()));

    DirectDruidClient client1 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            "foo",
            new NoopServiceEmitter());
    DirectDruidClient client2 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            "foo2",
            new NoopServiceEmitter());

    QueryableDruidServer queryableDruidServer1 =
        new QueryableDruidServer(
            new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client1);
    serverSelector.addServerAndUpdateSegment(queryableDruidServer1, serverSelector.getSegment());
    QueryableDruidServer queryableDruidServer2 =
        new QueryableDruidServer(
            new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client2);
    serverSelector.addServerAndUpdateSegment(queryableDruidServer2, serverSelector.getSegment());

    TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build();
    HashMap<String, List> context = Maps.newHashMap();
    Sequence s1 = client1.run(query, context);
    Assert.assertTrue(capturedRequest.hasCaptured());
    Assert.assertEquals(url, capturedRequest.getValue().getUrl());
    Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod());
    Assert.assertEquals(1, client1.getNumOpenConnections());

    // simulate read timeout
    Sequence s2 = client1.run(query, context);
    Assert.assertEquals(2, client1.getNumOpenConnections());
    futureException.setException(new ReadTimeoutException());
    Assert.assertEquals(1, client1.getNumOpenConnections());

    // subsequent connections should work
    Sequence s3 = client1.run(query, context);
    Sequence s4 = client1.run(query, context);
    Sequence s5 = client1.run(query, context);

    Assert.assertTrue(client1.getNumOpenConnections() == 4);

    // produce result for first connection
    futureResult.set(
        new ByteArrayInputStream(
            "[{\"timestamp\":\"2014-01-01T01:02:03Z\", \"result\": 42.0}]".getBytes()));
    List<Result> results = Sequences.toList(s1, Lists.<Result>newArrayList());
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(new DateTime("2014-01-01T01:02:03Z"), results.get(0).getTimestamp());
    Assert.assertEquals(3, client1.getNumOpenConnections());

    client2.run(query, context);
    client2.run(query, context);

    Assert.assertTrue(client2.getNumOpenConnections() == 2);

    Assert.assertTrue(serverSelector.pick() == queryableDruidServer2);

    EasyMock.verify(httpClient);
  }
 @Override
 public void onResponse(DeleteIndexResponse deleteIndexResponse) {
   future.set(RESULT_PARTITION);
 }
 @Override
 protected void triggerShutdown() {
   completion.set(null);
 }
  /**
   * Closes this channel and broadcasts the highest value payment transaction on the network.
   *
   * <p>This will set the state to {@link State#CLOSED} if the transaction is successfully broadcast
   * on the network. If we fail to broadcast for some reason, the state is set to {@link
   * State#ERROR}.
   *
   * <p>If the current state is before {@link State#READY} (ie we have not finished initializing the
   * channel), we simply set the state to {@link State#CLOSED} and let the client handle getting its
   * refund transaction confirmed.
   *
   * @return a future which completes when the provided multisig contract successfully broadcasts,
   *     or throws if the broadcast fails for some reason. Note that if the network simply rejects
   *     the transaction, this future will never complete, a timeout should be used.
   * @throws InsufficientMoneyException If the payment tx would have cost more in fees to spend than
   *     it is worth.
   */
  public synchronized ListenableFuture<Transaction> close() throws InsufficientMoneyException {
    if (storedServerChannel != null) {
      StoredServerChannel temp = storedServerChannel;
      storedServerChannel = null;
      StoredPaymentChannelServerStates channels =
          (StoredPaymentChannelServerStates)
              wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
      channels.closeChannel(
          temp); // May call this method again for us (if it wasn't the original caller)
      if (state.compareTo(State.CLOSING) >= 0) return closedFuture;
    }

    if (state.ordinal() < State.READY.ordinal()) {
      log.error("Attempt to settle channel in state " + state);
      state = State.CLOSED;
      closedFuture.set(null);
      return closedFuture;
    }
    if (state != State.READY) {
      // TODO: What is this codepath for?
      log.warn("Failed attempt to settle a channel in state " + state);
      return closedFuture;
    }
    Transaction tx = null;
    try {
      Wallet.SendRequest req = makeUnsignedChannelContract(bestValueToMe);
      tx = req.tx;
      // Provide a throwaway signature so that completeTx won't complain out about unsigned inputs
      // it doesn't
      // know how to sign. Note that this signature does actually have to be valid, so we can't use
      // a dummy
      // signature to save time, because otherwise completeTx will try to re-sign it to make it
      // valid and then
      // die. We could probably add features to the SendRequest API to make this a bit more
      // efficient.
      signMultisigInput(tx, Transaction.SigHash.NONE, true);
      // Let wallet handle adding additional inputs/fee as necessary.
      req.shuffleOutputs = false;
      req.missingSigsMode = Wallet.MissingSigsMode.USE_DUMMY_SIG;
      wallet.completeTx(req); // TODO: Fix things so shuffling is usable.
      feePaidForPayment = req.tx.getFee();
      log.info("Calculated fee is {}", feePaidForPayment);
      if (feePaidForPayment.compareTo(bestValueToMe) > 0) {
        final String msg =
            String.format(
                Locale.US,
                "Had to pay more in fees (%s) than the channel was worth (%s)",
                feePaidForPayment,
                bestValueToMe);
        throw new InsufficientMoneyException(feePaidForPayment.subtract(bestValueToMe), msg);
      }
      // Now really sign the multisig input.
      signMultisigInput(tx, Transaction.SigHash.ALL, false);
      // Some checks that shouldn't be necessary but it can't hurt to check.
      tx.verify(); // Sanity check syntax.
      for (TransactionInput input : tx.getInputs())
        input.verify(); // Run scripts and ensure it is valid.
    } catch (InsufficientMoneyException e) {
      throw e; // Don't fall through.
    } catch (Exception e) {
      log.error(
          "Could not verify self-built tx\nMULTISIG {}\nCLOSE {}",
          multisigContract,
          tx != null ? tx : "");
      throw new RuntimeException(e); // Should never happen.
    }
    state = State.CLOSING;
    log.info("Closing channel, broadcasting tx {}", tx);
    // The act of broadcasting the transaction will add it to the wallet.
    ListenableFuture<Transaction> future = broadcaster.broadcastTransaction(tx).future();
    Futures.addCallback(
        future,
        new FutureCallback<Transaction>() {
          @Override
          public void onSuccess(Transaction transaction) {
            log.info("TX {} propagated, channel successfully closed.", transaction.getHash());
            state = State.CLOSED;
            closedFuture.set(transaction);
          }

          @Override
          public void onFailure(Throwable throwable) {
            log.error("Failed to settle channel, could not broadcast", throwable);
            state = State.ERROR;
            closedFuture.setException(throwable);
          }
        });
    return closedFuture;
  }
Example #27
0
  @Test
  public void testQueryInterruptionExceptionLogMessage() throws JsonProcessingException {
    HttpClient httpClient = EasyMock.createMock(HttpClient.class);
    SettableFuture<Object> interruptionFuture = SettableFuture.create();
    Capture<Request> capturedRequest = EasyMock.newCapture();
    String hostName = "localhost:8080";
    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(interruptionFuture)
        .anyTimes();

    EasyMock.replay(httpClient);

    DataSegment dataSegment =
        new DataSegment(
            "test",
            new Interval("2013-01-01/2013-01-02"),
            new DateTime("2013-01-01").toString(),
            Maps.<String, Object>newHashMap(),
            Lists.<String>newArrayList(),
            Lists.<String>newArrayList(),
            NoneShardSpec.instance(),
            0,
            0L);
    final ServerSelector serverSelector =
        new ServerSelector(
            dataSegment,
            new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()));

    DirectDruidClient client1 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            hostName,
            new NoopServiceEmitter());

    QueryableDruidServer queryableDruidServer =
        new QueryableDruidServer(
            new DruidServer("test1", hostName, 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client1);

    serverSelector.addServerAndUpdateSegment(queryableDruidServer, dataSegment);

    TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build();
    HashMap<String, List> context = Maps.newHashMap();
    interruptionFuture.set(new ByteArrayInputStream("{\"error\":\"testing\"}".getBytes()));
    Sequence results = client1.run(query, context);

    QueryInterruptedException actualException = null;
    try {
      Sequences.toList(results, Lists.newArrayList());
    } catch (QueryInterruptedException e) {
      actualException = e;
    }
    Assert.assertNotNull(actualException);
    Assert.assertEquals(actualException.getMessage(), QueryInterruptedException.UNKNOWN_EXCEPTION);
    Assert.assertEquals(actualException.getCauseMessage(), "testing");
    Assert.assertEquals(actualException.getHost(), hostName);
    EasyMock.verify(httpClient);
  }