Java Code Examples for com.google.common.base.Supplier#get()

The following examples show how to use com.google.common.base.Supplier#get() . 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: GenericTestUtils.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Wait for the specified test to return true. The test will be performed
 * initially and then every {@code checkEveryMillis} until at least
 * {@code waitForMillis} time has expired. If {@code check} is null or
 * {@code waitForMillis} is less than {@code checkEveryMillis} this method
 * will throw an {@link IllegalArgumentException}.
 *
 * @param check            the test to perform
 * @param checkEveryMillis how often to perform the test
 * @param waitForMillis    the amount of time after which no more tests
 *                         will be
 *                         performed
 * @throws TimeoutException     if the test does not return true in the
 *                              allotted
 *                              time
 * @throws InterruptedException if the method is interrupted while waiting
 */
public static void waitFor(Supplier<Boolean> check, int checkEveryMillis,
    int waitForMillis) throws TimeoutException, InterruptedException {
  Preconditions.checkNotNull(check, ERROR_MISSING_ARGUMENT);
  Preconditions.checkArgument(waitForMillis >= checkEveryMillis,
      ERROR_INVALID_ARGUMENT);

  long st = monotonicNow();
  boolean result = check.get();

  while (!result && (monotonicNow() - st < waitForMillis)) {
    Thread.sleep(checkEveryMillis);
    result = check.get();
  }

  if (!result) {
    throw new TimeoutException("Timed out waiting for condition. " +
        "Thread diagnostics:\n" +
        TimedOutTestsListener.buildThreadDiagnosticString());
  }
}
 
Example 2
Source File: InternalSubchannel.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
InternalSubchannel(List<EquivalentAddressGroup> addressGroups, String authority, String userAgent,
    BackoffPolicy.Provider backoffPolicyProvider,
    ClientTransportFactory transportFactory, ScheduledExecutorService scheduledExecutor,
    Supplier<Stopwatch> stopwatchSupplier, SynchronizationContext syncContext, Callback callback,
    InternalChannelz channelz, CallTracer callsTracer, ChannelTracer channelTracer,
    InternalLogId logId, TimeProvider timeProvider) {
  Preconditions.checkNotNull(addressGroups, "addressGroups");
  Preconditions.checkArgument(!addressGroups.isEmpty(), "addressGroups is empty");
  checkListHasNoNulls(addressGroups, "addressGroups contains null entry");
  this.addressIndex = new Index(
      Collections.unmodifiableList(new ArrayList<>(addressGroups)));
  this.authority = authority;
  this.userAgent = userAgent;
  this.backoffPolicyProvider = backoffPolicyProvider;
  this.transportFactory = transportFactory;
  this.scheduledExecutor = scheduledExecutor;
  this.connectingTimer = stopwatchSupplier.get();
  this.syncContext = syncContext;
  this.callback = callback;
  this.channelz = channelz;
  this.callsTracer = callsTracer;
  this.channelTracer = Preconditions.checkNotNull(channelTracer, "channelTracer");
  this.logId = Preconditions.checkNotNull(logId, "logId");
  this.channelLogger = new ChannelLoggerImpl(channelTracer, timeProvider);
}
 
Example 3
Source File: PacketSchedulerTestCase.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueueDrops() throws Exception {
   final int TEST_SIZE = 1000000;
   Supplier<DropCounter> dropSupplier = Suppliers.memoize(DropCounterSupplier.INSTANCE);
   DropCounter drops = dropSupplier.get();

   T scheduler = createPacketScheduler()
      .dropOnQueueFull()
      .setDropHandler(dropSupplier)
      .build();

   PacketScheduler.Producer<Packet> producer = scheduler.attach();
   for (int i = 0; i < TEST_SIZE; ++i) {
      Packet sent1 = new Packet(i);
      producer.send(sent1);

      Packet sent2 = new Packet(TEST_SIZE+i);
      producer.send(sent2);

      Packet recv = scheduler.poll();
      assertSame("received an unexpected packet", sent1, recv);
   }

   assertEquals("queue dropped packets", TEST_SIZE, drops.get());
}
 
Example 4
Source File: PacketSchedulerTestCase.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleThreadedProduceConsumeProcessesAll() throws Exception {
   final int TEST_SIZE = 1000000;
   Supplier<DropCounter> dropSupplier = Suppliers.memoize(DropCounterSupplier.INSTANCE);
   DropCounter drops = dropSupplier.get();

   T scheduler = createPacketScheduler()
      .dropOnQueueFull()
      .setDropHandler(dropSupplier)
      .build();

   PacketScheduler.Producer<Packet> producer = scheduler.attach();
   for (int i = 0; i < TEST_SIZE; ++i) {
      Packet sent = new Packet(i);
      producer.send(sent);

      Packet recv = scheduler.poll();
      assertSame("received an unexpected packet", sent, recv);
   }

   assertEquals("queue dropped packets", 0L, drops.get());
}
 
