com.google.common.base.Supplier Java Examples

The following examples show how to use com.google.common.base.Supplier. 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: 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 #2
Source File: ProxyDetectorImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  proxySelectorSupplier = new Supplier<ProxySelector>() {
    @Override
    public ProxySelector get() {
      return proxySelector;
    }
  };
  proxyDetector = new ProxyDetectorImpl(proxySelectorSupplier, authenticator, null);
  int proxyPort = 1234;
  unresolvedProxy = InetSocketAddress.createUnresolved("10.0.0.1", proxyPort);
  proxyParmeters = new ProxyParameters(
      new InetSocketAddress(InetAddress.getByName(unresolvedProxy.getHostName()), proxyPort),
      NO_USER,
      NO_PW);
}
 
Example #3
Source File: OLAPValuesRel.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
/** Creates an OLAPValuesRel. */
public static OLAPValuesRel create(RelOptCluster cluster, final RelDataType rowType,
        final ImmutableList<ImmutableList<RexLiteral>> tuples) {
    final RelMetadataQuery mq = cluster.getMetadataQuery();
    final RelTraitSet traitSet = cluster.traitSetOf(OLAPRel.CONVENTION)
            .replaceIfs(RelCollationTraitDef.INSTANCE, new Supplier<List<RelCollation>>() {
                public List<RelCollation> get() {
                    return RelMdCollation.values(mq, rowType, tuples);
                }
            }).replaceIf(RelDistributionTraitDef.INSTANCE, new Supplier<RelDistribution>() {
                public RelDistribution get() {
                    return RelMdDistribution.values(rowType, tuples);
                }
            });
    return new OLAPValuesRel(cluster, rowType, tuples, traitSet);
}
 
Example #4
Source File: OLAPProjectRule.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public RelNode convert(final RelNode rel) {

    //  KYLIN-3281
    //  OLAPProjectRule can't normal working with projectRel[input=sortRel]
    final LogicalProject project = (LogicalProject) rel;
    final RelNode convertChild = convert(project.getInput(),
            project.getInput().getTraitSet().replace(OLAPRel.CONVENTION));
    final RelOptCluster cluster = convertChild.getCluster();
    final RelTraitSet traitSet = cluster.traitSet().replace(OLAPRel.CONVENTION)
            .replaceIfs(RelCollationTraitDef.INSTANCE, new Supplier<List<RelCollation>>() {
                public List<RelCollation> get() {
                    //  CALCITE-88
                    return RelMdCollation.project(cluster.getMetadataQuery(), convertChild, project.getProjects());
                }
            });
    return new OLAPProjectRel(convertChild.getCluster(), traitSet, convertChild, project.getProjects(),
            project.getRowType());
}
 
Example #5
Source File: ConfigStoreImpl.java    From qconfig with MIT License 6 votes vote down vote up
@PostConstruct
private void init() {
    configCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterAccess(10, TimeUnit.SECONDS)
            .recordStats()
            .build(new CacheLoader<VersionData<ConfigMeta>, ChecksumData<String>>() {
                @Override
                public ChecksumData<String> load(VersionData<ConfigMeta> configId) throws ConfigNotFoundException {
                    return loadConfig(configId);
                }
            });

    Metrics.gauge("configFile_notFound_cache_hitRate", new Supplier<Double>() {
        @Override
        public Double get() {
            return configCache.stats().hitRate();
        }
    });
}
 
Example #6
Source File: ObservableCombiner.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms a set of input observables with a function.
 *
 * @param inputs   The input observables.
 * @param function The function to apply to all of the inputs.
 * @param <I>      The type of all inputs values.
 * @param <O>      The type of the output values.
 * @return An observable which will reflect the combination of all inputs
 * with the given function. Changes in the output value will result
 * in calls to any callbacks registered with the output.
 */
