com.google.common.base.Suppliers Java Examples

The following examples show how to use com.google.common.base.Suppliers. 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: CompressedRefs.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public Collection<VcsRef> getRefs() {
  return new AbstractCollection<VcsRef>() {
    private final Supplier<Collection<VcsRef>> myLoadedRefs =
            Suppliers.memoize(() -> CompressedRefs.this.stream().collect(Collectors.toList()));

    @Nonnull
    @Override
    public Iterator<VcsRef> iterator() {
      return myLoadedRefs.get().iterator();
    }

    @Override
    public int size() {
      return myLoadedRefs.get().size();
    }
  };
}
 
Example #2
Source File: SchedulerTest.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public void testEarliestStartEarlierThanStartDate() {
  getTaskManager().getAlgorithmCollection().getRecalculateTaskScheduleAlgorithm().setEnabled(false);

  // start date on Mo, but earliest start is set to Fr (previous week).
  // task should be shifted backwards because there are no other constraints
  Task[] tasks = new Task[] {createTask(TestSetupHelper.newMonday())};
  tasks[0].setThirdDateConstraint(TaskImpl.EARLIESTBEGIN);
  tasks[0].setThirdDate(TestSetupHelper.newFriday());
  TaskDependency[] deps = new TaskDependency[0];
  DependencyGraph graph = createGraph(tasks, deps);

  SchedulerImpl scheduler = new SchedulerImpl(graph, Suppliers.ofInstance(getTaskManager().getTaskHierarchy()));
  scheduler.run();

  assertEquals(TestSetupHelper.newFriday(), tasks[0].getStart());
}
 
Example #3
Source File: DedupQueueTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@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.ofSeconds(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.ofSeconds(30), new SimpleEventSink(10));
    verifyNoMoreInteractions(readerDao);
}
 
Example #4
Source File: HybridEngineFactory.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
public HybridEngineFactory(List<String> wfPackges) {
    super(wfPackges);

    timeoutManager = Suppliers.memoize(new Supplier<TimeoutManager>() {
        @Override
        public TimeoutManager get() {
            logger.info("Creating TimeoutManager...");
            return createTimeoutManager();
        }
    });
    storage = Suppliers.memoize(new Supplier<Storage>() {
        @Override
        public Storage get() {
            logger.info("Creating Storage...");
            return createStorage();
        }
    });
}
 
Example #5
Source File: SchedulerTest.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public void testRhombus() throws Exception {
  getTaskManager().getAlgorithmCollection().getRecalculateTaskScheduleAlgorithm().setEnabled(false);
  Task[] tasks = new Task[] {
      createTask(TestSetupHelper.newMonday()), createTask(TestSetupHelper.newMonday()), createTask(TestSetupHelper.newMonday()),
      createTask(TestSetupHelper.newMonday()), createTask(TestSetupHelper.newMonday())};
  TaskDependency[] deps = new TaskDependency[] {
      createDependency(tasks[4], tasks[3]),
      createDependency(tasks[4], tasks[2]),
      createDependency(tasks[2], tasks[1]),
      createDependency(tasks[1], tasks[0]),
      createDependency(tasks[3], tasks[0])
  };
  DependencyGraph graph = createGraph(tasks, deps);
  SchedulerImpl scheduler = new SchedulerImpl(graph, Suppliers.ofInstance(getTaskManager().getTaskHierarchy()));
  scheduler.run();

  assertEquals(TestSetupHelper.newMonday(), tasks[0].getStart());
  assertEquals(TestSetupHelper.newTuesday(), tasks[1].getStart());
  assertEquals(TestSetupHelper.newTuesday(), tasks[3].getStart());
  assertEquals(TestSetupHelper.newWendesday(), tasks[2].getStart());
  assertEquals(TestSetupHelper.newThursday(), tasks[4].getStart());
}
 
Example #6
Source File: LocationTemplateContext.java    From bazel with Apache License 2.0 6 votes vote down vote up
public LocationTemplateContext(
    TemplateContext delegate,
    RuleContext ruleContext,
    @Nullable ImmutableMap<Label, ImmutableCollection<Artifact>> labelMap,
    boolean execPaths,
    boolean allowData,
    boolean windowsPath) {
  this(
      delegate,
      ruleContext.getLabel(),
      // Use a memoizing supplier to avoid eagerly building the location map.
      Suppliers.memoize(
          () -> LocationExpander.buildLocationMap(ruleContext, labelMap, allowData)),
      execPaths,
      ruleContext.getRule().getPackage().getRepositoryMapping(),
      windowsPath);
}
 
