Java 类com.google.common.base.Suppliers 实例源码

项目:guava-mock    文件:CallablesTest.java   
@GwtIncompatible // threads
public void testRenaming_exceptionalReturn() throws Exception {
  String oldName = Thread.currentThread().getName();
  final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
  class MyException extends Exception {}
  Callable<Void> callable = new Callable<Void>() {
    @Override public Void call() throws Exception {
      assertEquals(Thread.currentThread().getName(), newName.get());
      throw new MyException();
    }
  };
  try {
    Callables.threadRenaming(callable, newName).call();
    fail();
  } catch (MyException expected) {}
  assertEquals(oldName, Thread.currentThread().getName());
}
项目:guava-mock    文件:CallablesTest.java   
@GwtIncompatible // threads

  public void testRenaming_noPermissions() throws Exception {
    System.setSecurityManager(new SecurityManager() {
      @Override public void checkAccess(Thread t) {
        throw new SecurityException();
      }
      @Override public void checkPermission(Permission perm) {
        // Do nothing so we can clear the security manager at the end
      }
    });
    try {
      final String oldName = Thread.currentThread().getName();
      Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
      Callable<Void> callable = new Callable<Void>() {
        @Override public Void call() throws Exception {
          assertEquals(Thread.currentThread().getName(), oldName);
          return null;
        }
      };
      Callables.threadRenaming(callable, newName).call();
      assertEquals(oldName, Thread.currentThread().getName());
    } finally {
      System.setSecurityManager(null);
    }
  }
项目:ArchUnit    文件:DomainObjectCreationContext.java   
private <T> Supplier<Set<T>> newAccessSupplier(final JavaClass owner, final Function<JavaClass, Set<T>> doWithEachClass) {

                return Suppliers.memoize(new Supplier<Set<T>>() {
                    @Override
                    public Set<T> get() {
                        ImmutableSet.Builder<T> result = ImmutableSet.builder();
                        for (final JavaClass javaClass : getPossibleTargetClassesForAccess()) {
                            result.addAll(doWithEachClass.apply(javaClass));
                        }
                        return result.build();
                    }

                    private Set<JavaClass> getPossibleTargetClassesForAccess() {
                        return ImmutableSet.<JavaClass>builder()
                                .add(owner)
                                .addAll(owner.getAllSubClasses())
                                .build();
                    }
                });
            }
项目:ArchUnit    文件:JavaClass.java   
void completeMembers(final ImportContext context) {
    fields = context.createFields(this);
    methods = context.createMethods(this);
    constructors = context.createConstructors(this);
    staticInitializer = context.createStaticInitializer(this);
    codeUnits = ImmutableSet.<JavaCodeUnit>builder()
            .addAll(methods).addAll(constructors).addAll(staticInitializer.asSet())
            .build();
    members = ImmutableSet.<JavaMember>builder()
            .addAll(fields)
            .addAll(methods)
            .addAll(constructors)
            .build();
    this.annotations = Suppliers.memoize(new Supplier<Map<String, JavaAnnotation>>() {
        @Override
        public Map<String, JavaAnnotation> get() {
            return context.createAnnotations(JavaClass.this);
        }
    });
}
项目:ArchUnit    文件:ClassFileImporterTest.java   
@Test
public void imports_shadowed_and_superclass_field_access() throws Exception {
    ImportedClasses classes = classesIn("testexamples/hierarchicalfieldaccess");
    JavaClass classThatAccessesFieldOfSuperClass = classes.get(AccessToSuperAndSubClassField.class);
    JavaClass superClassWithAccessedField = classes.get(SuperClassWithAccessedField.class);
    JavaClass subClassWithAccessedField = classes.get(SubClassWithAccessedField.class);

    Set<JavaFieldAccess> accesses = classThatAccessesFieldOfSuperClass.getFieldAccessesFromSelf();

    assertThat(accesses).hasSize(2);
    JavaField field = superClassWithAccessedField.getField("field");
    FieldAccessTarget expectedSuperClassFieldAccess = new FieldAccessTargetBuilder()
            .withOwner(subClassWithAccessedField)
            .withName(field.getName())
            .withType(field.getType())
            .withField(Suppliers.ofInstance(Optional.of(field)))
            .build();
    assertThatAccess(getOnly(accesses, "field", GET))
            .isFrom("accessSuperClassField")
            .isTo(expectedSuperClassFieldAccess)
            .inLineNumber(5);
    assertThatAccess(getOnly(accesses, "maskedField", GET))
            .isFrom("accessSubClassField")
            .isTo(subClassWithAccessedField.getField("maskedField"))
            .inLineNumber(9);
}
项目:g-suite-identity-sync    文件:GSuiteGroupAuthorizationFilter.java   
public GSuiteGroupAuthorizationFilter(final GSuiteDirectoryService gsuiteDirService, AppConfiguration config) {
    this.config = config;
    this.externalAccountsCache = Suppliers.memoizeWithExpiration(
            () -> {
                String allowGroup = config.getExternalAccountsGroup();
                Set<String> result = Collections.emptySet();
                try {
                    GroupMembership membership = gsuiteDirService.getGroupMembers(allowGroup);
                    result = membership.getMembers() == null ? Collections.emptySet()
                    : membership.getMembers().stream().map(m -> m.getEmail()).collect(Collectors.toSet());
                } catch (ResourceNotFoundException e) {
                    log.warn("Group for external accounts {} does not exists", allowGroup);
                }
                return result;
            }, 15, TimeUnit.MINUTES);
}
项目:athena    文件:DefaultTopology.java   
/**
 * Creates a topology descriptor attributed to the specified provider.
 *
 * @param providerId        identity of the provider
 * @param description       data describing the new topology
 * @param broadcastFunction broadcast point function
 */