static <I, O> Observable<O> transform(final List<? extends Observable<I>> inputs,
                                      final Function<List<I>, O> function)
{
    return new ObservableCombiner<>(inputs, new Supplier<O>()
    {
        @Override
        public O get()
        {
            ArrayList<I> deps = new ArrayList<>();
            for (Observable<? extends I> dependency : inputs)
            {
                deps.add(dependency.get());
            }
            return function.apply(deps);
        }
    });
}
 
Example #7
Source File: HelmFacetImpl.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Save an asset and create blob.
 *
 * @return blob content
 */
@Override
@Nullable
public Content saveAsset(final StorageTx tx,
                          final Asset asset,
                          final Supplier<InputStream> contentSupplier,
                          final Payload payload)
{
  try {
    if (payload instanceof Content) {
      AttributesMap contentAttributes = ((Content) payload).getAttributes();
      String contentType = payload.getContentType();
      return saveAsset(tx, asset, contentSupplier, contentType, contentAttributes);
    }
    return saveAsset(tx, asset, contentSupplier, null, null);
  }
  catch (IOException ex) {
    log.warn("Could not set blob {}", ex.getMessage(), ex);
    return null;
  }
}
 
Example #8
Source File: XceiverClientRatis.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<RaftClientReply> sendRequestAsync(
    ContainerCommandRequestProto request) {
  return TracingUtil.executeInNewSpan(
      "XceiverClientRatis." + request.getCmdType().name(),
      (Supplier<CompletableFuture<RaftClientReply>>) () -> {
        final ContainerCommandRequestMessage message
            = ContainerCommandRequestMessage.toMessage(
            request, TracingUtil.exportCurrentSpan());
        if (HddsUtils.isReadOnly(request)) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("sendCommandAsync ReadOnly {}", message);
          }
          return getClient().sendReadOnlyAsync(message);
        } else {
          if (LOG.isDebugEnabled()) {
            LOG.debug("sendCommandAsync {}", message);
          }
          return getClient().sendAsync(message);
        }

      }

  );
}
 
Example #9
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 #10
Source File: AutogenMediumTestsSuite.java    From deploymentmanager-autogen with Apache License 2.0 6 votes vote down vote up
Solution(File inputSpecFile) {
  name = relativePathFunction(ROOT, inputSpecFile);
  solutionFolder =
      new File(TESTDATA_PATH + relativePathFunction(ROOT, inputSpecFile.getParentFile()));
  goldenFolder = new File(solutionFolder, "golden");
  solutionPackage =
      Suppliers.memoize(
          new Supplier<SolutionPackage>() {
            @Override
            public SolutionPackage get() {
              try {
                DeploymentPackageInput.Builder input = DeploymentPackageInput.newBuilder();
                TextFormat.getParser()
                    .merge(
                        Files.asCharSource(inputSpecFile, StandardCharsets.UTF_8).read(),
                        input);
                return Autogen.getInstance()
                    .generateDeploymentPackage(
                        input.build(), SharedSupportFilesStrategy.INCLUDED);
              } catch (IOException e) {
                throw new RuntimeException(e);
              }
            }
          });
}
 
Example #11
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 #12
Source File: FairQueuingPacketScheduler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public FairQueuingPacketScheduler(
   NetworkClock clock,
   RateLimiter outputRateLimit,
   RateLimiters.Builder<? extends RateLimiter> queueRateLimiter,
   Supplier<? extends BlockingQueue<T>> queueSupplier,
   Supplier<? extends PacketScheduler.PacketDropHandler<? super T>> dropHandler,
   Supplier<? extends PacketScheduler.QueueStateHandler<? super T>> queueHandler,
   double lowWatermarkPercent,
   double highWatermarkPercent,
   boolean blocking
   ) {
   this.clock = clock;
   this.outputRateLimit = outputRateLimit;
   this.queueRateLimiter = queueRateLimiter;
   this.queueSupplier = queueSupplier;
   this.dropHandler = dropHandler;
   this.queueHandler = queueHandler;
   this.lowWatermarkPercent = lowWatermarkPercent;
   this.highWatermarkPercent = highWatermarkPercent;
   this.blocking = blocking;

   this.next = new AtomicInteger(0);
   this.available = new Semaphore(0);
   this.producers = new ArrayList<>();
}
 