Example #7
Source File: UnitTestCassandraEngineFactory.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
public UnitTestCassandraEngineFactory(boolean truncate) {
    super(Arrays.asList("org.copperengine.core.persistent.cassandra.workflows"));
    this.truncate = truncate;

    backchannel = Suppliers.memoize(new Supplier<Backchannel>() {
        @Override
        public Backchannel get() {
            return new BackchannelDefaultImpl();
        }
    });
    dummyResponseSender = Suppliers.memoize(new Supplier<DummyResponseSender>() {
        @Override
        public DummyResponseSender get() {
            return new DummyResponseSender(scheduledExecutorService.get(), engine.get());
        }
    });
    dependencyInjector.get().register("dummyResponseSender", new Supplier2Provider<>(dummyResponseSender));
    dependencyInjector.get().register("backchannel", new Supplier2Provider<>(backchannel));
}
 
Example #8
Source File: ZabbixFeed.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected ZabbixFeed(final Builder<? extends ZabbixFeed, ?> builder) {
    setConfig(BASE_URI_PROVIDER, builder.baseUriProvider);
    if (builder.baseUri != null) {
        if (builder.baseUriProvider != null) {
            throw new IllegalStateException("Not permitted to supply baseUri and baseUriProvider");
        }
        setConfig(BASE_URI_PROVIDER, Suppliers.ofInstance(builder.baseUri));
    } else {
        setConfig(BASE_URI_PROVIDER, checkNotNull(builder.baseUriProvider, "baseUriProvider and baseUri"));
    }

    setConfig(GROUP_ID, checkNotNull(builder.groupId, "Zabbix groupId must be set"));
    setConfig(TEMPLATE_ID, checkNotNull(builder.templateId, "Zabbix templateId must be set"));
    setConfig(UNIQUE_HOSTNAME_GENERATOR, checkNotNull(builder.uniqueHostnameGenerator, "uniqueHostnameGenerator"));

    Set<ZabbixPollConfig<?>> polls = Sets.newLinkedHashSet();
    for (ZabbixPollConfig<?> config : builder.polls) {
        if (!config.isEnabled()) continue;
        @SuppressWarnings({ "unchecked", "rawtypes" })
        ZabbixPollConfig<?> configCopy = new ZabbixPollConfig(config);
        if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits);
        polls.add(configCopy);
    }
    setConfig(POLLS, polls);
    initUniqueTag(builder.uniqueTag, polls);
}
 
Example #9
Source File: GitRevisionHistoryTest.java    From MOE with Apache License 2.0 6 votes vote down vote up
public void testFindHighestRevision_nonExistentHashThrows() throws Exception {
  GitClonedRepository mockRepo = mockClonedRepo(repositoryName);

  expectLogCommand(mockRepo, LOG_FORMAT_COMMIT_ID, "bogusHash")
      .andThrow(
          new CommandException(
              "git",
              ImmutableList.<String>of("mock args"),
              "mock stdout",
              "mock stderr: unknown revision",
              1));

  control.replay();

  try {
    GitRevisionHistory rh = new GitRevisionHistory(Suppliers.ofInstance(mockRepo));
    rh.findHighestRevision("bogusHash");
    fail("'git log' didn't fail on bogus hash ID");
  } catch (MoeProblem expected) {
  }

  control.verify();
}
 
Example #10
Source File: LoadTestCassandraEngineFactory.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
public LoadTestCassandraEngineFactory() {
    super(Arrays.asList("org.copperengine.core.persistent.cassandra.loadtest.workflows"));
    super.setCassandraHosts(Arrays.asList("nuc1.scoop-gmbh.de"));

    backchannel = Suppliers.memoize(new Supplier<Backchannel>() {
        @Override
        public Backchannel get() {
            return new BackchannelDefaultImpl();
        }
    });
    dummyResponseSender = Suppliers.memoize(new Supplier<DummyResponseSender>() {
        @Override
        public DummyResponseSender get() {
            return new DummyResponseSender(scheduledExecutorService.get(), engine.get());
        }
    });
    dependencyInjector.get().register("dummyResponseSender", new Supplier2Provider<>(dummyResponseSender));
    dependencyInjector.get().register("backchannel", new Supplier2Provider<>(backchannel));
}
 