public DefaultTopology(ProviderId providerId, GraphDescription description,
                       Function<ConnectPoint, Boolean> broadcastFunction) {
    super(providerId);
    this.broadcastFunction = broadcastFunction;
    this.time = description.timestamp();
    this.creationTime = description.creationTime();

    // Build the graph
    this.graph = new DefaultTopologyGraph(description.vertexes(),
                                          description.edges());

    this.clusterResults = Suppliers.memoize(() -> searchForClusters());
    this.clusters = Suppliers.memoize(() -> buildTopologyClusters());

    this.clusterIndexes = Suppliers.memoize(() -> buildIndexes());

    this.hopCountWeight = new HopCountLinkWeight(graph.getVertexes().size());
    this.broadcastSets = Suppliers.memoize(() -> buildBroadcastSets());
    this.infrastructurePoints = Suppliers.memoize(() -> findInfrastructurePoints());
    this.computeCost = Math.max(0, System.nanoTime() - time);
}
项目:googles-monorepo-demo    文件:CallablesTest.java   
@GwtIncompatible // threads
public void testRenaming_exceptionalReturn() throws Exception {
  String oldName = Thread.currentThread().getName();
  final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
  class MyException extends Exception {}
  Callable<Void> callable = new Callable<Void>() {
    @Override public Void call() throws Exception {
      assertEquals(Thread.currentThread().getName(), newName.get());
      throw new MyException();
    }
  };
  try {
    Callables.threadRenaming(callable, newName).call();
    fail();
  } catch (MyException expected) {}
  assertEquals(oldName, Thread.currentThread().getName());
}
项目:googles-monorepo-demo    文件:CallablesTest.java   
@GwtIncompatible // threads

  public void testRenaming_noPermissions() throws Exception {
    System.setSecurityManager(new SecurityManager() {
      @Override public void checkAccess(Thread t) {
        throw new SecurityException();
      }
      @Override public void checkPermission(Permission perm) {
        // Do nothing so we can clear the security manager at the end
      }
    });
    try {
      final String oldName = Thread.currentThread().getName();
      Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
      Callable<Void> callable = new Callable<Void>() {
        @Override public Void call() throws Exception {
          assertEquals(Thread.currentThread().getName(), oldName);
          return null;
        }
      };
      Callables.threadRenaming(callable, newName).call();
      assertEquals(oldName, Thread.currentThread().getName());
    } finally {
      System.setSecurityManager(null);
    }
  }