Example 5
Source File: GatewayNetty.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static Provider create() {
   Supplier<String> nettyProvider = ConfigService.supplier("iris.gateway.provider", String.class, "");
   switch (nettyProvider.get()) {
   case "epoll":
      if (Epoll.isAvailable()) {
         log.debug("using netty epoll provider for gateway connection");
         return epoll();
      } else {
         if (!"".equals(nettyProvider.get())) {
            log.warn("netty epoll provider requested but not available, using nio for gateway connection:", Epoll.unavailabilityCause());
         } else {
            log.debug("using netty nio provider for gateway connection");
         }
         return nio();
      }

   case "":
   case "nio":
      log.debug("using netty nio provider for gateway connection");
      return nio();

   default:
      log.warn("unknown netty provider, using nio by default");
      return nio();
   }
}
 
Example 6
Source File: Main.java    From k8s-wordsmith-demo with Apache License 2.0 5 votes vote down vote up
private static HttpHandler handler(Supplier<String> word) {
    return t -> {
        String response = "{\"word\":\"" + word.get() + "\"}";
        byte[] bytes = response.getBytes(Charsets.UTF_8);

        System.out.println(response);
        t.getResponseHeaders().add("content-type", "application/json; charset=utf-8");
        t.sendResponseHeaders(200, bytes.length);

        try (OutputStream os = t.getResponseBody()) {
            os.write(bytes);
        }
    };
}
 
Example 7
Source File: PacketSchedulerTestCase.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected static void daemon(Thread[] threads, String type, Supplier<Runnable> task) {
   for (int i = 0; i < threads.length; ++i) {
      Thread thr = new Thread(task.get());

      thr.setDaemon(true);
      thr.setName(type + i);
      threads[i] = thr;
   }
}
 
Example 8
Source File: PacketSchedulerTestCase.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected static void create(Thread[] threads, String type, Supplier<Runnable> task) {
   for (int i = 0; i < threads.length; ++i) {
      Thread thr = new Thread(task.get());

      thr.setDaemon(false);
      thr.setName(type + i);
      threads[i] = thr;
   }
}
 
Example 9
Source File: PacketSchedulerTestCase.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testRateLimitsProducers() throws Exception {
   final int TEST_SIZE = 20;
   final double RATE_LIMIT = 10.0;
   final double EXPECTED_TIME = (double)TEST_SIZE / RATE_LIMIT;
   final double EPSILON = 0.100;

   Supplier<DropCounter> dropSupplier = Suppliers.memoize(DropCounterSupplier.INSTANCE);
   DropCounter drops = dropSupplier.get();

   T scheduler = createPacketScheduler()
      .setDropHandler(dropSupplier)
      .setProducerRateLimiter(RateLimiters.tokenBucket(1, RATE_LIMIT))
      //.useArrayQueue(TEST_SIZE)
      .build();

   PacketScheduler.Producer<Packet> producer = scheduler.attach();
   long start = System.nanoTime();
   for (int i = 0; i < TEST_SIZE; ++i) {
      Packet sent = new Packet(i);
      producer.send(sent);
      scheduler.take();
   }
   long elapsed = System.nanoTime() - start;
   double seconds = (double)elapsed / 1000000000.0;
   double epsilon = Math.abs(seconds - EXPECTED_TIME);

   assertEquals("queue dropped packets", 0, drops.get());
   assertTrue("execution time was different than expected: expected=" + EXPECTED_TIME + ", actual=" + seconds, epsilon < EPSILON);
}
 