Example #11
Source File: ItemController.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Autowired
public ItemController(ItemService itemService)
{
	this.itemService = itemService;

	memoizedPrices = Suppliers.memoizeWithExpiration(() -> new MemoizedPrices(itemService.fetchPrices().stream()
		.map(priceEntry ->
		{
			ItemPrice itemPrice = new ItemPrice();
			itemPrice.setId(priceEntry.getItem());
			itemPrice.setName(priceEntry.getName());
			itemPrice.setPrice(priceEntry.getPrice());
			itemPrice.setTime(priceEntry.getTime());
			return itemPrice;
		})
		.toArray(ItemPrice[]::new)), 30, TimeUnit.MINUTES);
}
 
Example #12
Source File: StubInstance.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
Write getWrite(
    String resourceName, long expectedSize, boolean autoflush, RequestMetadata requestMetadata) {
  return new StubWriteOutputStream(
      () ->
          deadlined(bsBlockingStub).withInterceptors(attachMetadataInterceptor(requestMetadata)),
      Suppliers.memoize(
          () ->
              ByteStreamGrpc.newStub(channel)
                  .withInterceptors(
                      attachMetadataInterceptor(
                          requestMetadata))), // explicitly avoiding deadline due to client
      // cancellation determination
      resourceName,
      expectedSize,
      autoflush);
}
 
Example #13
Source File: QueueModule.java    From emodb with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example #14
Source File: VHUPackingInfo.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
VHUPackingInfo(final I_M_HU vhu)
{
	Check.assumeNotNull(vhu, "Parameter vhu is not null");
	huProductStorageSupplier = Suppliers.memoize(() -> {
		final List<IHUProductStorage> productStorages = Services.get(IHandlingUnitsBL.class)
				.getStorageFactory()
				.getStorage(vhu)
				.getProductStorages();
		if (productStorages.size() == 1)
		{
			return productStorages.get(0);
		}
		else
		{
			return null;
		}
	});
}
 
Example #15
Source File: DashboardResource.java    From breakerbox with Apache License 2.0 6 votes vote down vote up
public DashboardResource(String defaultDashboard,
                         HostAndPort breakerboxHostAndPort,
                         Set<String> specifiedMetaClusters) {
    this.defaultDashboard = defaultDashboard;
    this.breakerboxHostAndPort = breakerboxHostAndPort;
    this.specifiedMetaClusters = specifiedMetaClusters;
    indexSupplier = Suppliers.memoize(
            () -> {
                try {
                    return Resources.asByteSource(Resources.getResource("index.html"))
                            .read();
                } catch (IOException err) {
                    throw new IllegalStateException(err);
                }
            });
}
 
Example #16
Source File: HgRevisionHistoryTest.java    From MOE with Apache License 2.0 6 votes vote down vote up
public void testFindHeadRevisions() throws Exception {
  HgClonedRepository mockRepo = mockClonedRepo(MOCK_REPO_NAME);

  expect(
          cmd.runCommand(
              CLONE_TEMP_DIR,
              "hg",
              ImmutableList.of("heads", "mybranch", "--template={node} {branch}\n")))
      .andReturn("mockChangesetID1 branch1\nmockChangesetID2 branch2\nmockChangesetID3 unused");

  control.replay();

  HgRevisionHistory rh = new HgRevisionHistory(cmd, HG_CMD, Suppliers.ofInstance(mockRepo));
  ImmutableList<Revision> revs = ImmutableList.copyOf(rh.findHeadRevisions());
  assertEquals(MOCK_REPO_NAME, revs.get(0).repositoryName());
  assertEquals("mockChangesetID1", revs.get(0).revId());
  assertEquals(MOCK_REPO_NAME, revs.get(1).repositoryName());
  assertEquals("mockChangesetID2", revs.get(1).revId());

  control.verify();
}
 