Example #13
Source File: EnumerableDefaults.java    From Quicksql with MIT License 6 votes vote down vote up
/**
 * Returns elements of {@code outer} for which there is (semi-join) / is not (anti-semi-join)
 * a member of {@code inner} with a matching key. A specified
 * {@code EqualityComparer<TSource>} is used to compare keys.
 */
private static <TSource, TInner, TKey> Enumerable<TSource> semiEquiJoin_(
    final Enumerable<TSource> outer, final Enumerable<TInner> inner,
    final Function1<TSource, TKey> outerKeySelector,
    final Function1<TInner, TKey> innerKeySelector,
    final EqualityComparer<TKey> comparer,
    final boolean anti) {
  return new AbstractEnumerable<TSource>() {
    public Enumerator<TSource> enumerator() {
      // CALCITE-2909 Delay the computation of the innerLookup until the moment when we are sure
      // that it will be really needed, i.e. when the first outer enumerator item is processed
      final Supplier<Enumerable<TKey>> innerLookup = Suppliers.memoize(() ->
          comparer == null
              ? inner.select(innerKeySelector).distinct()
              : inner.select(innerKeySelector).distinct(comparer));

      final Predicate1<TSource> predicate = anti
          ? v0 -> !innerLookup.get().contains(outerKeySelector.apply(v0))
          : v0 -> innerLookup.get().contains(outerKeySelector.apply(v0));

      return EnumerableDefaults.where(outer.enumerator(), predicate);
    }
  };
}
 
Example #14
Source File: PictureTakerFactory.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
public static PictureTakerFactory create(Logger.Factory logFactory, MainThread mainExecutor,
                                         CameraCommandExecutor commandExecutor,
                                         ImageSaver.Builder imageSaverBuilder,
                                         FrameServer frameServer,
                                         RequestBuilder.Factory rootRequestBuilder,
                                         ManagedImageReader sharedImageReader,
                                         Supplier<OneCamera.PhotoCaptureParameters.Flash> flashMode)
{
    // When flash is ON, always use the ConvergedImageCaptureCommand which
    // performs the AF & AE precapture sequence.
    ImageCaptureCommand flashOnCommand = new ConvergedImageCaptureCommand(
            sharedImageReader, frameServer, rootRequestBuilder,
            CameraDevice.TEMPLATE_STILL_CAPTURE, CameraDevice.TEMPLATE_STILL_CAPTURE,
            Arrays.asList(rootRequestBuilder), true /* ae */, true /* af */);

    // When flash is OFF, wait for AF convergence, but not AE convergence
    // (which can be very slow).
    ImageCaptureCommand flashOffCommand = new ConvergedImageCaptureCommand(
            sharedImageReader, frameServer, rootRequestBuilder,
            CameraDevice.TEMPLATE_STILL_CAPTURE, CameraDevice.TEMPLATE_STILL_CAPTURE,
            Arrays.asList(rootRequestBuilder), false /* ae */, true /* af */);

    // When flash is AUTO, wait for AF & AE.
    // TODO OPTIMIZE If the last converged-AE state indicates that flash is
    // not necessary, then this could skip waiting for AE convergence.
    ImageCaptureCommand flashAutoCommand = new ConvergedImageCaptureCommand(
            sharedImageReader, frameServer, rootRequestBuilder,
            CameraDevice.TEMPLATE_STILL_CAPTURE, CameraDevice.TEMPLATE_STILL_CAPTURE,
            Arrays.asList(rootRequestBuilder), true /* ae */, true /* af */);

    ImageCaptureCommand flashBasedCommand = new FlashBasedPhotoCommand(logFactory, flashMode,
            flashOnCommand, flashAutoCommand, flashOffCommand);
    return new PictureTakerFactory(new PictureTakerImpl(mainExecutor, commandExecutor,
            imageSaverBuilder, flashBasedCommand));
}
 