Example 10
Source File: PacketSchedulerTestCase.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testRateLimitsOutput() throws Exception {
   final int TEST_SIZE = 20;
   final double RATE_LIMIT = 10.0;
   final double EXPECTED_TIME = (double)TEST_SIZE / RATE_LIMIT;
   final double EPSILON = 0.100;

   Supplier<DropCounter> dropSupplier = Suppliers.memoize(DropCounterSupplier.INSTANCE);
   DropCounter drops = dropSupplier.get();

   T scheduler = createPacketScheduler()
      .setDropHandler(dropSupplier)
      .setRateLimiter(RateLimiters.tokenBucket(1, RATE_LIMIT).setInitiallyEmpty())
      .useArrayQueue(TEST_SIZE)
      .build();

   PacketScheduler.Producer<Packet> producer = scheduler.attach();
   for (int i = 0; i < TEST_SIZE; ++i) {
      Packet sent = new Packet(i);
      producer.send(sent);
   }

   long start = System.nanoTime();
   for (int i = 0; i < TEST_SIZE; ++i) {
      scheduler.take();
   }
   long elapsed = System.nanoTime() - start;
   double seconds = (double)elapsed / 1000000000.0;
   double epsilon = Math.abs(seconds - EXPECTED_TIME);

   assertEquals("queue dropped packets", 0, drops.get());
   assertTrue("execution time was different than expected: expected=" + EXPECTED_TIME + ", actual=" + seconds, epsilon < EPSILON);
}
 
Example 11
Source File: Models.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static <M extends Model> ClientFuture<M> getOrLoad(String address, Supplier<ClientFuture<M>> loader) {
	Model model =
 	IrisClientFactory
 		.getModelCache()
 		.get(address);
	if(model != null) {
		return Futures.succeededFuture((M) model);
	}
	
	return loader.get();
}
 
Example 12
Source File: GatewayNetty.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static SslProvider createSslProvider() {
   Supplier<String> sslProvider = ConfigService.supplier("iris.gateway.ssl.provider", String.class, "");

   Security.addProvider(new BouncyCastleProvider());

   switch (sslProvider.get()) {
   case "":
   case "openssl":
      if (OpenSsl.isAvailable()) {
         log.debug("using openssl for gateway ssl provider");
         return openssl();
      } else {
         if (!"".equals(sslProvider.get())) {
            log.warn("openssl ssl provider requested but not available, using jdk ssl for gateway connection:", OpenSsl.unavailabilityCause());
         } else {
            log.debug("using jdk for gateway ssl provider: ", OpenSsl.unavailabilityCause());
         }
         return jdk();
      }

   case "jdk":
      log.debug("using jdk for gateway ssl provider");
      return jdk();

   default:
      log.warn("unknown ssl provider, using jdk by default");
      return jdk();
   }
}
 
Example 13
Source File: PreviewConfig.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public List<StorageCredentials> getStorageAzureAccounts() {
	List<StorageCredentials> result = new ArrayList<>();

	for (int i = 1; true; ++i) {
		String rawAccount = "previews.storage.azure.account" + i;
		ConfigurationKey confAccount = new ConfigurationKey(rawAccount, KeyParser.parse(rawAccount));
		Supplier<String> supAccount = configProvider.getStringSupplier(confAccount, null);
		String account = (supAccount == null) ? null : supAccount.get();

		if (account == null || account.trim().isEmpty()) {
			break;
		}

		try {
			StorageCredentials creds = StorageCredentials.tryParseCredentials(account);
			if (creds == null) {
				throw new RuntimeException("invalid azure storage credentials");
			}

			result.add(creds);
		} catch (InvalidKeyException ex) {
			throw new RuntimeException(ex);
		}
	}

	return result;
}
 
Example 14
Source File: VideoConfig.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public List<StorageCredentials> getStorageAzureAccounts() {
   List<StorageCredentials> result = new ArrayList<>();

   for (int i = 1; true; ++i) {
      String rawAccount = "video.storage.azure.account" + i;
      ConfigurationKey confAccount = new ConfigurationKey(rawAccount, KeyParser.parse(rawAccount));
      Supplier<String> supAccount = configProvider.getStringSupplier(confAccount, null);
      String account = (supAccount == null) ? null : supAccount.get();

      if (account == null || account.trim().isEmpty()) {
         break;
      }

      try {
         StorageCredentials creds = StorageCredentials.tryParseCredentials(account);
         if (creds == null) {
            throw new RuntimeException("invalid azure storage credentials");
         }

         result.add(creds);
      } catch (InvalidKeyException ex) {
         throw new RuntimeException(ex);
      }
   }

   return result;
}
 