Example #17
Source File: JsonConfigProvider.java    From druid-api with Apache License 2.0 6 votes vote down vote up
@Override
public Supplier<T> get()
{
  if (retVal != null) {
    return retVal;
  }

  try {
    final T config = configurator.configurate(props, propertyBase, classToProvide);
    retVal = Suppliers.ofInstance(config);
  }
  catch (RuntimeException e) {
    // When a runtime exception gets thrown out, this provider will get called again if the object is asked for again.
    // This will have the same failed result, 'cause when it's called no parameters will have actually changed.
    // Guice will then report the same error multiple times, which is pretty annoying. Cache a null supplier and
    // return that instead.  This is technically enforcing a singleton, but such is life.
    retVal = Suppliers.ofInstance(null);
    throw e;
  }
  return retVal;
}
 
Example #18
Source File: AstyanaxTableDAO.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<Map.Entry<String, MaintenanceOp>> listMaintenanceOps() {
    final Iterator<Map<String, Object>> tableIter =
            _backingStore.scan(_systemTable, null, LimitCounter.max(), ReadConsistency.STRONG);
    final Supplier<List<TableEventDatacenter>> tableEventDatacenterSupplier = Suppliers.memoize(this::getTableEventDatacenters);
    return new AbstractIterator<Map.Entry<String, MaintenanceOp>>() {
        @Override
        protected Map.Entry<String, MaintenanceOp> computeNext() {
            while (tableIter.hasNext()) {
                TableJson json = new TableJson(tableIter.next());
                MaintenanceOp op = getNextMaintenanceOp(json, false/*don't expose task outside this class*/, tableEventDatacenterSupplier);
                if (op != null) {
                    return Maps.immutableEntry(json.getTable(), op);
                }
            }
            return endOfData();
        }
    };
}
 
Example #19
Source File: DefaultDataCenters.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public void refresh() {
    _cache = Suppliers.memoizeWithExpiration(new Supplier<CachedInfo>() {
        @Override
        public CachedInfo get() {
            Map<String, DataCenter> dataCenters = _dataCenterDao.loadAll();
            if (!_ignoredDataCenters.isEmpty()) {
                ImmutableMap.Builder<String, DataCenter> dataCentersBuilder = ImmutableMap.builder();
                for (Map.Entry<String, DataCenter> entry : dataCenters.entrySet()) {
                    if (!_ignoredDataCenters.contains(entry.getKey())) {
                        dataCentersBuilder.put(entry);
                    } else if (_loggedIgnored.add(entry.getKey())) {
                        // Only want to log that we're ignoring the data center once
                        _log.info("Ignoring data center: {}", entry.getKey());
                    }
                }
                dataCenters = dataCentersBuilder.build();
            }
            return new CachedInfo(dataCenters);
        }
    }, 10, TimeUnit.MINUTES);
}
 
Example #20
Source File: MySqlClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
protected EntitySpec<?> getFirstMemberSpec() {
    final EntitySpec<?> firstMemberSpec = super.getFirstMemberSpec();
    if (firstMemberSpec != null) {
        return applyDefaults(firstMemberSpec, Suppliers.ofInstance(MASTER_SERVER_ID), MASTER_CONFIG_URL);
    }

    final EntitySpec<?> memberSpec = super.getMemberSpec();
    if (memberSpec != null) {
        return applyDefaults(memberSpec, Suppliers.ofInstance(MASTER_SERVER_ID), MASTER_CONFIG_URL);
    }

    return EntitySpec.create(MySqlNode.class)
            .displayName("MySql Master")
            .configure(MySqlNode.MYSQL_SERVER_ID, MASTER_SERVER_ID)
            .configure(MySqlNode.TEMPLATE_CONFIGURATION_URL, MASTER_CONFIG_URL);
}
 
Example #21
Source File: TransactionalTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testBatchTransactional() throws Exception {
  UnitOfWork.beginBatch(Suppliers.ofInstance(session));
  try {
    methods.transactional();
    methods.transactional();
    methods.transactional();
  }
  finally {
    UnitOfWork.end();
  }

  InOrder order = inOrder(session, tx);
  order.verify(session).getTransaction();
  order.verify(tx).reason(DEFAULT_REASON);
  order.verify(tx).begin();
  order.verify(tx).commit();
  order.verify(session).getTransaction();
  order.verify(tx).isActive();
  order.verify(tx).reason(DEFAULT_REASON);
  order.verify(tx).begin();
  order.verify(tx).commit();
  order.verify(session).getTransaction();
  order.verify(tx).isActive();
  order.verify(tx).reason(DEFAULT_REASON);
  order.verify(tx).begin();
  order.verify(tx).commit();
  order.verify(session).close();
  verifyNoMoreInteractions(session, tx);
}
 