Example #15
Source File: ControlModeSelector.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
public ControlModeSelector(
        Supplier<Boolean> hdrSetting,
        Supplier<FaceDetectMode> faceDetectMode,
        SupportedHardwareLevel supportedHardwareLevel)
{
    mHdrSetting = hdrSetting;
    mFaceDetectMode = faceDetectMode;
    mSupportedHardwareLevel = supportedHardwareLevel;
}
 
Example #16
Source File: OkHttpClientTransport.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Create a transport connected to a fake peer for test.
 */
@VisibleForTesting
OkHttpClientTransport(
    String userAgent,
    Executor executor,
    FrameReader frameReader,
    FrameWriter testFrameWriter,
    int nextStreamId,
    Socket socket,
    Supplier<Stopwatch> stopwatchFactory,
    @Nullable Runnable connectingCallback,
    SettableFuture<Void> connectedFuture,
    int maxMessageSize,
    int initialWindowSize,
    Runnable tooManyPingsRunnable,
    TransportTracer transportTracer) {
  address = null;
  this.maxMessageSize = maxMessageSize;
  this.initialWindowSize = initialWindowSize;
  defaultAuthority = "notarealauthority:80";
  this.userAgent = GrpcUtil.getGrpcUserAgent("okhttp", userAgent);
  this.executor = Preconditions.checkNotNull(executor, "executor");
  serializingExecutor = new SerializingExecutor(executor);
  this.testFrameReader = Preconditions.checkNotNull(frameReader, "frameReader");
  this.testFrameWriter = Preconditions.checkNotNull(testFrameWriter, "testFrameWriter");
  this.socket = Preconditions.checkNotNull(socket, "socket");
  this.nextStreamId = nextStreamId;
  this.stopwatchFactory = stopwatchFactory;
  this.connectionSpec = null;
  this.connectingCallback = connectingCallback;
  this.connectedFuture = Preconditions.checkNotNull(connectedFuture, "connectedFuture");
  this.proxy = null;
  this.tooManyPingsRunnable =
      Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
  this.maxInboundMetadataSize = Integer.MAX_VALUE;
  this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
  initTransportTracer();
}
 
Example #17
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 #18
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 #19
Source File: PushConsumerImpl.java    From qmq with Apache License 2.0 5 votes vote down vote up
PushConsumerImpl(String subject, String group, RegistParam param) {
    super(param.getExecutor(), param.getMessageListener());
    this.consumeParam = new ConsumeParam(subject, group, param);

    String[] values = {subject, group};
    Metrics.gauge("qmq_pull_buffer_size", SUBJECT_GROUP_ARRAY, values, new Supplier<Double>() {
        @Override
        public Double get() {
            return (double) messageBuffer.size();
        }
    });
    this.createToHandleTimer = Metrics.timer("qmq_pull_createToHandle_timer", SUBJECT_GROUP_ARRAY, values);
    this.handleTimer = Metrics.timer("qmq_pull_handle_timer", SUBJECT_GROUP_ARRAY, values);
    this.handleFailCounter = Metrics.counter("qmq_pull_handleFail_count", SUBJECT_GROUP_ARRAY, values);
}
 
Example #20
Source File: RequestTemplate.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
/**
 * Attaches the given value to all derived RequestBuilders. Note that the
 * value is polled when each new RequestBuilder is created.
 */
public <T> RequestTemplate setParam(CaptureRequest.Key<T> key,
                                    Supplier<T> value)
{
    mParameters.add(new Parameter<T>(key, value));
    return this;
}
 
Example #21
Source File: HubAttributesService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Attribute<T> computed(Class<T> type, String name, Supplier<T> compute) {
   synchronized (attributes) {
      Attribute<T> existing = (Attribute<T>)attributes.get(name);
      if (existing != null) {
         return existing;
      }

      AttributeImpl<?> attr = new ComputedAttribute<T>(type, name, compute);
      attributes.put(name, attr);

      return (Attribute<T>)attr;
   }
}
 