Example 15
Source File: AbstractKafkaConfig.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T get(ConfigurationProvider configProvider, String prefix, String base, Class<T> type, @Nullable T def) {
   try {
      ConfigurationKey conf = new ConfigurationKey(prefix + base, KeyParser.parse(prefix + base));
      if(!configProvider.has(conf)) {
         return def;
      }

      Supplier<T> sup;
      if (String.class == type) {
         sup = (Supplier<T>)configProvider.getStringSupplier(conf, (String)def);
      } else if (Long.class == type || long.class == type) {
         sup = (Supplier<T>)configProvider.getLongSupplier(conf, (Long)def);
      } else if (Integer.class == type || int.class == type) {
         sup = (Supplier<T>)configProvider.getIntegerSupplier(conf, (Integer)def);
      } else if (Boolean.class == type || boolean.class == type) {
         sup = (Supplier<T>)configProvider.getBooleanSupplier(conf, (Boolean)def);
      } else if (Double.class == type || double.class == type) {
         sup = (Supplier<T>)configProvider.getDoubleSupplier(conf, (Double)def);
      } else {
         throw new IllegalArgumentException("cannot get configuration supplier for type: " + type.getName());
      }

      return (sup == null) ? def : sup.get();
   }
   catch(Exception e) {
      throw new IllegalArgumentException("Unable to read property [" + prefix + base + "]", e);
   }
}
 
Example 16
Source File: CalcitePrepareImpl.java    From Quicksql with MIT License 4 votes vote down vote up
private PreparedResult prepare_(Supplier<RelNode> fn,
    RelDataType resultType) {
  Class runtimeContextClass = Object.class;
  init(runtimeContextClass);

  final RelNode rel = fn.get();
  final RelDataType rowType = rel.getRowType();
  final List<Pair<Integer, String>> fields =
      Pair.zip(ImmutableIntList.identity(rowType.getFieldCount()),
          rowType.getFieldNames());
  final RelCollation collation =
      rel instanceof Sort
          ? ((Sort) rel).collation
          : RelCollations.EMPTY;
  RelRoot root = new RelRoot(rel, resultType, SqlKind.SELECT, fields,
      collation);

  if (timingTracer != null) {
    timingTracer.traceTime("end sql2rel");
  }

  final RelDataType jdbcType =
      makeStruct(rexBuilder.getTypeFactory(), resultType);
  fieldOrigins = Collections.nCopies(jdbcType.getFieldCount(), null);
  parameterRowType = rexBuilder.getTypeFactory().builder().build();

  // Structured type flattening, view expansion, and plugging in
  // physical storage.
  root = root.withRel(flattenTypes(root.rel, true));

  // Trim unused fields.
  root = trimUnusedFields(root);

  final List<Materialization> materializations = ImmutableList.of();
  final List<CalciteSchema.LatticeEntry> lattices = ImmutableList.of();
  root = optimize(root, materializations, lattices);

  if (timingTracer != null) {
    timingTracer.traceTime("end optimization");
  }

  return implement(root);
}
 
Example 17
Source File: GDRegistry.java    From GriefDefender with MIT License 4 votes vote down vote up
@Override
public <T> T createBuilder(Class<T> builderClass) throws IllegalArgumentException {
    final Supplier<?> supplier = BUILDER_SUPPLIERS.get(builderClass);
    checkArgument(supplier != null, "Could not find a Supplier for the provided builder class: " + builderClass.getCanonicalName());
    return (T) supplier.get();
}
 
Example 18
Source File: GDRegistry.java    From GriefDefender with MIT License 4 votes vote down vote up
@Override
public <T> T createBuilder(Class<T> builderClass) throws IllegalArgumentException {
    final Supplier<?> supplier = BUILDER_SUPPLIERS.get(builderClass);
    checkArgument(supplier != null, "Could not find a Supplier for the provided builder class: " + builderClass.getCanonicalName());
    return (T) supplier.get();
}
 