项目:StubbornJava    文件:SuppliersExamples.java   
public static void main(String[] args) throws InterruptedException {
    // {{start:memoize}}
    log.info("Memoized");
    Supplier<String> memoized = Suppliers.memoize(SuppliersExamples::helloWorldSupplier);
    log.info(memoized.get());
    log.info(memoized.get());
    // {{end:memoize}}

    // {{start:memoizeWithExpiration}}
    log.info("Memoized with Expiration");
    Supplier<String> memoizedExpiring = Suppliers.memoizeWithExpiration(
        SuppliersExamples::helloWorldSupplier, 50, TimeUnit.MILLISECONDS);
    log.info(memoizedExpiring.get());
    log.info(memoizedExpiring.get());
    log.info("sleeping");
    TimeUnit.MILLISECONDS.sleep(100);
    log.info(memoizedExpiring.get());
    log.info(memoizedExpiring.get());
    log.info("sleeping");
    TimeUnit.MILLISECONDS.sleep(100);
    log.info(memoizedExpiring.get());
    log.info(memoizedExpiring.get());
    // {{end:memoizeWithExpiration}}
}
项目:nifi-minifi    文件:ConfigService.java   
public ConfigService(List<ConfigurationProvider> configurationProviders, Authorizer authorizer, long maximumCacheSize, long cacheTtlMillis) {
    this.authorizer = authorizer;
    this.objectMapper = new ObjectMapper();
    if (configurationProviders == null || configurationProviders.size() == 0) {
        throw new IllegalArgumentException("Expected at least one configuration provider");
    }
    this.configurationProviderInfo = Suppliers.memoizeWithExpiration(() -> initContentTypeInfo(configurationProviders), cacheTtlMillis, TimeUnit.MILLISECONDS);
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (maximumCacheSize >= 0) {
        cacheBuilder = cacheBuilder.maximumSize(maximumCacheSize);
    }
    if (cacheTtlMillis >= 0) {
        cacheBuilder = cacheBuilder.refreshAfterWrite(cacheTtlMillis, TimeUnit.MILLISECONDS);
    }
    this.configurationCache = cacheBuilder
            .build(new CacheLoader<ConfigurationProviderKey, ConfigurationProviderValue>() {
                @Override
                public ConfigurationProviderValue load(ConfigurationProviderKey key) throws Exception {
                    return initConfigurationProviderValue(key);
                }
            });
}
项目:rules_closure    文件:WebfilesValidatorTest.java   
@Test
public void badCssUrl_resultsInError() throws Exception {
  save(fs.getPath("/fs/path/index.html"), "<link rel=\"stylesheet\" href=\"index.css\">");
  save(fs.getPath("/fs/path/index.css"), "body { background: url(hello.jpg); }");
  assertThat(
          validator.validate(
              Webfiles.newBuilder()
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.html")
                      .setWebpath("/web/path/index.html")
                      .build())
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.css")
                      .setWebpath("/web/path/index.css")
                      .build())
                  .build(),
              ImmutableList.<Webfiles>of(),
              Suppliers.ofInstance(ImmutableList.<Webfiles>of())))
      .isNotEmpty();
}
项目:Mastering-Mesos    文件:AttributeAggregate.java   
@VisibleForTesting
static AttributeAggregate create(
    final Supplier<Iterable<IScheduledTask>> taskSupplier,
    final AttributeStore attributeStore) {

  final Function<String, Iterable<IAttribute>> getHostAttributes =
      host -> {
        // Note: this assumes we have access to attributes for hosts where all active tasks
        // reside.
        requireNonNull(host);
        return attributeStore.getHostAttributes(host).get().getAttributes();
      };

  return create(Suppliers.compose(
      tasks -> FluentIterable.from(tasks)
          .transform(Tasks::scheduledToSlaveHost)
          .transformAndConcat(getHostAttributes),
      taskSupplier));
}
项目:rules_closure    文件:WebfilesValidatorTest.java   
@Test
public void absoluteReferenceToImgInSrcs_printsError() throws Exception {
  save(fs.getPath("/fs/path/index.html"), "<img src=\"/a/b/c\">");
  assertThat(
          validator.validate(
              Webfiles.newBuilder()
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.html")
                      .setWebpath("/web/path/index.html")
                      .build())
                  .build(),
              ImmutableList.<Webfiles>of(),
              Suppliers.ofInstance(ImmutableList.<Webfiles>of())))
      .containsEntry(
          WebfilesValidator.ABSOLUTE_PATH_ERROR,
          "/fs/path/index.html: Please use relative path for asset: /a/b/c");
}
项目:rules_closure    文件:WebfilesValidatorTest.java   
@Test
public void relativeReferenceToUndeclaredAsset_printsError() throws Exception {
  save(fs.getPath("/fs/path/index.html"), "<img src=\"hello.jpg\">");
  save(fs.getPath("/fs/path/hello.jpg"), "oh my goth");
  assertThat(
          validator.validate(
              Webfiles.newBuilder()
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.html")
                      .setWebpath("/web/path/index.html")
                      .build())
                  .build(),
              ImmutableList.<Webfiles>of(),
              Suppliers.ofInstance(ImmutableList.<Webfiles>of())))
      .containsEntry(
          WebfilesValidator.STRICT_DEPENDENCIES_ERROR,
          "/fs/path/index.html: Referenced hello.jpg (/web/path/hello.jpg)"
              + " without depending on a web_library() rule providing it");
}
项目:metasfresh-webui-api    文件:TUPackingInfo.java   
TUPackingInfo(final I_M_HU tuHU)
{
    Check.assumeNotNull(tuHU, "Parameter tuHU is not null");
    this.tuHU = tuHU;

    huProductStorageSupplier = Suppliers.memoize(() -> {
        final List<IHUProductStorage> productStorages = Services.get(IHandlingUnitsBL.class)
                .getStorageFactory()
                .getStorage(tuHU)
                .getProductStorages();
        if (productStorages.size() == 1)
        {
            return productStorages.get(0);
        }
        else
        {
            return null;
        }
    });
}
项目:metasfresh-webui-api    文件:AggregatedTUPackingInfo.java   
public AggregatedTUPackingInfo(final I_M_HU aggregatedTU)
{
    this.aggregatedTU = aggregatedTU;
    huProductStorageSupplier = Suppliers.memoize(() -> {
        final List<IHUProductStorage> productStorages = Services.get(IHandlingUnitsBL.class)
                .getStorageFactory()
                .getStorage(aggregatedTU)
                .getProductStorages();
        if (productStorages.size() == 1)
        {
            return productStorages.get(0);
        }
        else
        {
            return null;
        }
    });
}
项目:examples-java    文件:EnrichmentExample.java   
public EnrichmentExample(StorageFactory storageFactory) {
    this.storageFactory = storageFactory;
    final UserNameLookup userNameLookup = new UserNameLookup();
    final EventEnricher enricher = EventEnricher
            .newBuilder()
            .addFieldEnrichment(UserId.class, PersonName.class, userNameLookup)
            .build();

    final Supplier<StorageFactory> storageFactorySupplier = Suppliers.ofInstance(storageFactory);
    final EventBus eventBus = EventBus.newBuilder()
                                      .setStorageFactory(storageFactorySupplier.get())
                                      .setEnricher(enricher)
                                      .build();
    eventBus.subscribe(userNameLookup);
    eventBus.subscribe(new Printer());

    this.boundedContext = BoundedContext.newBuilder()
                                        .setEventBus(eventBus)
                                        .setStorageFactorySupplier(storageFactorySupplier)
                                        .build();
}
项目:turbine    文件:BytecodeBoundClass.java   
public BytecodeBoundClass(
    ClassSymbol sym,
    final Supplier<byte[]> bytes,
    Env<ClassSymbol, BytecodeBoundClass> env,
    String jarFile) {
  this.sym = sym;
  this.env = env;
  this.jarFile = jarFile;
  this.classFile =
      Suppliers.memoize(
          new Supplier<ClassFile>() {
            @Override
            public ClassFile get() {
              ClassFile cf = ClassReader.read(jarFile + "!" + sym, bytes.get());
              verify(
                  cf.name().equals(sym.binaryName()),
                  "expected class data for %s, saw %s instead",
                  sym.binaryName(),
                  cf.name());
              return cf;
            }
          });
}
项目:turbine    文件:WildImportIndex.java   
/** Creates an import index for the given top-level environment. */
public static WildImportIndex create(
    CanonicalSymbolResolver importResolver,
    final TopLevelIndex cpi,
    ImmutableList<ImportDecl> imports) {
  ImmutableList.Builder<Supplier<ImportScope>> packageScopes = ImmutableList.builder();
  for (final ImportDecl i : imports) {
    if (i.wild()) {
      packageScopes.add(
          Suppliers.memoize(
              new Supplier<ImportScope>() {
                @Override
                public ImportScope get() {
                  if (i.stat()) {
                    return staticOnDemandImport(cpi, i, importResolver);
                  } else {
                    return onDemandImport(cpi, i, importResolver);
                  }
                }
              }));
    }
  }
  return new WildImportIndex(packageScopes.build());
}
项目:emodb    文件:DataStoreJobStatusDAO.java   
@Inject
public DataStoreJobStatusDAO(@JobsTableName final Supplier<String> tableNameSupplier,
                             @JobsTablePlacement final String placement,
                             DataStore dataStore) {
    _dataStore = dataStore;

    _tableNameSupplier = Suppliers.memoize(
        new Supplier<String>() {
            @Override
            public String get() {
                // Lazily ensure the table exists on the first use.
                String tableName = tableNameSupplier.get();
                if (!_dataStore.getTableExists(tableName)) {
                    _dataStore.createTable(tableName,
                            new TableOptionsBuilder().setPlacement(placement).build(),
                            ImmutableMap.<String, String>of(),
                            new AuditBuilder().setLocalHost().setComment("create table").build()
                    );
                }
                return tableName;
            }
        }
    );
}
项目:emodb    文件:TestDefaultJobService.java   
@Test
public void testRunOneJob() throws Exception {
    _jobHandlerRegistry.addHandler(new TestJobType(), Suppliers.<JobHandler<TestRequest, TestResult>>ofInstance(
            new JobHandler<TestRequest, TestResult>() {
                @Override
                public TestResult run(TestRequest request)
                        throws Exception {
                    return new TestResult(Collections.nCopies(request.getValue2(), request.getValue1()));
                }
            }));

    JobIdentifier<TestRequest, TestResult> jobId = submitJob(new TestRequest("hello", 3));
    runJob(jobId, true, true);

    JobStatus<TestRequest, TestResult> status = _service.getJobStatus(jobId);
    assertEquals(status.getStatus(), JobStatus.Status.FINISHED);
    assertEquals(status.getRequest(), new TestRequest("hello", 3));
    assertEquals(status.getResult(), new TestResult(ImmutableList.of("hello", "hello", "hello")));
}
项目:emodb    文件:TestDefaultJobService.java   
@Test
public void testRunOneJobWithFailure() {
    _jobHandlerRegistry.addHandler(new TestJobType(), Suppliers.<JobHandler<TestRequest, TestResult>>ofInstance(
            new JobHandler<TestRequest, TestResult>() {
                @Override
                public TestResult run(TestRequest request)
                        throws Exception {
                    throw new IllegalArgumentException("Your argument is invalid");
                }
            }));

    JobIdentifier<TestRequest, TestResult> jobId = submitJob(new TestRequest("hello", 3));
    runJob(jobId, true, true);

    JobStatus<TestRequest, TestResult> status = _service.getJobStatus(jobId);
    assertEquals(status.getStatus(), JobStatus.Status.FAILED);
    assertEquals(status.getRequest(), new TestRequest("hello", 3));
    assertNull(status.getResult());
    assertEquals(status.getErrorMessage(), "Your argument is invalid");
}
项目:emodb    文件:TestDefaultJobService.java   
@Test
public void testRunOneJobNonLocal() {
    _jobHandlerRegistry.addHandler(new TestJobType(), Suppliers.<JobHandler<TestRequest, TestResult>>ofInstance(
            new JobHandler<TestRequest, TestResult>() {
                @Override
                public TestResult run(TestRequest request)
                        throws Exception {
                    return notOwner();
                }
            }));

    JobIdentifier<TestRequest, TestResult> jobId = submitJob(new TestRequest("hello", 3));

    // Job will run, but it won't be local so it won't be acked.
    runJob(jobId, true, false);

    // Job won't run because it's known to be running on a non-local server.
    runJob(jobId, false, false);
}
项目:emodb    文件:DedupQueueTest.java   
@Test
public void testPollSkipsEmptyChannels() {
    EventReaderDAO readerDao = mock(EventReaderDAO.class);
    EventStore eventStore = new DefaultEventStore(readerDao, mock(EventWriterDAO.class), new AstyanaxEventIdSerializer(), new MockClaimStore());

    DedupQueue q = new DedupQueue("test-queue", "read", "write",
            mock(QueueDAO.class), eventStore, Suppliers.ofInstance(true), mock(ScheduledExecutorService.class), getPersistentSortedQueueFactory(),
            mock(MetricRegistry.class));
    q.startAndWait();

    // The first poll checks the read channel, find it empty, checks the write channel.
    q.poll(Duration.standardSeconds(30), new SimpleEventSink(10));
    verify(readerDao).readNewer(eq("read"), Matchers.<EventSink>any());
    verify(readerDao).readNewer(eq("write"), Matchers.<EventSink>any());
    verifyNoMoreInteractions(readerDao);

    reset(readerDao);

    // Subsequent polls w/in a short window skips the poll operations.
    q.poll(Duration.standardSeconds(30), new SimpleEventSink(10));
    verifyNoMoreInteractions(readerDao);
}
项目:emodb    文件:DedupQueueTest.java   
@Test
public void testPeekChecksAllChannels() {
    EventReaderDAO readerDao = mock(EventReaderDAO.class);
    EventStore eventStore = new DefaultEventStore(readerDao, mock(EventWriterDAO.class), new AstyanaxEventIdSerializer(), new MockClaimStore());

    DedupQueue q = new DedupQueue("test-queue", "read", "write",
            mock(QueueDAO.class), eventStore, Suppliers.ofInstance(true), mock(ScheduledExecutorService.class), getPersistentSortedQueueFactory(),
            mock(MetricRegistry.class));
    q.startAndWait();

    // The first peek checks the read channel, find it empty, checks the write channel.
    q.peek(new SimpleEventSink(10));
    verify(readerDao).readAll(eq("read"), Matchers.<EventSink>any(), (Date) Matchers.isNull());
    verify(readerDao).readNewer(eq("write"), Matchers.<EventSink>any());
    verifyNoMoreInteractions(readerDao);

    reset(readerDao);

    // Subsequent peeks w/in a short window still peek the read channel, skip polling the write channel.
    q.peek(new SimpleEventSink(10));
    verify(readerDao).readAll(eq("read"), Matchers.<EventSink>any(), (Date) Matchers.isNull());
    verifyNoMoreInteractions(readerDao);
}
项目:rules_closure    文件:WebfilesValidatorTest.java   
@Test
public void relativeReferenceToImgInDirectDeps_isAllowed() throws Exception {
  save(fs.getPath("/fs/path/index.html"), "<img src=\"hello.jpg\">");
  save(fs.getPath("/fs/path/hello.jpg"), "oh my goth");
  assertThat(
          validator.validate(
              Webfiles.newBuilder()
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.html")
                      .setWebpath("/web/path/index.html")
                      .build())
                  .build(),
              ImmutableList.of(
                  Webfiles.newBuilder()
                      .addSrc(WebfilesSource.newBuilder()
                          .setPath("/fs/path/hello.jpg")
                          .setWebpath("/web/path/hello.jpg")
                          .build())
                      .build()),
              Suppliers.ofInstance(ImmutableList.<Webfiles>of())))
      .isEmpty();
}
项目:emodb    文件:AstyanaxTableDAO.java   
private AstyanaxStorage newAstyanaxStorage(long uuid, int shardsLog2, boolean readsAllowed, final String placement,
                                           final String table) {
    // Delay resolving the placement until it's used so we can manipulate table metadata for placements that
    // don't replicate to the current data center.
    return new AstyanaxStorage(uuid, shardsLog2, readsAllowed, placement, Suppliers.memoize(new Supplier<Placement>() {
        @Override
        public Placement get() {
            try {
                return _placementCache.get(placement);
            } catch (UnknownPlacementException e) {
                // Add table information to the exception
                e.setTable(table);
                throw e;
            }
        }
    }));
}
项目:rules_closure    文件:WebfilesValidatorTest.java   
@Test
public void invalidHtml_doesntCare() throws Exception {
  // jsoup is too strict about html syntax errors to be useful for polymer and it doesn't provide
  // a very friendly way to report these errors.
  save(fs.getPath("/fs/path/index.html"), "< ");
  assertThat(
          validator.validate(
              Webfiles.newBuilder()
                  .addSrc(
                      WebfilesSource.newBuilder()
                          .setPath("/fs/path/index.html")
                          .setWebpath("/web/path/index.html")
                          .build())
                  .build(),
              ImmutableList.<Webfiles>of(),
              Suppliers.ofInstance(ImmutableList.<Webfiles>of())))
      .isEmpty();
}
项目:emodb    文件:QueueModule.java   
@Override
protected void configure() {
    bind(CassandraFactory.class).asEagerSingleton();

    // Event Store
    bind(ChannelConfiguration.class).to(QueueChannelConfiguration.class).asEagerSingleton();
    bind(CuratorFramework.class).annotatedWith(EventStoreZooKeeper.class).to(Key.get(CuratorFramework.class, QueueZooKeeper.class));
    bind(HostDiscovery.class).annotatedWith(EventStoreHostDiscovery.class).to(Key.get(HostDiscovery.class, DedupQueueHostDiscovery.class));
    bind(DedupEventStoreChannels.class).toInstance(DedupEventStoreChannels.isolated("__dedupq_write:", "__dedupq_read:"));
    bind(new TypeLiteral<Supplier<Boolean>>() {}).annotatedWith(DedupEnabled.class).toInstance(Suppliers.ofInstance(true));
    install(new EventStoreModule("bv.emodb.queue", _metricRegistry));

    // Bind the Queue instance that the rest of the application will consume
    bind(QueueService.class).to(DefaultQueueService.class).asEagerSingleton();
    expose(QueueService.class);

    // Bind the DedupQueue instance that the rest of the application will consume
    bind(DedupQueueService.class).to(DefaultDedupQueueService.class).asEagerSingleton();
    expose(DedupQueueService.class);

}
项目:emodb    文件:SorCqlSettingsTaskTest.java   
@Test
public void testTask()
        throws Exception {
    CqlDriverConfiguration cqlDriverConfig = new CqlDriverConfiguration();
    int defaultFetchSize = cqlDriverConfig.getSingleRowFetchSize();
    SorCqlSettingsTask task =
            new SorCqlSettingsTask(mock(TaskRegistry.class), cqlDriverConfig, Suppliers.ofInstance(true),
                    Suppliers.ofInstance(true));

    // Verify the fetch size is the same as default of 10
    assertEquals(cqlDriverConfig.getSingleRowFetchSize(), defaultFetchSize, "Fetch size should be the default.");

    // Try modifying fetch size and prefetch limit
    int expectedFetchSize = 15;
    int expectedPrefetchLimit = 5;
    task.execute(ImmutableMultimap.<String, String>builder()
            .put("fetchSize", Integer.toString(expectedFetchSize))
            .put("prefetchLimit", Integer.toString(expectedPrefetchLimit))
            .build(), new PrintWriter(System.out));
    // Verify the fetch size is changed to 15 and the prefetch limit is changed to 5
    assertEquals(cqlDriverConfig.getSingleRowFetchSize(), expectedFetchSize, "Fetch size should be changed.");
    assertEquals(cqlDriverConfig.getSingleRowPrefetchLimit(), expectedPrefetchLimit, "Prefetch limit should be changed.");
}
项目:emodb    文件:StandardStashReader.java   
@VisibleForTesting
StandardStashReader(URI stashRoot, AmazonS3 s3, long refreshLatestMs) {
    super(stashRoot, s3);

    Supplier<String> s3LatestRootSupplier = new Supplier<String>() {
        @Override
        public String get() {
            String latest = readLatestStash();
            return String.format("%s/%s", _rootPath, latest);
        }
    };

    if (refreshLatestMs > 0) {
        // Cache the latest stash directory and periodically recheck
        _latestRootSupplier = Suppliers.memoizeWithExpiration(s3LatestRootSupplier, refreshLatestMs, TimeUnit.MILLISECONDS);
    } else {
        _latestRootSupplier = s3LatestRootSupplier;
    }
}
项目:beam    文件:FnApiDoFnRunner.java   
private <T> BagUserState<T> createBagUserState(String id, Coder<T> coder) {
  BagUserState rval = new BagUserState<T>(
      beamFnStateClient,
      id,
      coder,
      new Supplier<StateRequest.Builder>() {
        /** Memoizes the partial state key for the lifetime of the {@link BagUserState}. */
        private final Supplier<StateKey.BagUserState> memoizingSupplier =
            Suppliers.memoize(() -> createOrUseCachedBagUserStateKey(id))::get;

        @Override
        public Builder get() {
          return StateRequest.newBuilder()
              .setInstructionReference(processBundleInstructionId.get())
              .setStateKey(StateKey.newBuilder()
                  .setBagUserState(memoizingSupplier.get()));
        }
      });
  stateFinalizers.add(rval::asyncClose);
  return rval;
}
项目:rules_closure    文件:WebfilesValidatorTest.java   
@Test
public void cyclicEdge_resultsInError() throws Exception {
  save(fs.getPath("/fs/path/index.html"), "<link rel=\"stylesheet\" href=\"index.css\">");
  save(fs.getPath("/fs/path/index.css"), "body { background: url(index.html); }");
  assertThat(
          validator.validate(
              Webfiles.newBuilder()
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.html")
                      .setWebpath("/web/path/index.html")
                      .build())
                  .addSrc(WebfilesSource.newBuilder()
                      .setPath("/fs/path/index.css")
                      .setWebpath("/web/path/index.css")
                      .build())
                  .build(),
              ImmutableList.<Webfiles>of(),
              Suppliers.ofInstance(ImmutableList.<Webfiles>of())))
      .containsEntry(
          WebfilesValidator.CYCLES_ERROR,
          "These webpaths are strongly connected; please make your html acyclic\n\n"
              + "  - /web/path/index.css\n"
              + "  - /web/path/index.html\n");
}
项目:beam    文件:BigQuerySourceBase.java   
List<BoundedSource<T>> createSources(List<ResourceId> files, TableSchema schema)
    throws IOException, InterruptedException {

  final String jsonSchema = BigQueryIO.JSON_FACTORY.toString(schema);
  SerializableFunction<GenericRecord, T> fnWrapper =
      new SerializableFunction<GenericRecord, T>() {
        private Supplier<TableSchema> schema = Suppliers.memoize(
            Suppliers.compose(new TableSchemaFunction(), Suppliers.ofInstance(jsonSchema)));

        @Override
        public T apply(GenericRecord input) {
          return parseFn.apply(new SchemaAndRecord(input, schema.get()));
        }
      };
  List<BoundedSource<T>> avroSources = Lists.newArrayList();
  for (ResourceId file : files) {
    avroSources.add(
        AvroSource.from(file.toString()).withParseFn(fnWrapper, getOutputCoder()));
  }
  return ImmutableList.copyOf(avroSources);
}
项目:guava-mock    文件:CacheBuilderSpecTest.java   
public void testMaximumWeight_withoutWeigher() {
  CacheBuilder<Object, Object> builder = CacheBuilder.from(parse("maximumWeight=9000"));
  try {
    builder.build(CacheLoader.from(Suppliers.ofInstance(null)));
    fail();
  } catch (IllegalStateException expected) {}
}
项目:guava-mock    文件:CacheBuilderSpecTest.java   
public void testDisableCaching() {
  // Functional test: assert that CacheBuilderSpec.disableCaching()
  // disables caching.  It's irrelevant how it does so.
  CacheBuilder<Object, Object> builder = CacheBuilder.from(CacheBuilderSpec.disableCaching());
  Object key = new Object();
  Object value = new Object();
  LoadingCache<Object, Object> cache = builder.build(
      CacheLoader.from(Suppliers.ofInstance(value)));
  assertSame(value, cache.getUnchecked(key));
  assertEquals(0, cache.size());
  assertFalse(cache.asMap().containsKey(key));
}
项目:guava-mock    文件:MoreExecutorsTest.java   
public void testThreadRenaming() {
  Executor renamingExecutor = renamingDecorator(newDirectExecutorService(),
      Suppliers.ofInstance("FooBar"));
  String oldName = Thread.currentThread().getName();
  renamingExecutor.execute(new Runnable() {
    @Override public void run() {
      assertEquals("FooBar", Thread.currentThread().getName());
    }});
  assertEquals(oldName, Thread.currentThread().getName());
}
项目:guava-mock    文件:CallablesTest.java   
@GwtIncompatible // threads
public void testRenaming() throws Exception {
  String oldName = Thread.currentThread().getName();
  final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
  Callable<Void> callable = new Callable<Void>() {
    @Override public Void call() throws Exception {
      assertEquals(Thread.currentThread().getName(), newName.get());
      return null;
    }
  };
  Callables.threadRenaming(callable, newName).call();
  assertEquals(oldName, Thread.currentThread().getName());
}
项目:Elasticsearch    文件:ShardSizeExpression.java   
@Inject
public ShardSizeExpression(final IndexShard indexShard) {
    sizeSupplier = Suppliers.memoizeWithExpiration(new Supplier<Long>() {
        @Override
        public Long get() {
            return indexShard.storeStats().getSizeInBytes();
        }
    }, 10, TimeUnit.SECONDS);
}