java.util.concurrent.ExecutionException Java Examples

The following examples show how to use java.util.concurrent.ExecutionException. 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: IdentityUserTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testSyncSameUser() throws IOException, InterruptedException, ExecutionException {
  IdentityUser previous =
      new IdentityUser.Builder()
          .setUserIdentity("user1")
          .setSchema("schema")
          .setAttribute("attrib")
          .setGoogleIdentity("[email protected]")
          .build();
  IdentityUser current =
      new IdentityUser.Builder()
          .setUserIdentity("user1")
          .setSchema("schema")
          .setAttribute("attrib")
          .setGoogleIdentity("[email protected]")
          .build();
  ListenableFuture<IdentityUser> sync = current.sync(previous, mockIdentityService);
  assertEquals(current, sync.get());
}
 
Example #2
Source File: NettyHttpClientHandler.java    From jus with Apache License 2.0 6 votes vote down vote up
private synchronized NetworkResponse doGet(Long timeoutMs)
        throws InterruptedException, ExecutionException, TimeoutException {
    if (exception != null) {
        throw new ExecutionException(exception);
    }

    if (resultReceived) {
        return result;
    }

    if (timeoutMs == null) {
        wait(0);
    } else if (timeoutMs > 0) {
        wait(timeoutMs);
    }

    if (exception != null) {
        throw new ExecutionException(exception);
    }

    if (!resultReceived) {
        throw new TimeoutException();
    }

    return result;
}
 