Example #22
Source File: JpaTransactionManagerRule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public void before() throws Exception {
  if (entityHash == emfEntityHash) {
    checkState(emf != null, "Missing EntityManagerFactory.");
    resetTablesAndSequences();
  } else {
    recreateSchema();
  }
  JpaTransactionManagerImpl txnManager = new JpaTransactionManagerImpl(emf, clock);
  cachedTm = TransactionManagerFactory.jpaTm();
  TransactionManagerFactory.setJpaTm(Suppliers.ofInstance(txnManager));
}
 
Example #23
Source File: ChaosHttpProxyTest.java    From chaos-http-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpPostPartialData() throws Exception {
    int contentLength = 65536 + 1;
    proxy.setFailureSupplier(Suppliers.ofInstance(
            Failure.PARTIAL_REQUEST));
    ContentResponse response = client.POST(httpBinEndpoint + "/post")
            .content(new BytesContentProvider(new byte[contentLength]))
            .send();
    assertThat(response.getContent().length).isNotEqualTo(contentLength);
}
 
Example #24
Source File: NoDxArgsHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
static Supplier<ImmutableSet<JavaLibrary>> createSupplierForRulesToExclude(
    ActionGraphBuilder graphBuilder,
    BuildTarget buildTarget,
    ImmutableSet<BuildTarget> noDxTargets) {
  return Suppliers.memoize(
      () -> findRulesToExcludeFromDex(graphBuilder, buildTarget, noDxTargets));
}
 
Example #25
Source File: EventStoreModuleTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventStoreModule() {
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            binder().requireExplicitBindings();

            bind(ChannelConfiguration.class).toInstance(mock(ChannelConfiguration.class));
            bind(CassandraKeyspace.class).toInstance(mock(CassandraKeyspace.class));
            bind(LeaderServiceTask.class).toInstance(mock(LeaderServiceTask.class));
            bind(LifeCycleRegistry.class).toInstance(new SimpleLifeCycleRegistry());
            bind(TaskRegistry.class).toInstance(mock(TaskRegistry.class));
            bind(HostAndPort.class).annotatedWith(SelfHostAndPort.class).toInstance(HostAndPort.fromString("localhost:8080"));
            bind(CuratorFramework.class).annotatedWith(EventStoreZooKeeper.class).toInstance(mock(CuratorFramework.class));
            bind(HostDiscovery.class).annotatedWith(EventStoreHostDiscovery.class).toInstance(mock(HostDiscovery.class));
            bind(DedupEventStoreChannels.class).toInstance(DedupEventStoreChannels.isolated(":__dedupq_write", ":__dedupq_read"));
            bind(new TypeLiteral<Supplier<Boolean>>() {}).annotatedWith(DedupEnabled.class).toInstance(Suppliers.ofInstance(true));

            MetricRegistry metricRegistry = new MetricRegistry();
            bind(MetricRegistry.class).toInstance(metricRegistry);

            install(new EventStoreModule("bv.event", metricRegistry));
        }
    });

    EventStore eventStore = injector.getInstance(EventStore.class);

    assertNotNull(eventStore);

    // Verify that some things we expect to be private are, indeed, private
    assertPrivate(injector, AstyanaxEventReaderDAO.class);
    assertPrivate(injector, AstyanaxManifestPersister.class);
    assertPrivate(injector, DefaultSlabAllocator.class);
    assertPrivate(injector, DefaultClaimStore.class);
}
 
