@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()); }
@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); } }
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(); } }); }
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); } }); }
@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); }
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); }
/** * 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); }
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}} }
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); } }); }
@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(); }
@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)); }
@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"); }
@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"); }
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; } }); }
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; } }); }
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(); }
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; } }); }
/** 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()); }
@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; } } ); }
@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"))); }
@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"); }
@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); }
@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); }
@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); }
@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(); }
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; } } })); }
@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(); }
@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); }
@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."); }
@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; } }
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; }
@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"); }
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); }
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) {} }
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)); }
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()); }
@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()); }
@Inject public ShardSizeExpression(final IndexShard indexShard) { sizeSupplier = Suppliers.memoizeWithExpiration(new Supplier<Long>() { @Override public Long get() { return indexShard.storeStats().getSizeInBytes(); } }, 10, TimeUnit.SECONDS); }