Example #3
Source File: DataTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void listenForValueThenWriteOnANodeWithExistingData()
    throws DatabaseException, ExecutionException, TimeoutException, InterruptedException,
        TestFailure {
  List<DatabaseReference> refs = IntegrationTestHelpers.getRandomNode(2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  new WriteFuture(writer, new MapBuilder().put("a", 5).put("b", 2).build()).timedGet();

  ReadFuture readFuture = new ReadFuture(reader);

  // Slight race condition. We're banking on this local set being processed before the
  // network catches up with the writer's broadcast.
  reader.child("a").setValue(10);

  EventRecord event = readFuture.timedGet().get(0);

  assertEquals(10L, event.getSnapshot().child("a").getValue());
}
 
Example #4
Source File: ArangoDatabaseTest.java    From arangodb-java-driver with Apache License 2.0 6 votes vote down vote up
@Test
public void getCollections() throws InterruptedException, ExecutionException {
    try {
        final Collection<CollectionEntity> systemCollections = db.getCollections(null).get();
        db.createCollection(COLLECTION_NAME + "1", null).get();
        db.createCollection(COLLECTION_NAME + "2", null).get();
        db.getCollections(null)
                .whenComplete((collections, ex) -> {
                    assertThat(collections.size(), is(2 + systemCollections.size()));
                    assertThat(collections, is(notNullValue()));
                })
                .get();
    } finally {
        db.collection(COLLECTION_NAME + "1").drop().get();
        db.collection(COLLECTION_NAME + "2").drop().get();
    }
}
 
Example #5
Source File: LumentumWaveReadyDiscovery.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public List<PortDescription> discoverPortDetails() {
    DeviceId deviceId = handler().data().deviceId();
    Tl1Controller ctrl = checkNotNull(handler().get(Tl1Controller.class));

    // Assume we're successfully logged in
    // Fetch port descriptions
    Tl1Command pdCmd = DefaultTl1Command.builder()
            .withVerb(RTRV)
            .withModifier(PLUGGABLE_INV)
            .withCtag(102)
            .build();
    Future<String> pd = ctrl.sendMsg(deviceId, pdCmd);

    try {
        String pdResponse = pd.get(TIMEOUT, TimeUnit.MILLISECONDS);

        return extractPorts(pdResponse);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        log.error("Port description not found", e);
        return Collections.EMPTY_LIST;
    }
}
 
Example #6
Source File: RequestFuture.java    From TitanjumNote with Apache License 2.0 6 votes vote down vote up
private synchronized T doGet(Long timeoutMs)
        throws InterruptedException, ExecutionException, TimeoutException {
    if (mException != null) {
        throw new ExecutionException(mException);
    }

    if (mResultReceived) {
        return mResult;
    }

    if (timeoutMs == null) {
        wait(0);
    } else if (timeoutMs > 0) {
        wait(timeoutMs);
    }

    if (mException != null) {
        throw new ExecutionException(mException);
    }

    if (!mResultReceived) {
        throw new TimeoutException();
    }

    return mResult;
}
 
Example #7
Source File: CacheLoadingTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
public void testBulkLoadUncheckedException() throws ExecutionException {
  Exception e = new RuntimeException();
  CacheLoader<Object, Object> loader = exceptionLoader(e);
  LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
      .recordStats(), bulkLoader(loader));
  CacheStats stats = cache.stats();
  assertEquals(0, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(0, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());

  try {
    cache.getAll(asList(new Object()));
    fail();
  } catch (UncheckedExecutionException expected) {
    assertSame(e, expected.getCause());
  }
  stats = cache.stats();
  assertEquals(1, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(1, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());
}
 
Example #8
Source File: DefaultDeployer.java    From helios with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
String pickHost(final List<String> filteredHosts) {
  final List<String> mutatedList = Lists.newArrayList(filteredHosts);

  while (true) {
    final String candidateHost = hostPicker.pickHost(mutatedList);
    try {
      final HostStatus hostStatus = client.hostStatus(candidateHost).get();
      if (hostStatus != null && Status.UP == hostStatus.getStatus()) {
        return candidateHost;
      }
      mutatedList.remove(candidateHost);
      if (mutatedList.isEmpty()) {
        fail("all hosts matching filter pattern are DOWN");
      }
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example #9
Source File: BruteForceProtectionBean.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public int registerUnsuccessfulLogin(String login, String ipAddress) {
    lock.readLock().lock();
    try {
        checkInitialized();
    } finally {
        lock.readLock().unlock();
    }

    lock.writeLock().lock();
    try {
        String cacheKey = makeCacheKey(login, ipAddress);
        Integer attemptsNumber = loginAttemptsCache.get(cacheKey);
        loginAttemptsCache.put(cacheKey, attemptsNumber + 1);
        return serverConfig.getMaxLoginAttemptsNumber() - (attemptsNumber + 1);
    } catch (ExecutionException e) {
        throw new RuntimeException("BruteForceProtection error", e);
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example #10
Source File: DatabaseImpl.java    From sync-android with Apache License 2.0 6 votes vote down vote up
@Override
public InternalDocumentRevision read(final String id, final String rev) throws
        DocumentNotFoundException, DocumentStoreException {
    Misc.checkState(this.isOpen(), "Database is closed");
    Misc.checkNotNullOrEmpty(id, "Document id");
    try {
        if (id.startsWith(CouchConstants._local_prefix)) {
            Misc.checkArgument(rev == null, "Local documents must have a null revision ID");
            String localId = id.substring(CouchConstants._local_prefix.length());
            LocalDocument ld = get(queue.submit(new GetLocalDocumentCallable(localId)));
            // convert to DocumentRevision, adding back "_local/" prefix which was stripped off when document was written
            return new DocumentRevisionBuilder().setDocId(CouchConstants._local_prefix + ld.docId).setBody(ld.body).build();
        } else {
            return get(queue.submit(new GetDocumentCallable(id, rev, this.attachmentsDir, this.attachmentStreamFactory)));
        }
    } catch (ExecutionException e) {
        throwCauseAs(e, DocumentNotFoundException.class);
        String message = String.format(Locale.ENGLISH, "Failed to get document id %s at revision %s", id, rev);
        logger.log(Level.SEVERE, message, e);
        throw new DocumentStoreException(message, e.getCause());
    }
}
 
Example #11
Source File: TrackingParallelWriterIndexCommitter.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private Throwable logFailedTasksAndGetCause(List<Future<Boolean>> failedFutures,
        List<HTableInterfaceReference> failedTables) {
    int i = 0;
    Throwable t = null;
    for (Future<Boolean> future : failedFutures) {
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.warn("Index Write failed for table " + failedTables.get(i), e);
            if (t == null) {
                t = e;
            }
        }
        i++;
    }
    return t;
}
 
Example #12
Source File: RubyRepSshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected void customizeConfiguration() throws ExecutionException, InterruptedException, URISyntaxException {
    log.info("Copying creation script " + getEntity().toString());

    // TODO check these semantics are what we really want?
    String configScriptUrl = entity.getConfig(RubyRepNode.CONFIGURATION_SCRIPT_URL);
    Reader configContents;
    if (configScriptUrl != null) {
        // If set accept as-is
        configContents = Streams.reader(resource.getResourceFromUrl(configScriptUrl));
    } else {
        String configScriptContents = processTemplate(entity.getConfig(RubyRepNode.TEMPLATE_CONFIGURATION_URL));
        configContents = Streams.newReaderWithContents(configScriptContents);
    }

    getMachine().copyTo(configContents, getRunDir() + "/rubyrep.conf");
}
 
Example #13
Source File: RedissonMapCacheTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpireOverwrite() throws InterruptedException, ExecutionException {
    RMapCache<String, Integer> map = redisson.getMapCache("simple");
    map.put("123", 3, 1, TimeUnit.SECONDS);

    Thread.sleep(800);

    map.put("123", 3, 1, TimeUnit.SECONDS);

    Thread.sleep(800);
    Assert.assertEquals(3, (int)map.get("123"));

    Thread.sleep(200);

    Assert.assertFalse(map.containsKey("123"));
    map.destroy();
}
 
Example #14
Source File: BaseAlarmService.java    From Groza with Apache License 2.0 6 votes vote down vote up
@Override
public Alarm createOrUpdateAlarm(Alarm alarm) {
    alarmDataValidator.validate(alarm);
    try {
        if (alarm.getStartTs() == 0L) {
            alarm.setStartTs(System.currentTimeMillis());
        }
        if (alarm.getEndTs() == 0L) {
            alarm.setEndTs(alarm.getStartTs());
        }
        if (alarm.getId() == null) {
            Alarm existing = alarmDao.findLatestByOriginatorAndType(alarm.getTenantId(), alarm.getOriginator(), alarm.getType()).get();
            if (existing == null || existing.getStatus().isCleared()) {
                return createAlarm(alarm);
            } else {
                return updateAlarm(existing, alarm);
            }
        } else {
            return updateAlarm(alarm).get();
        }
    } catch (ExecutionException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: ThreadsDslInOutTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testParallelConsumption() throws InterruptedException, ExecutionException {
    final int messageCount = 10;

    final MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(messageCount);
    mockOut.setResultWaitTime(5000);

    for (int i = 0; i < messageCount; i++) {
        Future<Object> future = template.asyncRequestBody("direct:in", "Message[" + i + "]");
        // here we ask the Future to return to us the response set by the thread assigned by the
        // threads() DSL
        String response = (String) future.get();
        assertEquals("Processed", response);
    }

    assertMockEndpointsSatisfied();
}
 
Example #16
Source File: TestElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void deleteAllIndices() {

		ImmutableOpenMap<String, IndexMetaData> indices = elasticSearchClient.admin().cluster()
				.prepareState().get().getState()
				.getMetaData().getIndices();

		indices.forEach(cursor -> {
			try {
				elasticSearchClient.admin()
						.indices()
						.delete(new DeleteIndexRequest(cursor.value.getIndex().getName()))
						.get();
			} catch (InterruptedException | ExecutionException e) {
				throw new RuntimeException(e);
			}
		});
	}
 
Example #17
Source File: CommandHttpTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test cleanup
 * 
 */
@AfterGroups(groups = {"http-commands"})
public static void stopGlassFish() {
    final String METHOD = "stopGlassFish";
    LOGGER.log(Level.INFO, METHOD, "stopFrame");
    LOGGER.log(Level.INFO, METHOD, "stopText");
    LOGGER.log(Level.INFO, METHOD, "stopFrame");
    GlassFishServer server = glassFishServer();
    Command command = new CommandStopDAS();
    try {
        Future<ResultString> future = 
                ServerAdmin.<ResultString>exec(server, command);
        try {
            ResultString result = future.get();
            gfStdOut.close();
            gfStdErr.close();
            assertNotNull(result.getValue());
            assertTrue(result.getState() == TaskState.COMPLETED);
        } catch (InterruptedException | ExecutionException ie) {
            fail("Version command execution failed: " + ie.getMessage());
        }
    } catch (GlassFishIdeException gfie) {
        fail("Version command execution failed: " + gfie.getMessage());
    }
}
 
Example #18
Source File: MySQLClient.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T waitExpectedResponse(final Class<T> type) {
    try {
        Object response = responseCallback.get();
        if (null == response) {
            return null;
        }
        if (type.equals(response.getClass())) {
            return (T) response;
        }
        if (response instanceof MySQLErrPacket) {
            throw new RuntimeException(((MySQLErrPacket) response).getErrorMessage());
        }
        throw new RuntimeException("unexpected response type");
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: AbstractAsynchronousOperationHandlersTest.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that an querying an unknown trigger id will return an exceptionally completed
 * future.
 */
@Test
public void testUnknownTriggerId() throws Exception {
	final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder().build();

	try {
		testingStatusHandler.handleRequest(
			statusOperationRequest(new TriggerId()),
			testingRestfulGateway).get();

		fail("This should have failed with a RestHandlerException.");
	} catch (ExecutionException ee) {
		final Optional<RestHandlerException> optionalRestHandlerException = ExceptionUtils.findThrowable(ee, RestHandlerException.class);

		assertThat(optionalRestHandlerException.isPresent(), is(true));

		final RestHandlerException restHandlerException = optionalRestHandlerException.get();

		assertThat(restHandlerException.getMessage(), containsString("Operation not found"));
		assertThat(restHandlerException.getHttpResponseStatus(), is(HttpResponseStatus.NOT_FOUND));
	}
}
 
Example #20
Source File: JBDeploymentManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public ProgressObject start(final TargetModuleID[] targetModuleID) throws IllegalStateException {
    if (df == null) {
        throw new IllegalStateException("Deployment manager is disconnected");
    }
    try {
        return executeAction(new Action<ProgressObject>() {
            @Override
            public ProgressObject execute(DeploymentManager manager) throws ExecutionException {
                if (isAs7()) {
                    return manager.start(unwrap(targetModuleID));
                }
                return manager.start(targetModuleID);
            }
        });
    } catch (Exception ex) {
        if (ex.getCause() instanceof IllegalStateException) {
            throw (IllegalStateException) ex.getCause();
        } else {
            throw new IllegalStateException(ex.getCause());
        }
    }
}
 
Example #21
Source File: ShutdownHelper.java    From embedded-rabbitmq with Apache License 2.0 6 votes vote down vote up
private void confirmShutdown() throws ShutDownException {
  int exitValue;
  try {
    ProcessResult rabbitMqProcessResult = rabbitMqProcess.get(timeoutDuration, TimeUnit.MILLISECONDS);
    exitValue = rabbitMqProcessResult.getExitValue();
  } catch (InterruptedException | ExecutionException | TimeoutException e) {
    throw new ShutDownException("Error while waiting " + timeoutDuration + " " + timeoutUnit + "for "
        + "RabbitMQ Server to shut down", e);
  }

  if (exitValue == 0) {
    LOGGER.debug("RabbitMQ Server stopped successfully.");
  } else {
    LOGGER.warn("RabbitMQ Server stopped with exit value: " + exitValue);
  }
}
 
Example #22
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleQueriesOnTheSameNode()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  new WriteFuture(ref, new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4)
      .put("e", 5).put("f", 6).build()).timedGet();

  final AtomicInteger limit2Called = new AtomicInteger(0);
  final Semaphore semaphore = new Semaphore(0);
  ref.limitToLast(2).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      // Should only be called once
      if (limit2Called.incrementAndGet() == 1) {
        semaphore.release(1);
      }
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });

  // Skipping nested calls, no re-entrant APIs in Java

  TestHelpers.waitFor(semaphore);
  assertEquals(1, limit2Called.get());

  DataSnapshot snap = TestHelpers.getSnap(ref.limitToLast(1));
  TestHelpers.assertDeepEquals(MapBuilder.of("f", 6L), snap.getValue());
}
 
Example #23
Source File: RelationQueryCache.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
public SliceQuery getQuery(InternalRelationType type, Direction dir) {
    CacheEntry ce;
    try {
        ce = cache.get(type.longId(), () -> new CacheEntry(edgeSerializer, type));
    } catch (ExecutionException e) {
        throw new AssertionError("Should not happen: " + e.getMessage());
    }
    return ce.get(dir);
}
 
Example #24
Source File: RequestTest.java    From jus with Apache License 2.0 5 votes vote down vote up
/**
 * 10.2.5 204 No Content - means what it says, however representations of HTTP responses may not only
 * consider the entity-body(which anyway is not 'MUST' restricted) but entity-headers as well
 */
@Test
public void http204_DOES_NOT_SkipConverter() throws IOException, ExecutionException, InterruptedException {
    final Converter<NetworkResponse, Number> converter = spy(new Converter<NetworkResponse, Number>() {
        @Override
        public Number convert(NetworkResponse value) throws IOException {
            if (value.data == null || value.data.length == 0) {
                return null;
            }
            return Double.parseDouble(value.getBodyAsString());
        }
    });
    retroProxy = new RetroProxy.Builder()
            .baseUrl(server.url("/").toString())
            .addConverterFactory(new ToNumberConverterFactory() {
                @Override
                public Converter<NetworkResponse, ?> fromResponse(Type type, Annotation[] annotations) {
                    return converter;
                }
            })
            .build();
    Service example = retroProxy.create(Service.class);

    server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin"));

    Request<Number> request = example.getNumber();
    request.getFuture().get();
    Response<Number> response = request.getRawResponse();
    assertThat(response.isSuccess()).isTrue();
    assertThat(response.result).isNull();
    verify(converter).convert((NetworkResponse) Mockito.anyObject());
    verifyNoMoreInteractions(converter);
}
 
Example #25
Source File: TaskExecutorTest.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that we ignore slot requests if the TaskExecutor is not
 * registered at a ResourceManager.
 */
@Test
public void testIgnoringSlotRequestsIfNotRegistered() throws Exception {
	final TaskExecutor taskExecutor = createTaskExecutor(1);

	taskExecutor.start();

	try {
		final TestingResourceManagerGateway testingResourceManagerGateway = new TestingResourceManagerGateway();

		final CompletableFuture<RegistrationResponse> registrationFuture = new CompletableFuture<>();
		final CompletableFuture<ResourceID> taskExecutorResourceIdFuture = new CompletableFuture<>();

		testingResourceManagerGateway.setRegisterTaskExecutorFunction(taskExecutorRegistration -> {
			taskExecutorResourceIdFuture.complete(taskExecutorRegistration.getResourceId());
			return registrationFuture;
		});

		rpc.registerGateway(testingResourceManagerGateway.getAddress(), testingResourceManagerGateway);
		resourceManagerLeaderRetriever.notifyListener(testingResourceManagerGateway.getAddress(), testingResourceManagerGateway.getFencingToken().toUUID());

		final TaskExecutorGateway taskExecutorGateway = taskExecutor.getSelfGateway(TaskExecutorGateway.class);

		final ResourceID resourceId = taskExecutorResourceIdFuture.get();

		final SlotID slotId = new SlotID(resourceId, 0);
		final CompletableFuture<Acknowledge> slotRequestResponse = taskExecutorGateway.requestSlot(slotId, jobId, new AllocationID(), ResourceProfile.ZERO, "foobar", testingResourceManagerGateway.getFencingToken(), timeout);

		try {
			slotRequestResponse.get();
			fail("We should not be able to request slots before the TaskExecutor is registered at the ResourceManager.");
		} catch (ExecutionException ee) {
			assertThat(ExceptionUtils.stripExecutionException(ee), instanceOf(TaskManagerException.class));
		}
	} finally {
		RpcUtils.terminateRpcEndpoint(taskExecutor, timeout);
	}
}
 
Example #26
Source File: ApiHandlerTest.java    From riotapi with Apache License 2.0 5 votes vote down vote up
public void testGetItems() throws InterruptedException, ExecutionException, TimeoutException {
    try {
        handler.getItemList(ItemData.ALL).get(1, MINUTES);
    } catch (RequestException ex) {
        // 5xx errors indicate serverside issues
        if (isNotServerside(ex)) throw ex;
    }
}
 
Example #27
Source File: FieldSetter.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void setUnchecked(Object obj, T value) {
    try {
        set(obj, value);
    } catch(ExecutionException e) {
        throw new UncheckedExecutionException(e.getCause());
    }
}
 
Example #28
Source File: BlockingQueueContextPropagationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncSpanDelegation() throws ExecutionException, InterruptedException {
    Transaction transaction = ElasticApm.startTransaction();
    long startTime = TimeUnit.NANOSECONDS.toMicros(nanoTimeOffsetToEpoch + System.nanoTime());
    transaction.setStartTimestamp(startTime);
    final CompletableFuture<String> result = new CompletableFuture<>();
    String asyncSpanId = null;
    try (Scope scope = transaction.activate()) {
        final Span asyncSpan = ElasticApm.currentSpan().startSpan("async", "blocking-queue", null);
        asyncSpanId = asyncSpan.getId();
        blockingQueue.offer(new ElasticApmQueueElementWrapper<>(result, asyncSpan));
    } catch (Exception e) {
        e.printStackTrace();
    }
    transaction.end();

    // important for waiting on the queue reader thread to finish the span
    assertThat(result.get()).isEqualTo(asyncSpanId);

    co.elastic.apm.agent.impl.transaction.Transaction reportedTransaction = reporter.getFirstTransaction();
    assertThat(reportedTransaction).isNotNull();
    long transactionTimestamp = reportedTransaction.getTimestamp();
    assertThat(transactionTimestamp).isEqualTo(startTime);
    assertThat(reportedTransaction.getDuration()).isBetween(
        TimeUnit.MILLISECONDS.toMicros(0),
        TimeUnit.MILLISECONDS.toMicros(70)
    );

    co.elastic.apm.agent.impl.transaction.Span reportedSpan = reporter.getFirstSpan();
    assertThat(reportedSpan.getTraceContext().getTraceId()).isEqualTo(reportedTransaction.getTraceContext().getTraceId());
    assertThat(reportedSpan).isNotNull();
    assertThat(reportedSpan.getType()).isEqualTo("async");
    assertThat(reportedSpan.getTimestamp() - transactionTimestamp).isGreaterThanOrEqualTo(TimeUnit.MILLISECONDS.toMicros(100));
    assertThat(reportedSpan.getDuration()).isBetween(
        TimeUnit.MILLISECONDS.toMicros(10),
        TimeUnit.MILLISECONDS.toMicros(70)
    );
}
 
Example #29
Source File: CombinatorTreeCache.java    From yanwte2 with Apache License 2.0 5 votes vote down vote up
public static Lazy<Combinator> getLazyTree(ServiceOrchestrator<?> serviceOrchestrator) {
    try {
        return cache.get(serviceOrchestrator, () -> getLazyCombinatorTree(serviceOrchestrator));
    } catch (UncheckedExecutionException | ExecutionException e) {
        Throwables.throwIfUnchecked(e.getCause());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #30
Source File: ConsulTargetsCache.java    From GomJabbar with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException, ExecutionException, InterruptedException {
    final URL configFileUrl = new URL("file:./config-template.yaml");
    final TargetFilters targetFilters = ConfigParser.parseConfiguration(configFileUrl).targetFilters;

    final ConsulTargetsCache consulTargetsCache = new ConsulTargetsCache(ConsulAPI.getHealth(), ConsulAPI.getCatalog(), targetFilters);

//    consulTargetsCache.print();

    for (int i = 0; i < 1000; i++) {
      System.out.println(consulTargetsCache.chooseTarget().get());
      Thread.sleep(2000);
    }
  }