Example #22
Source File: PrometheusClient.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Supplier<Map<String, Object>> metricsSupplier(final JsonCodec<Map<String, Object>> metricsCodec, final URI metadataUri)
{
    return () -> {
        try {
            byte[] json = getHttpResponse(metadataUri).bytes();
            Map<String, Object> metrics = metricsCodec.fromJson(json);
            return metrics;
        }
        catch (IOException | URISyntaxException e) {
            throw new UncheckedIOException((IOException) e);
        }
    };
}
 
Example #23
Source File: ExampleClient.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Supplier<Map<String, Map<String, ExampleTable>>> schemasSupplier(final JsonCodec<Map<String, List<ExampleTable>>> catalogCodec, final URI metadataUri)
{
    return () -> {
        try {
            return lookupSchemas(metadataUri, catalogCodec);
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    };
}
 
Example #24
Source File: HubAttributesService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Attribute<List<T>> computedList(Class<T> contained, String name, Supplier<List<T>> compute) {
   synchronized (attributes) {
      Attribute<List<T>> existing = (Attribute<List<T>>)attributes.get(name);
      if (existing != null) {
         return existing;
      }

      @SuppressWarnings("rawtypes")
      AttributeImpl<?> attr = new ComputedAttribute(List.class, name, compute);
      attributes.put(name, attr);

      return (Attribute<List<T>>)attr;
   }
}
 
Example #25
Source File: HubAttributesService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <K,V> Attribute<Map<K,V>> computedMap(Class<K> key, Class<V> val, String name, Supplier<Map<K,V>> compute) {
   synchronized (attributes) {
      Attribute<Map<K,V>> existing = (Attribute<Map<K,V>>)attributes.get(name);
      if (existing != null) {
         return existing;
      }

      @SuppressWarnings("rawtypes")
      AttributeImpl<?> attr = new ComputedAttribute(Map.class, name, compute);
      attributes.put(name, attr);

      return (Attribute<Map<K,V>>)attr;
   }
}
 
Example #26
Source File: FlashBasedPhotoCommand.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
FlashBasedPhotoCommand(Logger.Factory logFactory,
                       Supplier<OneCamera.PhotoCaptureParameters.Flash> flashMode,
                       ImageCaptureCommand flashOnCommand,
                       ImageCaptureCommand flashAutoCommand,
                       ImageCaptureCommand flashOffCommand)
{
    mLog = logFactory.create(new Log.Tag("FlashBasedPhotoCmd"));
    mFlashMode = flashMode;
    mFlashOnCommand = flashOnCommand;
    mFlashAutoCommand = flashAutoCommand;
    mFlashOffCommand = flashOffCommand;
}
 
Example #27
Source File: ExtensionPointMap.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * Call the extension point(s) corresponding to the given id
 * <p>
 * This iteration was isolated here to protect against ConcurrentModificationException using PluginRegistry's lock
 *
 * @param log    log channel to pass to extension point call
 * @param id     the id of the extension point interface
 * @param object object to pass to extension point call
 */
public void callExtensionPoint( ILogChannel log, String id, Object object ) throws HopException {
  lock.readLock().lock();
  try {
    if ( extensionPointPluginMap.containsRow( id ) && !extensionPointPluginMap.rowMap().get( id ).values().isEmpty() ) {
      for ( Supplier<IExtensionPoint> extensionPoint : extensionPointPluginMap.row( id ).values() ) {
        extensionPoint.get().callExtensionPoint( log, object );
      }
    }
  } finally {
    lock.readLock().unlock();
  }
}
 
Example #28
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 #29
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 #30
Source File: ArrayTable.java    From Quicksql with MIT License 5 votes vote down vote up
/** Creates an ArrayTable. */
ArrayTable(Type elementType, RelProtoDataType protoRowType,
    Supplier<Content> supplier) {
  super(elementType);
  this.protoRowType = protoRowType;
  this.supplier = supplier;
}