Example 19
Source File: ManagedChannelImpl.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
ManagedChannelImpl(
    AbstractManagedChannelImplBuilder<?> builder,
    ClientTransportFactory clientTransportFactory,
    BackoffPolicy.Provider backoffPolicyProvider,
    ObjectPool<? extends Executor> balancerRpcExecutorPool,
    Supplier<Stopwatch> stopwatchSupplier,
    List<ClientInterceptor> interceptors,
    final TimeProvider timeProvider) {
  this.target = checkNotNull(builder.target, "target");
  this.nameResolverFactory = builder.getNameResolverFactory();
  this.nameResolverParams = checkNotNull(builder.getNameResolverParams(), "nameResolverParams");
  this.nameResolver = getNameResolver(target, nameResolverFactory, nameResolverParams);

  //----begin----注册Consumer信息,设置注册对象----

  this.nameResolver.setRegistry(consumerServiceRegistry);
  this.nameResolver.setManagedChannel(this);

  //----end----注册Consumer信息,设置注册对象----

  this.timeProvider = checkNotNull(timeProvider, "timeProvider");
  maxTraceEvents = builder.maxTraceEvents;
  channelTracer = new ChannelTracer(
      logId, builder.maxTraceEvents, timeProvider.currentTimeNanos(),
      "Channel for '" + target + "'");
  channelLogger = new ChannelLoggerImpl(channelTracer, timeProvider);
  if (builder.loadBalancerFactory == null) {
    this.loadBalancerFactory = new AutoConfiguredLoadBalancerFactory();
  } else {
    this.loadBalancerFactory = builder.loadBalancerFactory;
  }
  this.executorPool = checkNotNull(builder.executorPool, "executorPool");
  this.balancerRpcExecutorPool = checkNotNull(balancerRpcExecutorPool, "balancerRpcExecutorPool");
  this.balancerRpcExecutorHolder = new ExecutorHolder(balancerRpcExecutorPool);
  this.executor = checkNotNull(executorPool.getObject(), "executor");
  this.delayedTransport = new DelayedClientTransport(this.executor, this.syncContext);
  this.delayedTransport.start(delayedTransportListener);
  this.backoffPolicyProvider = backoffPolicyProvider;
  this.transportFactory =
      new CallCredentialsApplyingTransportFactory(clientTransportFactory, this.executor);
  this.scheduledExecutorForBalancer =
      new ScheduledExecutorForBalancer(transportFactory.getScheduledExecutorService());
  this.retryEnabled = builder.retryEnabled && !builder.temporarilyDisableRetry;
  serviceConfigInterceptor = new ServiceConfigInterceptor(
      retryEnabled, builder.maxRetryAttempts, builder.maxHedgedAttempts);
  Channel channel = new RealChannel(nameResolver.getServiceAuthority());
  channel = ClientInterceptors.intercept(channel, serviceConfigInterceptor);
  if (builder.binlog != null) {
    channel = builder.binlog.wrapChannel(channel);
  }
  this.interceptorChannel = ClientInterceptors.intercept(channel, interceptors);
  this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatchSupplier");
  if (builder.idleTimeoutMillis == IDLE_TIMEOUT_MILLIS_DISABLE) {
    this.idleTimeoutMillis = builder.idleTimeoutMillis;
  } else {
    checkArgument(
        builder.idleTimeoutMillis
            >= AbstractManagedChannelImplBuilder.IDLE_MODE_MIN_TIMEOUT_MILLIS,
        "invalid idleTimeoutMillis %s", builder.idleTimeoutMillis);
    this.idleTimeoutMillis = builder.idleTimeoutMillis;
  }

  idleTimer = new Rescheduler(
      new IdleModeTimer(),
      syncContext,
      transportFactory.getScheduledExecutorService(),
      stopwatchSupplier.get());
  this.fullStreamDecompression = builder.fullStreamDecompression;
  this.decompressorRegistry = checkNotNull(builder.decompressorRegistry, "decompressorRegistry");
  this.compressorRegistry = checkNotNull(builder.compressorRegistry, "compressorRegistry");
  this.userAgent = builder.userAgent;

  this.channelBufferLimit = builder.retryBufferSize;
  this.perRpcBufferLimit = builder.perRpcBufferLimit;
  final class ChannelCallTracerFactory implements CallTracer.Factory {
    @Override
    public CallTracer create() {
      return new CallTracer(timeProvider);
    }
  }

  this.callTracerFactory = new ChannelCallTracerFactory();
  channelCallTracer = callTracerFactory.create();
  this.channelz = checkNotNull(builder.channelz);
  channelz.addRootChannel(this);


  //----begin----注册Consumer信息,调用注册方法----

  new Thread(registryRunnable, CLIENT_REGISTRY_THREAD_NAME).start();

  //----end----功能描述,调用注册方法----
}
 
Example 20
Source File: BaseController.java    From cloud-template with MIT License 3 votes vote down vote up
/**
 * Supplier是JDK8新特性
 * 特点:只有返回值,没有输入参数
 * 如:Supplier<User> user = User::new;
 * 此时并没有构造User对象,当调用`user.get()`方法才获取一个新的User构造对象
 * <p>
 * QueryPage 是封装分页条件的entity,如果没有指定默认查询所有
 */
public Map<String, Object> selectByPageNumSize(QueryPage page, Supplier<?> s) {
    PageHelper.startPage(page.getPageCode(), page.getPageSize());
    PageInfo<?> pageInfo = new PageInfo<>((List<?>) s.get());
    PageHelper.clearPage();
    return getData(pageInfo);
}