Example #26
Source File: GitRevisionHistoryTest.java    From MOE with Apache License 2.0 5 votes vote down vote up
public void testFindNewRevisions_all() throws Exception {
  GitClonedRepository mockRepo = mockClonedRepo(repositoryName);
  mockFindHeadRevisions(mockRepo);
  DummyDb db = new DummyDb(false, null);

  // Breadth-first search order.
  expectLogCommandIgnoringMissing(mockRepo, LOG_FORMAT_ALL_METADATA, "head")
      .andReturn(
          METADATA_JOINER.join(
              "head", "[email protected]", GIT_COMMIT_DATE, "parent1 parent2", "description"));

  expectLogCommandIgnoringMissing(mockRepo, LOG_FORMAT_ALL_METADATA, "parent1")
      .andReturn(
          METADATA_JOINER.join("parent1", "[email protected]", GIT_COMMIT_DATE, "", "description"));

  expectLogCommandIgnoringMissing(mockRepo, LOG_FORMAT_ALL_METADATA, "parent2")
      .andReturn(
          METADATA_JOINER.join("parent2", "[email protected]", GIT_COMMIT_DATE, "", "description"));

  control.replay();

  GitRevisionHistory rh = new GitRevisionHistory(Suppliers.ofInstance(mockRepo));
  List<Revision> newRevisions =
      rh.findRevisions(null, new RepositoryEquivalenceMatcher("mockRepo", db), BRANCHED)
          .getRevisionsSinceEquivalence()
          .getBreadthFirstHistory();

  assertThat(newRevisions).hasSize(3);
  assertEquals(repositoryName, newRevisions.get(0).repositoryName());
  assertEquals("head", newRevisions.get(0).revId());
  assertEquals(repositoryName, newRevisions.get(1).repositoryName());
  assertEquals("parent1", newRevisions.get(1).revId());
  assertEquals(repositoryName, newRevisions.get(2).repositoryName());
  assertEquals("parent2", newRevisions.get(2).revId());

  control.verify();
}
 
Example #27
Source File: DepositStorage.java    From teku with Apache License 2.0 5 votes vote down vote up
private DepositStorage(
    final Eth1EventsChannel eth1EventsChannel,
    final Database database,
    final boolean eth1DepositsFromStorageEnabled) {
  this.eth1EventsChannel = eth1EventsChannel;
  this.database = database;
  this.replayResult = Suppliers.memoize(() -> SafeFuture.of(this::replayDeposits));
  this.eth1DepositsFromStorageEnabled = eth1DepositsFromStorageEnabled;
}
 
Example #28
Source File: FirebaseMessagingTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendAllAsyncFailure() throws InterruptedException {
  MockFirebaseMessagingClient client = MockFirebaseMessagingClient.fromException(TEST_EXCEPTION);
  FirebaseMessaging messaging = getMessagingForSend(Suppliers.ofInstance(client));
  ImmutableList<Message> messages = ImmutableList.of(EMPTY_MESSAGE);

  try {
    messaging.sendAllAsync(messages).get();
  } catch (ExecutionException e) {
    assertSame(TEST_EXCEPTION, e.getCause());
  }

  assertSame(messages, client.lastBatch);
  assertFalse(client.isLastDryRun);
}
 
Example #29
Source File: PackageableRowsRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public PackageableRowsRepository(@NonNull final MoneyService moneyService)
{
	this.moneyService = moneyService;

	// creating those LookupDataSources requires DB access. So, to allow this component to be initialized early during startup
	// and also to allow it to be unit-tested (when the lookups are not part of the test), I use those suppliers.
	bpartnerLookup = Suppliers.memoize(() -> LookupDataSourceFactory.instance.searchInTableLookup(I_C_BPartner.Table_Name));
	shipperLookup = Suppliers.memoize(() -> LookupDataSourceFactory.instance.searchInTableLookup(I_M_Shipper.Table_Name));
	userLookup = Suppliers.memoize(() -> LookupDataSourceFactory.instance.searchInTableLookup(I_AD_User.Table_Name));
}
 
Example #30
Source File: FirebaseMessagingTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscribeToTopicFailure() {
  MockInstanceIdClient client = MockInstanceIdClient.fromException(TEST_EXCEPTION);
  FirebaseMessaging messaging = getMessagingForTopicManagement(Suppliers.ofInstance(client));

  try {
    messaging.subscribeToTopic(ImmutableList.of("id1", "id2"), "test-topic");
  } catch (FirebaseMessagingException e) {
    assertSame(TEST_EXCEPTION, e);
  }
}